Machine.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # Copyright (C) 2007-2016 John Goerzen & contributors.
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. try:
  17. from urllib import urlencode
  18. except ImportError: # python3
  19. from urllib.parse import urlencode
  20. import sys
  21. import time
  22. import logging
  23. from threading import currentThread
  24. import offlineimap
  25. from offlineimap.ui.UIBase import UIBase
  26. protocol = '7.2.0'
  27. class MachineLogFormatter(logging.Formatter):
  28. """urlencodes any outputted line, to avoid multi-line output"""
  29. def format(s, record):
  30. # Mapping of log levels to historic tag names
  31. severity_map = {
  32. 'info': 'msg',
  33. 'warning': 'warn',
  34. }
  35. line = super(MachineLogFormatter, s).format(record)
  36. severity = record.levelname.lower()
  37. if severity in severity_map:
  38. severity = severity_map[severity]
  39. if hasattr(record, "machineui"):
  40. command = record.machineui["command"]
  41. whoami = record.machineui["id"]
  42. else:
  43. command = ""
  44. whoami = currentThread().getName()
  45. prefix = "%s:%s"% (command, urlencode([('', whoami)])[1:])
  46. return "%s:%s:%s"% (severity, prefix, urlencode([('', line)])[1:])
  47. class MachineUI(UIBase):
  48. def __init__(s, config, loglevel=logging.INFO):
  49. super(MachineUI, s).__init__(config, loglevel)
  50. s._log_con_handler.createLock()
  51. """lock needed to block on password input"""
  52. # Set up the formatter that urlencodes the strings...
  53. s._log_con_handler.setFormatter(MachineLogFormatter())
  54. # Arguments:
  55. # - handler: must be method from s.logger that reflects
  56. # the severity of the passed message
  57. # - command: command that produced this message
  58. # - msg: the message itself
  59. def _printData(s, handler, command, msg):
  60. handler(msg,
  61. extra = {
  62. 'machineui': {
  63. 'command': command,
  64. 'id': currentThread().getName(),
  65. }
  66. })
  67. def _msg(s, msg):
  68. s._printData(s.logger.info, '_display', msg)
  69. def warn(s, msg, minor=0):
  70. # TODO, remove and cleanup the unused minor stuff
  71. s._printData(s.logger.warning, '', msg)
  72. def registerthread(s, account):
  73. super(MachineUI, s).registerthread(account)
  74. s._printData(s.logger.info, 'registerthread', account)
  75. def unregisterthread(s, thread):
  76. UIBase.unregisterthread(s, thread)
  77. s._printData(s.logger.info, 'unregisterthread', thread.getName())
  78. def debugging(s, debugtype):
  79. s._printData(s.logger.debug, 'debugging', debugtype)
  80. def acct(s, accountname):
  81. s._printData(s.logger.info, 'acct', accountname)
  82. def acctdone(s, accountname):
  83. s._printData(s.logger.info, 'acctdone', accountname)
  84. def validityproblem(s, folder):
  85. s._printData(s.logger.warning, 'validityproblem', "%s\n%s\n%s\n%s"%
  86. (folder.getname(), folder.getrepository().getname(),
  87. folder.get_saveduidvalidity(), folder.get_uidvalidity()))
  88. def connecting(s, reposname, hostname, port):
  89. s._printData(s.logger.info, 'connecting', "%s\n%s\n%s"% (hostname,
  90. str(port), reposname))
  91. def syncfolders(s, srcrepos, destrepos):
  92. s._printData(s.logger.info, 'syncfolders', "%s\n%s"% (s.getnicename(srcrepos),
  93. s.getnicename(destrepos)))
  94. def syncingfolder(s, srcrepos, srcfolder, destrepos, destfolder):
  95. s._printData(s.logger.info, 'syncingfolder', "%s\n%s\n%s\n%s\n"%
  96. (s.getnicename(srcrepos), srcfolder.getname(),
  97. s.getnicename(destrepos), destfolder.getname()))
  98. def loadmessagelist(s, repos, folder):
  99. s._printData(s.logger.info, 'loadmessagelist', "%s\n%s"% (s.getnicename(repos),
  100. folder.getvisiblename()))
  101. def messagelistloaded(s, repos, folder, count):
  102. s._printData(s.logger.info, 'messagelistloaded', "%s\n%s\n%d"%
  103. (s.getnicename(repos), folder.getname(), count))
  104. def syncingmessages(s, sr, sf, dr, df):
  105. s._printData(s.logger.info, 'syncingmessages', "%s\n%s\n%s\n%s\n"%
  106. (s.getnicename(sr), sf.getname(), s.getnicename(dr),
  107. df.getname()))
  108. def ignorecopyingmessage(s, uid, srcfolder, destfolder):
  109. s._printData(s.logger.info, 'ignorecopyingmessage', "%d\n%s\n%s\n%s[%s]"%
  110. (uid, s.getnicename(srcfolder), srcfolder.getname(),
  111. s.getnicename(destfolder), destfolder))
  112. def copyingmessage(s, uid, num, num_to_copy, srcfolder, destfolder):
  113. s._printData(s.logger.info, 'copyingmessage', "%d\n%s\n%s\n%s[%s]"%
  114. (uid, s.getnicename(srcfolder), srcfolder.getname(),
  115. s.getnicename(destfolder), destfolder))
  116. def folderlist(s, list):
  117. return ("\f".join(["%s\t%s"% (s.getnicename(x), x.getname()) for x in list]))
  118. def uidlist(s, list):
  119. return ("\f".join([str(u) for u in list]))
  120. def deletingmessages(s, uidlist, destlist):
  121. ds = s.folderlist(destlist)
  122. s._printData(s.logger.info, 'deletingmessages', "%s\n%s"% (s.uidlist(uidlist), ds))
  123. def addingflags(s, uidlist, flags, dest):
  124. s._printData(s.logger.info, "addingflags", "%s\n%s\n%s"% (s.uidlist(uidlist),
  125. "\f".join(flags),
  126. dest))
  127. def deletingflags(s, uidlist, flags, dest):
  128. s._printData(s.logger.info, 'deletingflags', "%s\n%s\n%s"% (s.uidlist(uidlist),
  129. "\f".join(flags),
  130. dest))
  131. def threadException(s, thread):
  132. s._printData(s.logger.warning, 'threadException', "%s\n%s"%
  133. (thread.getName(), s.getThreadExceptionString(thread)))
  134. s.delThreadDebugLog(thread)
  135. s.terminate(100)
  136. def terminate(s, exitstatus=0, errortitle='', errormsg=''):
  137. s._printData(s.logger.info, 'terminate', "%d\n%s\n%s"% (exitstatus, errortitle, errormsg))
  138. sys.exit(exitstatus)
  139. def mainException(s):
  140. s._printData(s.logger.warning, 'mainException', s.getMainExceptionString())
  141. def threadExited(s, thread):
  142. s._printData(s.logger.info, 'threadExited', thread.getName())
  143. UIBase.threadExited(s, thread)
  144. def sleeping(s, sleepsecs, remainingsecs):
  145. s._printData(s.logger.info, 'sleeping', "%d\n%d"% (sleepsecs, remainingsecs))
  146. if sleepsecs > 0:
  147. time.sleep(sleepsecs)
  148. return 0
  149. def getpass(s, accountname, config, errmsg=None):
  150. if errmsg:
  151. s._printData(s.logger.warning,
  152. 'getpasserror', "%s\n%s"% (accountname, errmsg),
  153. False)
  154. s._log_con_handler.acquire() # lock the console output
  155. try:
  156. s._printData(s.logger.info, 'getpass', accountname)
  157. return (sys.stdin.readline()[:-1])
  158. finally:
  159. s._log_con_handler.release()
  160. def init_banner(s):
  161. s._printData(s.logger.info, 'protocol', protocol)
  162. s._printData(s.logger.info, 'initbanner', offlineimap.banner)
  163. def callhook(s, msg):
  164. s._printData(s.logger.info, 'callhook', msg)