diff cagou/plugins/plugin_wid_file_sharing.py @ 312:772c170b47a9

Python3 port: /!\ Cagou now runs with Python 3.6+ Port has been done in the same way as for backend (check backend commit b2d067339de3 message for details).
author Goffi <goffi@goffi.org>
date Tue, 13 Aug 2019 19:14:22 +0200
parents 1b835bcfa663
children dddea9684a8e
line wrap: on
line diff
--- a/cagou/plugins/plugin_wid_file_sharing.py	Mon Aug 05 11:21:54 2019 +0200
+++ b/cagou/plugins/plugin_wid_file_sharing.py	Tue Aug 13 19:14:22 2019 +0200
@@ -42,22 +42,22 @@
 
 
 PLUGIN_INFO = {
-    "name": _(u"file sharing"),
+    "name": _("file sharing"),
     "main": "FileSharing",
-    "description": _(u"share/transfer files between devices"),
-    "icon_symbol": u"exchange",
+    "description": _("share/transfer files between devices"),
+    "icon_symbol": "exchange",
 }
-MODE_VIEW = u"view"
-MODE_LOCAL = u"local"
-SELECT_INSTRUCTIONS = _(u"Please select entities to share with")
+MODE_VIEW = "view"
+MODE_LOCAL = "local"
+SELECT_INSTRUCTIONS = _("Please select entities to share with")
 
 if kivy_utils.platform == "android":
     from jnius import autoclass
     Environment = autoclass("android.os.Environment")
     base_dir = Environment.getExternalStorageDirectory().getAbsolutePath()
     def expanduser(path):
-        if path == u'~' or path.startswith(u'~/'):
-            return path.replace(u'~', base_dir, 1)
+        if path == '~' or path.startswith('~/'):
+            return path.replace('~', base_dir, 1)
         return path
 else:
     expanduser = os.path.expanduser
@@ -72,11 +72,11 @@
 
     def on_mode(self, parent, new_mode):
         if new_mode == MODE_VIEW:
-            self.text = _(u"view shared files")
+            self.text = _("view shared files")
         elif new_mode == MODE_LOCAL:
-            self.text = _(u"share local files")
+            self.text = _("share local files")
         else:
-            exceptions.InternalError(u"Unknown mode: {mode}".format(mode=new_mode))
+            exceptions.InternalError("Unknown mode: {mode}".format(mode=new_mode))
 
 
 class PathWidget(ItemWidget):
@@ -84,8 +84,8 @@
     def __init__(self, filepath, main_wid, **kw):
         name = os.path.basename(filepath)
         self.filepath = os.path.normpath(filepath)
-        if self.filepath == u'.':
-            self.filepath = u''
+        if self.filepath == '.':
+            self.filepath = ''
         super(PathWidget, self).__init__(name=name, main_wid=main_wid, **kw)
 
     @property
@@ -97,7 +97,7 @@
             self.main_wid.current_dir = self.filepath
 
     def open_menu(self, touch, dt):
-        log.debug(_(u"opening menu for {path}").format(path=self.filepath))
+        log.debug(_("opening menu for {path}").format(path=self.filepath))
         super(PathWidget, self).open_menu(touch, dt)
 
 
@@ -110,11 +110,11 @@
     def getMenuChoices(self):
         choices = []
         if self.shared:
