Advertisement
Guest User

Untitled

a guest
Nov 27th, 2015
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. import subprocess
  4. import sys
  5. import tempfile
  6.  
  7. def main():
  8. with subprocess.Popen(['doveadm', 'user', '*'], stdout=subprocess.PIPE) as p:
  9. for line in p.stdout:
  10. process(line[:-1]) # strip final newline
  11.  
  12. def process(user):
  13. kw = 'answered-learned-ham'
  14.  
  15. class parser(base_parser):
  16. def learn(self):
  17. r = subprocess.call(['spamc', '-s', str(2*2**20), '-u', user, '-L', 'ham'], stdin=self.file.fileno())
  18. if r == 0:
  19. subprocess.check_call(['doveadm', 'flags', 'add', '-u', user, kw, 'mailbox-guid', self.mailbox_guid, 'uid', self.uid])
  20.  
  21. with subprocess.Popen(
  22. ['doveadm', 'fetch', '-u', user, 'mailbox-guid uid text', 'ANSWERED', 'NOT', 'KEYWORD', kw],
  23. stdout=subprocess.PIPE
  24. ) as proc:
  25. par = parser()
  26. for line in proc.stdout:
  27. par.process_line(line)
  28.  
  29. class base_parser:
  30. def __init__(self):
  31. self.__reset()
  32.  
  33. def process_line(self, line):
  34. if self.__state == 0:
  35. self.__read_field(line)
  36. elif self.__state == 1:
  37. self.__read_message(line)
  38. else:
  39. raise Exception('Invalid state {}', self.__state)
  40.  
  41. def __read_field(self, line):
  42. if line.startswith(b'mailbox-guid:'):
  43. self.mailbox_guid = line.split()[1]
  44. elif line.startswith(b'uid:'):
  45. self.uid = line.split()[1]
  46. elif line.startswith(b'text:'):
  47. self.__state = 1
  48. self.file = tempfile.NamedTemporaryFile(buffering=4096)
  49. else:
  50. raise Exception('Unable to parse field for mailbox {} uid {}: {}'.format(self.mailbox_guid, self.uid, line))
  51.  
  52. def __read_message(self, line):
  53. if line == b'\x0c\n':
  54. self.file.flush()
  55. self.file.seek(0)
  56. self.learn()
  57. self.__reset()
  58. else:
  59. self.file.write(line)
  60.  
  61. def lean(self):
  62. pass
  63.  
  64. def __reset(self):
  65. self.__state = 0
  66. self.mailbox_guid = None
  67. self.uid = None
  68. if hasattr(self, 'file'):
  69. self.file.close()
  70. self.file = tempfile.NamedTemporaryFile(buffering=4096)
  71.  
  72. if __name__ == '__main__':
  73. main()
  74.  
  75. # vim: ts=4 sts=4 sw=4 et
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement