diff src/plugins/plugin_xep_0096.py @ 993:301b342c697a

core: use of the new core.log module: /!\ this is a massive refactoring and was largely automated, it probably did bring some bugs /!\
author Goffi <goffi@goffi.org>
date Sat, 19 Apr 2014 19:19:19 +0200
parents c6d8fc63b1db
children 4dbe8e57ff51
line wrap: on
line diff
--- a/src/plugins/plugin_xep_0096.py	Sat Apr 19 16:48:26 2014 +0200
+++ b/src/plugins/plugin_xep_0096.py	Sat Apr 19 19:19:19 2014 +0200
@@ -19,10 +19,11 @@
 
 from sat.core.i18n import _
 from sat.core.constants import Const as C
-from logging import debug, info, warning, error
+from sat.core.log import getLogger
+log = getLogger(__name__)
 from twisted.words.xish import domish
 from twisted.words.protocols.jabber import jid
-from twisted.words.protocols.jabber import error as jab_error
+from twisted.words.protocols import jabber
 import os
 from twisted.internet import reactor
 
@@ -47,7 +48,7 @@
 class XEP_0096(object):
 
     def __init__(self, host):
-        info(_("Plugin XEP_0096 initialization"))
+        log.info(_("Plugin XEP_0096 initialization"))
         self.host = host
         self.managed_stream_m = [self.host.plugins["XEP-0065"].NAMESPACE,
                                  self.host.plugins["XEP-0047"].NAMESPACE]  # Stream methods managed
@@ -62,12 +63,12 @@
     def _kill_id(self, approval_id, profile):
         """Delete a waiting_for_approval id, called after timeout
         @param approval_id: id of _xep_0096_waiting_for_approval"""
-        info(_("SI File Transfer: TimeOut reached for id %s") % approval_id)
+        log.info(_("SI File Transfer: TimeOut reached for id %s") % approval_id)
         try:
             client = self.host.getClient(profile)
             del client._xep_0096_waiting_for_approval[approval_id]
         except KeyError:
-            warning(_("kill id called on a non existant approval id"))
+            log.warning(_("kill id called on a non existant approval id"))
 
     def transferRequest(self, iq_id, from_jid, si_id, si_mime_type, si_el, profile):
         """Called when a file transfer is requested
@@ -77,8 +78,8 @@
         @param si_mime_type: Mime type of the file (or default "application/octet-stream" if unknown)
         @param si_el: domish.Element of the request
         @param profile: %(doc_profile)s"""
-        info(_("XEP-0096 file transfer requested"))
-        debug(si_el.toXml())
+        log.info(_("XEP-0096 file transfer requested"))
+        log.debug(si_el.toXml())
         client = self.host.getClient(profile)
         filename = ""
         file_size = ""
@@ -95,14 +96,14 @@
             file_size = file_el["size"]
             file_date = file_el.getAttribute("date", "")
             file_hash = file_el.getAttribute("hash", "")
-            info(_("File proposed: name=[%(name)s] size=%(size)s") % {'name': filename, 'size': file_size})
+            log.info(_("File proposed: name=[%(name)s] size=%(size)s") % {'name': filename, 'size': file_size})
             for file_child_el in file_el.elements():
                 if file_child_el.name == "desc":
                     file_desc = unicode(file_child_el)
                 elif file_child_el.name == "range":
                     can_range = True
         else:
-            warning(_("No file element found"))
+            log.warning(_("No file element found"))
             self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile)
             return
 
@@ -112,15 +113,15 @@
             try:
                 stream_method = self.host.plugins["XEP-0020"].negociate(feature_el, 'stream-method', self.managed_stream_m)
             except KeyError:
-                warning(_("No stream method found"))
+                log.warning(_("No stream method found"))
                 self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile)
                 return
             if not stream_method:
-                warning(_("Can't find a valid stream method"))
+                log.warning(_("Can't find a valid stream method"))
                 self.host.plugins["XEP-0095"].sendFailedError(iq_id, from_jid, profile)
                 return
         else:
-            warning(_("No feature element found"))
+            log.warning(_("No feature element found"))
             self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile)
             return
 
@@ -152,7 +153,7 @@
             try:
                 dest_path = frontend_data['dest_path']
             except KeyError:
-                error(_('dest path not found in frontend_data'))
+                log.error(_('dest path not found in frontend_data'))
                 del(client._xep_0096_waiting_for_approval[sid])
                 return
             if stream_method == self.host.plugins["XEP-0065"].NAMESPACE:
@@ -164,7 +165,7 @@
                 range_offset = file_obj.tell()
                 self.host.plugins["XEP-0047"].prepareToReceive(jid.JID(data['from']), sid, file_obj, int(data["size"]), self._transferSucceeded, self._transferFailed, profile)
             else:
-                error(_("Unknown stream method, this should not happen at this stage, cancelling transfer"))
+                log.error(_("Unknown stream method, this should not happen at this stage, cancelling transfer"))
                 del(client._xep_0096_waiting_for_approval[sid])
                 return
 
@@ -179,7 +180,7 @@
                 misc_elts.append(range_elt)
             self.host.plugins["XEP-0095"].acceptStream(data["id"], data['from'], feature_elt, misc_elts, profile)
         else:
-            debug(_("Transfer [%s] refused"), sid)
+            log.debug(_("Transfer [%s] refused"), sid)
             self.host.plugins["XEP-0095"].sendRejectedError(data["id"], data['from'], profile=profile)
             del(client._xep_0096_waiting_for_approval[sid])
 