-            choices.append(dict(text=_(u'unshare'),
+            choices.append(dict(text=_('unshare'),
                                 index=len(choices)+1,
                                 callback=self.main_wid.unshare))
         else:
-            choices.append(dict(text=_(u'share'),
+            choices.append(dict(text=_('share'),
                                 index=len(choices)+1,
                                 callback=self.main_wid.share))
         return choices
@@ -132,8 +132,8 @@
 
     def do_item_action(self, touch):
         if self.is_dir:
-            if self.filepath == u'..':
-                self.main_wid.remote_entity = u''
+            if self.filepath == '..':
+                self.main_wid.remote_entity = ''
             else:
                 super(RemotePathWidget, self).do_item_action(touch)
         else:
@@ -144,7 +144,7 @@
 
     def do_item_action(self, touch):
         self.main_wid.remote_entity = self.entity_jid
-        self.main_wid.remote_dir = u''
+        self.main_wid.remote_dir = ''
 
 
 class FileSharing(quick_widgets.QuickWidget, cagou_widget.CagouWidget, FilterBehavior,
@@ -152,9 +152,9 @@
     SINGLE=False
     layout = properties.ObjectProperty()
     mode = properties.OptionProperty(MODE_VIEW, options=[MODE_VIEW, MODE_LOCAL])
-    local_dir = properties.StringProperty(expanduser(u'~'))
-    remote_dir = properties.StringProperty(u'')
-    remote_entity = properties.StringProperty(u'')
+    local_dir = properties.StringProperty(expanduser('~'))
+    remote_dir = properties.StringProperty('')
+    remote_entity = properties.StringProperty('')
     shared_paths = properties.ListProperty()
     signals_registered = False
 
@@ -208,12 +208,12 @@
         self.update_view(None, self.local_dir)
 
     def onHeaderInput(self):
-        if u'/' in self.header_input.text or self.header_input.text == u'~':
+        if '/' in self.header_input.text or self.header_input.text == '~':
             self.current_dir = expanduser(self.header_input.text)
 
     def onHeaderInputComplete(self, wid, text, **kwargs):
         """we filter items when text is entered in input box"""
-        if u'/' in text:
+        if '/' in text:
             return
         self.do_filter(self.layout.children,
                        text,
@@ -221,7 +221,7 @@
                        width_cb=lambda c: c.base_width,
                        height_cb=lambda c: c.minimum_height,
                        continue_tests=[lambda c: not isinstance(c, ItemWidget),
-                                       lambda c: c.name == u'..'])
+                                       lambda c: c.name == '..'])
 
 
     ## remote sharing callback ##
@@ -229,14 +229,14 @@
     def _discoFindByFeaturesCb(self, data):
         entities_services, entities_own, entities_roster = data
         for entities_map, title in ((entities_services,
-                                     _(u'services')),
+                                     _('services')),
                                     (entities_own,
-                                     _(u'your devices')),
+                                     _('your devices')),
                                     (entities_roster,
-                                     _(u'your contacts devices'))):
+                                     _('your contacts devices'))):
             if entities_map:
                 self.layout.add_widget(CategorySeparator(text=title))
-                for entity_str, entity_ids in entities_map.iteritems():
+                for entity_str, entity_ids in entities_map.items():
                     entity_jid = jid.JID(entity_str)
                     item = SharingDeviceWidget(
                         self, entity_jid, Identities(entity_ids))
@@ -246,39 +246,39 @@
                 size_hint=(1, 1),
                 halign='center',
                 text_size=self.size,
-                text=_(u"No sharing device found")))
+                text=_("No sharing device found")))
 
     def discover_devices(self):
         """Looks for devices handling file "File Information Sharing" and display them"""
         try:
             namespace = self.host.ns_map['fis']
         except KeyError:
-            msg = _(u"can't find file information sharing namespace, "
-                    u"is the plugin running?")
+            msg = _("can't find file information sharing namespace, "
+                    "is the plugin running?")
             log.warning(msg)
-            G.host.addNote(_(u"missing plugin"), msg, C.XMLUI_DATA_LVL_ERROR)
+            G.host.addNote(_("missing plugin"), msg, C.XMLUI_DATA_LVL_ERROR)
             return
         self.host.bridge.discoFindByFeatures(
             [namespace], [], False, True, True, True, False, self.profile,
             callback=self._discoFindByFeaturesCb,
             errback=partial(G.host.errback,
-                title=_(u"shared folder error"),
-                message=_(u"can't check sharing devices: {msg}")))
+                title=_("shared folder error"),
+                message=_("can't check sharing devices: {msg}")))
 
     def FISListCb(self, files_data):
         for file_data in files_data:
-            filepath = os.path.join(self.current_dir, file_data[u'name'])
+            filepath = os.path.join(self.current_dir, file_data['name'])
             item = RemotePathWidget(
                 filepath=filepath,
                 main_wid=self,
-                type_=file_data[u'type'])
+                type_=file_data['type'])
             self.layout.add_widget(item)
 
     def FISListEb(self, failure_):
