imap_folder_agent.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. require 'delegate'
  2. require 'net/imap'
  3. require 'mail'
  4. module Agents
  5. class ImapFolderAgent < Agent
  6. cannot_receive_events!
  7. can_dry_run!
  8. default_schedule "every_30m"
  9. description <<-MD
  10. The Imap Folder Agent checks an IMAP server in specified folders and creates Events based on new mails found since the last run. In the first visit to a folder, this agent only checks for the initial status and does not create events.
  11. Specify an IMAP server to connect with `host`, and set `ssl` to true if the server supports IMAP over SSL. Specify `port` if you need to connect to a port other than standard (143 or 993 depending on the `ssl` value).
  12. Specify login credentials in `username` and `password`.
  13. List the names of folders to check in `folders`.
  14. To narrow mails by conditions, build a `conditions` hash with the following keys:
  15. - `subject`
  16. - `body`
  17. Specify a regular expression to match against the decoded subject/body of each mail.
  18. Use the `(?i)` directive for case-insensitive search. For example, a pattern `(?i)alert` will match "alert", "Alert"or "ALERT". You can also make only a part of a pattern to work case-insensitively: `Re: (?i:alert)` will match either "Re: Alert" or "Re: alert", but not "RE: alert".
  19. When a mail has multiple non-attachment text parts, they are prioritized according to the `mime_types` option (which see below) and the first part that matches a "body" pattern, if specified, will be chosen as the "body" value in a created event.
  20. Named captures will appear in the "matches" hash in a created event.
  21. - `from`, `to`, `cc`
  22. Specify a shell glob pattern string that is matched against mail addresses extracted from the corresponding header values of each mail.
  23. Patterns match addresses in case insensitive manner.
  24. Multiple pattern strings can be specified in an array, in which case a mail is selected if any of the patterns matches. (i.e. patterns are OR'd)
  25. - `mime_types`
  26. Specify an array of MIME types to tell which non-attachment part of a mail among its text/* parts should be used as mail body. The default value is `['text/plain', 'text/enriched', 'text/html']`.
  27. - `is_unread`
  28. Setting this to true or false means only mails that is marked as unread or read respectively, are selected.
  29. If this key is unspecified or set to null, it is ignored.
  30. - `has_attachment`
  31. Setting this to true or false means only mails that does or does not have an attachment are selected.
  32. If this key is unspecified or set to null, it is ignored.
  33. Set `mark_as_read` to true to mark found mails as read.
  34. Each agent instance memorizes the highest UID of mails that are found in the last run for each watched folder, so even if you change a set of conditions so that it matches mails that are missed previously, or if you alter the flag status of already found mails, they will not show up as new events.
  35. Also, in order to avoid duplicated notification it keeps a list of Message-Id's of 100 most recent mails, so if multiple mails of the same Message-Id are found, you will only see one event out of them.
  36. MD
  37. event_description <<-MD
  38. Events look like this:
  39. {
  40. "folder": "INBOX",
  41. "subject": "...",
  42. "from": "Nanashi <nanashi.gombeh@example.jp>",
  43. "to": ["Jane <jane.doe@example.com>"],
  44. "cc": [],
  45. "date": "2014-05-10T03:47:20+0900",
  46. "mime_type": "text/plain",
  47. "body": "Hello,\n\n...",
  48. "matches": {
  49. }
  50. }
  51. MD
  52. IDCACHE_SIZE = 100
  53. FNM_FLAGS = [:FNM_CASEFOLD, :FNM_EXTGLOB].inject(0) { |flags, sym|
  54. if File.const_defined?(sym)
  55. flags | File.const_get(sym)
  56. else
  57. flags
  58. end
  59. }
  60. def working?
  61. event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
  62. end
  63. def default_options
  64. {
  65. 'expected_update_period_in_days' => "1",
  66. 'host' => 'imap.gmail.com',
  67. 'ssl' => true,
  68. 'username' => 'your.account',
  69. 'password' => 'your.password',
  70. 'folders' => %w[INBOX],
  71. 'conditions' => {}
  72. }
  73. end
  74. def validate_options
  75. %w[host username password].each { |key|
  76. String === options[key] or
  77. errors.add(:base, '%s is required and must be a string' % key)
  78. }
  79. if options['port'].present?
  80. errors.add(:base, "port must be a positive integer") unless is_positive_integer?(options['port'])
  81. end
  82. %w[ssl mark_as_read].each { |key|
  83. if options[key].present?
  84. if boolify(options[key]).nil?
  85. errors.add(:base, '%s must be a boolean value' % key)
  86. end
  87. end
  88. }
  89. case mime_types = options['mime_types']
  90. when nil
  91. when Array
  92. mime_types.all? { |mime_type|
  93. String === mime_type && mime_type.start_with?('text/')
  94. } or errors.add(:base, 'mime_types may only contain strings that match "text/*".')
  95. if mime_types.empty?
  96. errors.add(:base, 'mime_types should not be empty')
  97. end
  98. else
  99. errors.add(:base, 'mime_types must be an array')
  100. end
  101. case folders = options['folders']
  102. when nil
  103. when Array
  104. folders.all? { |folder|
  105. String === folder
  106. } or errors.add(:base, 'folders may only contain strings')
  107. if folders.empty?
  108. errors.add(:base, 'folders should not be empty')
  109. end
  110. else
  111. errors.add(:base, 'folders must be an array')
  112. end
  113. case conditions = options['conditions']
  114. when Hash
  115. conditions.each { |key, value|
  116. value.present? or next
  117. case key
  118. when 'subject', 'body'
  119. case value
  120. when String
  121. begin
  122. Regexp.new(value)
  123. rescue
  124. errors.add(:base, 'conditions.%s contains an invalid regexp' % key)
  125. end
  126. else
  127. errors.add(:base, 'conditions.%s contains a non-string object' % key)
  128. end
  129. when 'from', 'to', 'cc'
  130. Array(value).each { |pattern|
  131. case pattern
  132. when String
  133. begin
  134. glob_match?(pattern, '')
  135. rescue
  136. errors.add(:base, 'conditions.%s contains an invalid glob pattern' % key)
  137. end
  138. else
  139. errors.add(:base, 'conditions.%s contains a non-string object' % key)
  140. end
  141. }
  142. when 'is_unread', 'has_attachment'
  143. case boolify(value)
  144. when true, false
  145. else
  146. errors.add(:base, 'conditions.%s must be a boolean value or null' % key)
  147. end
  148. end
  149. }
  150. else
  151. errors.add(:base, 'conditions must be a hash')
  152. end
  153. if options['expected_update_period_in_days'].present?
  154. errors.add(:base, "Invalid expected_update_period_in_days format") unless is_positive_integer?(options['expected_update_period_in_days'])
  155. end
  156. end
  157. def check
  158. each_unread_mail { |mail, notified|
  159. message_id = mail.message_id
  160. body_parts = mail.body_parts(mime_types)
  161. matched_part = nil
  162. matches = {}
  163. interpolated['conditions'].all? { |key, value|
  164. case key
  165. when 'subject'
  166. value.present? or next true
  167. re = Regexp.new(value)
  168. if m = re.match(mail.scrubbed(:subject))
  169. m.names.each { |name|
  170. matches[name] = m[name]
  171. }
  172. true
  173. else
  174. false
  175. end
  176. when 'body'
  177. value.present? or next true
  178. re = Regexp.new(value)
  179. matched_part = body_parts.find { |part|
  180. if m = re.match(part.scrubbed(:decoded))
  181. m.names.each { |name|
  182. matches[name] = m[name]
  183. }
  184. true
  185. else
  186. false
  187. end
  188. }
  189. when 'from', 'to', 'cc'
  190. value.present? or next true
  191. mail.header[key].addresses.any? { |address|
  192. Array(value).any? { |pattern|
  193. glob_match?(pattern, address)
  194. }
  195. }
  196. when 'has_attachment'
  197. boolify(value) == mail.has_attachment?
  198. when 'is_unread'
  199. true # already filtered out by each_unread_mail
  200. else
  201. log 'Unknown condition key ignored: %s' % key
  202. true
  203. end
  204. } or next
  205. if notified.include?(mail.message_id)
  206. log 'Ignoring mail: %s (already notified)' % message_id
  207. else
  208. matched_part ||= body_parts.first
  209. if matched_part
  210. mime_type = matched_part.mime_type
  211. body = matched_part.scrubbed(:decoded)
  212. else
  213. mime_type = 'text/plain'
  214. body = ''
  215. end
  216. log 'Emitting an event for mail: %s' % message_id
  217. create_event :payload => {
  218. 'folder' => mail.folder,
  219. 'subject' => mail.scrubbed(:subject),
  220. 'from' => mail.from_addrs.first,
  221. 'to' => mail.to_addrs,
  222. 'cc' => mail.cc_addrs,
  223. 'date' => (mail.date.iso8601 rescue nil),
  224. 'mime_type' => mime_type,
  225. 'body' => body,
  226. 'matches' => matches,
  227. 'has_attachment' => mail.has_attachment?,
  228. }
  229. notified << mail.message_id if mail.message_id
  230. end
  231. if boolify(interpolated['mark_as_read'])
  232. log 'Marking as read'
  233. mail.mark_as_read unless dry_run?
  234. end
  235. }
  236. end
  237. def each_unread_mail
  238. host, port, ssl, username = interpolated.values_at(:host, :port, :ssl, :username)
  239. ssl = boolify(ssl)
  240. port = (Integer(port) if port.present?)
  241. log "Connecting to #{host}#{':%d' % port if port}#{' via SSL' if ssl}"
  242. Client.open(host, port: port, ssl: ssl) { |imap|
  243. log "Logging in as #{username}"
  244. imap.login(username, interpolated[:password])
  245. # 'lastseen' keeps a hash of { uidvalidity => lastseenuid, ... }
  246. lastseen, seen = self.lastseen, self.make_seen
  247. # 'notified' keeps an array of message-ids of {IDCACHE_SIZE}
  248. # most recent notified mails.
  249. notified = self.notified
  250. interpolated['folders'].each { |folder|
  251. log "Selecting the folder: %s" % folder
  252. imap.select(folder)
  253. uidvalidity = imap.uidvalidity
  254. lastseenuid = lastseen[uidvalidity]
  255. if lastseenuid.nil?
  256. maxseq = imap.responses['EXISTS'].last
  257. log "Recording the initial status: %s" % pluralize(maxseq, 'existing mail')
  258. if maxseq > 0
  259. seen[uidvalidity] = imap.fetch(maxseq, 'UID').last.attr['UID']
  260. end
  261. next
  262. end
  263. seen[uidvalidity] = lastseenuid
  264. is_unread = boolify(interpolated['conditions']['is_unread'])
  265. uids = imap.uid_fetch((lastseenuid + 1)..-1, 'FLAGS').
  266. each_with_object([]) { |data, ret|
  267. uid, flags = data.attr.values_at('UID', 'FLAGS')
  268. seen[uidvalidity] = uid
  269. next if uid <= lastseenuid
  270. case is_unread
  271. when nil, !flags.include?(:Seen)
  272. ret << uid
  273. end
  274. }
  275. log pluralize(uids.size,
  276. case is_unread
  277. when true
  278. 'new unread mail'
  279. when false
  280. 'new read mail'
  281. else
  282. 'new mail'
  283. end)
  284. next if uids.empty?
  285. imap.uid_fetch_mails(uids).each { |mail|
  286. yield mail, notified
  287. }
  288. }
  289. self.notified = notified
  290. self.lastseen = seen
  291. save!
  292. }
  293. ensure
  294. log 'Connection closed'
  295. end
  296. def mime_types
  297. interpolated['mime_types'] || %w[text/plain text/enriched text/html]
  298. end
  299. def lastseen
  300. Seen.new(memory['lastseen'])
  301. end
  302. def lastseen= value
  303. memory.delete('seen') # obsolete key
  304. memory['lastseen'] = value
  305. end
  306. def make_seen
  307. Seen.new
  308. end
  309. def notified
  310. Notified.new(memory['notified'])
  311. end
  312. def notified= value
  313. memory['notified'] = value
  314. end
  315. private
  316. def is_positive_integer?(value)
  317. Integer(value) >= 0
  318. rescue
  319. false
  320. end
  321. def glob_match?(pattern, value)
  322. File.fnmatch?(pattern, value, FNM_FLAGS)
  323. end
  324. def pluralize(count, noun)
  325. "%d %s" % [count, noun.pluralize(count)]
  326. end
  327. class Client < ::Net::IMAP
  328. class << self
  329. def open(host, *args)
  330. imap = new(host, *args)
  331. yield imap
  332. ensure
  333. imap.disconnect unless imap.nil?
  334. end
  335. end
  336. attr_reader :uidvalidity
  337. def select(folder)
  338. ret = super(@folder = folder)
  339. @uidvalidity = responses['UIDVALIDITY'].last
  340. ret
  341. end
  342. def fetch(*args)
  343. super || []
  344. end
  345. def uid_fetch(*args)
  346. super || []
  347. end
  348. def uid_fetch_mails(set)
  349. uid_fetch(set, 'RFC822.HEADER').map { |data|
  350. Message.new(self, data, folder: @folder, uidvalidity: @uidvalidity)
  351. }
  352. end
  353. end
  354. class Seen < Hash
  355. def initialize(hash = nil)
  356. super()
  357. if hash
  358. # Deserialize a JSON hash which keys are strings
  359. hash.each { |uidvalidity, uid|
  360. self[uidvalidity.to_i] = uid
  361. }
  362. end
  363. end
  364. def []=(uidvalidity, uid)
  365. # Update only if the new value is larger than the current value
  366. if (curr = self[uidvalidity]).nil? || curr <= uid
  367. super
  368. end
  369. end
  370. end
  371. class Notified < Array
  372. def initialize(array = nil)
  373. super()
  374. replace(array) if array
  375. end
  376. def <<(value)
  377. slice!(0...-IDCACHE_SIZE) if size > IDCACHE_SIZE
  378. super
  379. end
  380. end
  381. class Message < SimpleDelegator
  382. DEFAULT_BODY_MIME_TYPES = %w[text/plain text/enriched text/html]
  383. attr_reader :uid, :folder, :uidvalidity
  384. module Scrubbed
  385. def scrubbed(method)
  386. (@scrubbed ||= {})[method.to_sym] ||=
  387. __send__(method).try(:scrub) { |bytes| "<#{bytes.unpack('H*')[0]}>" }
  388. end
  389. end
  390. include Scrubbed
  391. def initialize(client, fetch_data, props = {})
  392. @client = client
  393. props.each { |key, value|
  394. instance_variable_set(:"@#{key}", value)
  395. }
  396. attr = fetch_data.attr
  397. @uid = attr['UID']
  398. super(Mail.read_from_string(attr['RFC822.HEADER']))
  399. end
  400. def has_attachment?
  401. @has_attachment ||=
  402. if data = @client.uid_fetch(@uid, 'BODYSTRUCTURE').first
  403. struct_has_attachment?(data.attr['BODYSTRUCTURE'])
  404. else
  405. false
  406. end
  407. end
  408. def fetch
  409. @parsed ||=
  410. if data = @client.uid_fetch(@uid, 'BODY.PEEK[]').first
  411. Mail.read_from_string(data.attr['BODY[]'])
  412. else
  413. Mail.read_from_string('')
  414. end
  415. end
  416. def body_parts(mime_types = DEFAULT_BODY_MIME_TYPES)
  417. mail = fetch
  418. if mail.multipart?
  419. mail.body.set_sort_order(mime_types)
  420. mail.body.sort_parts!
  421. mail.all_parts
  422. else
  423. [mail]
  424. end.select { |part|
  425. if part.multipart? || part.attachment? || !part.text? ||
  426. !mime_types.include?(part.mime_type)
  427. false
  428. else
  429. part.extend(Scrubbed)
  430. true
  431. end
  432. }
  433. end
  434. def mark_as_read
  435. @client.uid_store(@uid, '+FLAGS', [:Seen])
  436. end
  437. private
  438. def struct_has_attachment?(struct)
  439. struct.multipart? && (
  440. struct.subtype == 'MIXED' ||
  441. struct.parts.any? { |part|
  442. struct_has_attachment?(part)
  443. }
  444. )
  445. end
  446. end
  447. end
  448. end