@@ -188,7 +189,7 @@
         @param id: stream id"""
         client = self.host.getClient(profile)
         file_obj.close()
-        info(_('Transfer %s successfuly finished') % sid)
+        log.info(_('Transfer %s successfuly finished') % sid)
         del(client._xep_0096_waiting_for_approval[sid])
 
     def _transferFailed(self, sid, file_obj, stream_method, reason, profile):
@@ -197,7 +198,7 @@
         @param reason: can be TIMEOUT, IO_ERROR, PROTOCOL_ERROR"""
         client = self.host.getClient(profile)
         data, timeout, stream_method, failed_methods = client._xep_0096_waiting_for_approval[sid]
-        warning(_('Transfer %(id)s failed with stream method %(s_method)s: %(reason)s') % {
+        log.warning(_('Transfer %(id)s failed with stream method %(s_method)s: %(reason)s') % {
             'id': sid,
             's_method': stream_method,
             'reason': reason})
@@ -205,36 +206,36 @@
         file_obj.close()
         os.remove(filepath)
         #TODO: session remenber (within a time limit) when a stream method fail, and avoid that stream method with full jid for the rest of the session
-        warning(_("All stream methods failed, can't transfer the file"))
+        log.warning(_("All stream methods failed, can't transfer the file"))
         del(client._xep_0096_waiting_for_approval[sid])
 
     def fileCb(self, filepath, sid, size, profile, IQ):
         if IQ['type'] == "error":
-            stanza_err = jab_error.exceptionFromStanza(IQ)
+            stanza_err = jabber.error.exceptionFromStanza(IQ)
             if stanza_err.code == '403' and stanza_err.condition == 'forbidden':
-                debug(_("File transfer refused by %s") % IQ['from'])
+                log.debug(_("File transfer refused by %s") % IQ['from'])
                 self.host.bridge.newAlert(_("The contact %s refused your file") % IQ['from'], _("File refused"), "INFO", profile)
             else:
-                warning(_("Error during file transfer with %s") % IQ['from'])
+                log.warning(_("Error during file transfer with %s") % IQ['from'])
                 self.host.bridge.newAlert(_("Something went wrong during the file transfer session intialisation with %s") % IQ['from'], _("File transfer error"), "ERROR", profile)
             return
 
         si_elt = IQ.firstChildElement()
 
         if IQ['type'] != "result" or not si_elt or si_elt.name != "si":
-            error(_("Protocol error during file transfer"))
+            log.error(_("Protocol error during file transfer"))
             return
 
         feature_elts = self.host.plugins["XEP-0020"].getFeatureElt(si_elt)
         if not feature_elts:
-            warning(_("No feature element"))
+            log.warning(_("No feature element"))
             return
 
         choosed_options = self.host.plugins["XEP-0020"].getChoosedOptions(feature_elts[0])
         try:
             stream_method = choosed_options["stream-method"]
         except KeyError:
-            warning(_("No stream method choosed"))
+            log.warning(_("No stream method choosed"))
             return
 
         range_offset = 0
@@ -256,7 +257,7 @@
                 file_obj.seek(range_offset)
             self.host.plugins["XEP-0047"].startStream(file_obj, jid.JID(IQ['from']), sid, range_length, self.sendSuccessCb, self.sendFailureCb, size, profile)
         else:
-            warning(_("Invalid stream method received"))
+            log.warning(_("Invalid stream method received"))
 
     def sendFile(self, to_jid, filepath, data={}, profile_key=C.PROF_KEY_NONE):
         """send a file using XEP-0096
@@ -269,16 +270,16 @@
         """
         profile = self.host.memory.getProfileName(profile_key)
         if not profile:
-            warning(_("Trying to send a file from an unknown profile"))
+            log.warning(_("Trying to send a file from an unknown profile"))
             return ""
         feature_elt = self.host.plugins["XEP-0020"].proposeFeatures({'stream-method': self.managed_stream_m})
 
         file_transfer_elts = []
 
-        statinfo = os.stat(filepath)
+        statlog.info = os.stat(filepath)
         file_elt = domish.Element((PROFILE, 'file'))
         file_elt['name'] = os.path.basename(filepath)
-        size = file_elt['size'] = str(statinfo.st_size)
+        size = file_elt['size'] = str(statlog.info.st_size)
         file_transfer_elts.append(file_elt)
 
         file_transfer_elts.append(domish.Element((None, 'range')))
@@ -288,10 +289,10 @@
         return sid
 
     def sendSuccessCb(self, sid, file_obj, stream_method, profile):
-        info(_('Transfer %(sid)s successfuly finished [%(profile)s]')
+        log.info(_('Transfer %(sid)s successfuly finished [%(profile)s]')
              % {"sid": sid, "profile": profile})
         file_obj.close()
 
     def sendFailureCb(self, sid, file_obj, stream_method, reason, profile):
         file_obj.close()
-        warning(_('Transfer %(id)s failed with stream method %(s_method)s: %(reason)s [%(profile)s]') % {'id': sid, "s_method": stream_method, 'reason': reason, 'profile': profile})
+        log.warning(_('Transfer %(id)s failed with stream method %(s_method)s: %(reason)s [%(profile)s]') % {'id': sid, "s_method": stream_method, 'reason': reason, 'profile': profile})