-        self.remote_dir = u''
+        self.remote_dir = ''
         G.host.addNote(
-            _(u"shared folder error"),
-            _(u"can't list files for {remote_entity}: {msg}").format(
+            _("shared folder error"),
+            _("can't list files for {remote_entity}: {msg}").format(
                 remote_entity=self.remote_entity,
                 msg=failure_),
             level=C.XMLUI_DATA_LVL_WARNING)
@@ -287,25 +287,25 @@
 
     def update_view(self, *args):
         """update items according to current mode, entity and dir"""
-        log.debug(u'updating {}, {}'.format(self.current_dir, args))
+        log.debug('updating {}, {}'.format(self.current_dir, args))
         self.layout.clear_widgets()
-        self.header_input.text = u''
+        self.header_input.text = ''
         self.header_input.hint_text = self.current_dir
 
         if self.mode == MODE_LOCAL:
-            filepath = os.path.join(self.local_dir, u'..')
+            filepath = os.path.join(self.local_dir, '..')
             self.layout.add_widget(LocalPathWidget(filepath=filepath, main_wid=self))
             try:
                 files = sorted(os.listdir(self.local_dir))
             except OSError as e:
-                msg = _(u"can't list files in \"{local_dir}\": {msg}").format(
+                msg = _("can't list files in \"{local_dir}\": {msg}").format(
                     local_dir=self.local_dir,
                     msg=e)
                 G.host.addNote(
-                    _(u"shared folder error"),
+                    _("shared folder error"),
                     msg,
                     level=C.XMLUI_DATA_LVL_WARNING)
-                self.local_dir = expanduser(u'~')
+                self.local_dir = expanduser('~')
                 return
             for f in files:
                 filepath = os.path.join(self.local_dir, f)
@@ -317,14 +317,14 @@
             else:
                 # we always a way to go back
                 # so user can return to previous list even in case of error
-                parent_path = os.path.join(self.remote_dir, u'..')
+                parent_path = os.path.join(self.remote_dir, '..')
                 item = RemotePathWidget(
                     filepath = parent_path,
                     main_wid=self,
                     type_ = C.FILE_TYPE_DIRECTORY)
                 self.layout.add_widget(item)
                 self.host.bridge.FISList(
-                    unicode(self.remote_entity),
+                    str(self.remote_entity),
                     self.remote_dir,
                     {},
                     self.profile,
@@ -335,8 +335,8 @@
 
     def do_share(self, entities_jids, item):
         if entities_jids:
-            access = {u'read': {u'type': 'whitelist',
-                                u'jids': entities_jids}}
+            access = {'read': {'type': 'whitelist',
+                                'jids': entities_jids}}
         else:
             access = {}
 
@@ -346,11 +346,11 @@
             json.dumps(access, ensure_ascii=False),
             self.profile,
             callback=lambda name: G.host.addNote(
-                _(u"sharing folder"),
-                _(u"{name} is now shared").format(name=name)),
+                _("sharing folder"),
+                _("{name} is now shared").format(name=name)),
             errback=partial(G.host.errback,
-                title=_(u"sharing folder"),
-                message=_(u"can't share folder: {msg}")))
+                title=_("sharing folder"),
+                message=_("can't share folder: {msg}")))
 
     def share(self, menu):
         item = self.menu_item
@@ -365,16 +365,16 @@
             item.filepath,
             self.profile,
             callback=lambda: G.host.addNote(
-                _(u"sharing folder"),
-                _(u"{name} is not shared anymore").format(name=item.name)),
+                _("sharing folder"),
+                _("{name} is not shared anymore").format(name=item.name)),
             errback=partial(G.host.errback,
-                title=_(u"sharing folder"),
-                message=_(u"can't unshare folder: {msg}")))
+                title=_("sharing folder"),
+                message=_("can't unshare folder: {msg}")))
 
     def fileJingleRequestCb(self, progress_id, item, dest_path):
         G.host.addNote(
-            _(u"file request"),
-            _(u"{name} download started at {dest_path}").format(
+            _("file request"),
+            _("{name} download started at {dest_path}").format(
                 name = item.name,
                 dest_path = dest_path))
 
@@ -388,19 +388,19 @@
         assert self.remote_entity
         extra = {'path': path}
         dest_path = files_utils.get_unique_name(os.path.join(G.host.downloads_dir, name))
-        G.host.bridge.fileJingleRequest(unicode(self.remote_entity),
+        G.host.bridge.fileJingleRequest(str(self.remote_entity),
                                         dest_path,
                                         name,
-                                        u'',
-                                        u'',
+                                        '',
+                                        '',
                                         extra,
                                         self.profile,
                                         callback=partial(self.fileJingleRequestCb,
                                             item=item,
                                             dest_path=dest_path),
                                         errback=partial(G.host.errback,
-                                            title = _(u"file request error"),
-                                            message = _(u"can't request file: {msg}")))
+                                            title = _("file request error"),
+                                            message = _("can't request file: {msg}")))
 
     @classmethod
     def shared_path_new(cls, shared_path, name, profile):
@@ -414,5 +414,5 @@
             if shared_path in wid.shared_paths:
                 wid.shared_paths.remove(shared_path)
             else:
-                log.warning(_(u"shared path {path} not found in {widget}".format(
+                log.warning(_("shared path {path} not found in {widget}".format(
                     path = shared_path, widget = wid)))