From 4b2a782b05f99f81e9c9a084e87f5ec982c32c00 Mon Sep 17 00:00:00 2001
From: Cyril Jouve <jv.cyril@gmail.com>
Date: Tue, 11 Aug 2020 18:08:07 +0200
Subject: [PATCH] str never has attribute decode

---
 web/pgadmin/__init__.py                       |  3 -
 web/pgadmin/about/__init__.py                 |  3 -
 .../browser/server_groups/servers/__init__.py |  4 -
 web/pgadmin/misc/file_manager/__init__.py     | 24 +----
 web/pgadmin/tools/sqleditor/__init__.py       | 18 +---
 web/pgadmin/utils/crypto.py                   | 13 +--
 .../utils/driver/psycopg2/connection.py       | 89 +++----------------
 .../utils/driver/psycopg2/server_manager.py   |  9 +-
 web/pgadmin/utils/session.py                  |  7 +-
 9 files changed, 21 insertions(+), 149 deletions(-)

diff --git a/web/pgadmin/__init__.py b/web/pgadmin/__init__.py
index 915c286ad..e3ec4b57e 100644
--- a/web/pgadmin/__init__.py
+++ b/web/pgadmin/__init__.py
@@ -568,9 +568,6 @@ def create_app(app_name=None):
                     svr_discovery_id = section
                     description = registry.get(section, 'Description')
                     data_directory = registry.get(section, 'DataDirectory')
-                    if hasattr(str, 'decode'):
-                        description = description.decode('utf-8')
-                        data_directory = data_directory.decode('utf-8')
                     svr_comment = gettext(u"Auto-detected {0} installation "
                                           u"with the data directory at {1}"
                                           ).format(description, data_directory)
diff --git a/web/pgadmin/about/__init__.py b/web/pgadmin/about/__init__.py
index fd545b09e..a46f87e98 100644
--- a/web/pgadmin/about/__init__.py
+++ b/web/pgadmin/about/__init__.py
@@ -24,9 +24,6 @@ class AboutModule(PgAdminModule):
     def get_own_menuitems(self):
         appname = config.APP_NAME
 
-        if hasattr(str, 'decode'):
-            appname = appname.decode('utf-8')
-
         return {
             'help_items': [
                 MenuItem(
diff --git a/web/pgadmin/browser/server_groups/servers/__init__.py b/web/pgadmin/browser/server_groups/servers/__init__.py
index 05f29f8fc..7a0730b24 100644
--- a/web/pgadmin/browser/server_groups/servers/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/__init__.py
@@ -841,8 +841,6 @@ class ServerNode(PGChildNodeView):
                     tunnel_password=tunnel_password,
                     server_types=ServerType.types()
                 )
-                if hasattr(str, 'decode') and errmsg is not None:
-                    errmsg = errmsg.decode('utf-8')
                 if not status:
                     db.session.delete(server)
                     db.session.commit()
@@ -1109,8 +1107,6 @@ class ServerNode(PGChildNodeView):
                 server, 401, True, True, getattr(e, 'message', str(e)))
 
         if not status:
-            if hasattr(str, 'decode'):
-                errmsg = errmsg.decode('utf-8')
 
             current_app.logger.error(
                 "Could not connect to server(#{0}) - '{1}'.\nError: {2}"
diff --git a/web/pgadmin/misc/file_manager/__init__.py b/web/pgadmin/misc/file_manager/__init__.py
index 6a23d58b6..71fcca515 100644
--- a/web/pgadmin/misc/file_manager/__init__.py
+++ b/web/pgadmin/misc/file_manager/__init__.py
@@ -552,8 +552,6 @@ class Filemanager(object):
         is_show_hidden_files = show_hidden
 
         path = unquote(path)
-        if hasattr(str, 'decode'):
-            path = unquote(path).encode('utf-8').decode('utf-8')
 
         try:
             Filemanager.check_access_permission(in_dir, path)
@@ -743,8 +741,6 @@ class Filemanager(object):
         about the given file.
         """
         path = unquote(path)
-        if hasattr(str, 'decode'):
-            path = unquote(path).encode('utf-8').decode('utf-8')
         if self.dir is None:
             self.dir = ""
         orig_path = u"{0}{1}".format(self.dir, path)
@@ -851,8 +847,6 @@ class Filemanager(object):
 
         # extract filename
         oldname = split_path(old)[-1]
-        if hasattr(str, 'decode'):
-            old = old.encode('utf-8').decode('utf-8')
         path = old
         path = split_path(path)[0]  # extract path
 
@@ -860,8 +854,6 @@ class Filemanager(object):
             path += u'/'
 
         newname = new
-        if hasattr(str, 'decode'):
-            newname = new.encode('utf-8').decode('utf-8')
         newpath = path + newname
 
         # make system old path
@@ -899,8 +891,6 @@ class Filemanager(object):
             }
 
         the_dir = self.dir if self.dir is not None else ''
-        path = path.encode(
-            'utf-8').decode('utf-8') if hasattr(str, 'decode') else path
         orig_path = u"{0}{1}".format(the_dir, path)
 
         try:
@@ -949,10 +939,6 @@ class Filemanager(object):
 
             file_obj = req.files['newfile']
             file_name = file_obj.filename
-            if hasattr(str, 'decode'):
-                path = req.form.get('currentpath').encode(
-                    'utf-8').decode('utf-8')
-                file_name = file_obj.filename.encode('utf-8').decode('utf-8')
             orig_path = u"{0}{1}".format(the_dir, path)
             new_name = u"{0}{1}".format(orig_path, file_name)
 
@@ -995,9 +981,6 @@ class Filemanager(object):
 
         name = unquote(name)
         path = unquote(path)
-        if hasattr(str, 'decode'):
-            name = name.encode('utf-8').decode('utf-8')
-            path = path.encode('utf-8').decode('utf-8')
         try:
             orig_path = u"{0}{1}".format(the_dir, path)
             Filemanager.check_access_permission(
@@ -1182,12 +1165,7 @@ class Filemanager(object):
             }
 
         the_dir = self.dir if self.dir is not None else ''
-
-        if hasattr(str, 'decode'):
-            path = path.encode('utf-8')
-            orig_path = u"{0}{1}".format(the_dir, path.decode('utf-8'))
-        else:
-            orig_path = u"{0}{1}".format(the_dir, path)
+        orig_path = u"{0}{1}".format(the_dir, path)
 
         try:
             Filemanager.check_access_permission(
diff --git a/web/pgadmin/tools/sqleditor/__init__.py b/web/pgadmin/tools/sqleditor/__init__.py
index ec958ff18..8093322fb 100644
--- a/web/pgadmin/tools/sqleditor/__init__.py
+++ b/web/pgadmin/tools/sqleditor/__init__.py
@@ -1187,10 +1187,6 @@ def load_file():
         file_data = json.loads(request.data, encoding='utf-8')
 
     file_path = unquote(file_data['file_name'])
-    if hasattr(str, 'decode'):
-        file_path = unquote(
-            file_data['file_name']
-        ).encode('utf-8').decode('utf-8')
 
     # retrieve storage directory path
     storage_manager_path = get_storage_directory()
@@ -1234,10 +1230,6 @@ def save_file():
 
     # generate full path of file
     file_path = unquote(file_data['file_name'])
-    if hasattr(str, 'decode'):
-        file_path = unquote(
-            file_data['file_name']
-        ).encode('utf-8').decode('utf-8')
 
     try:
         Filemanager.check_access_permission(storage_manager_path, file_path)
@@ -1260,18 +1252,12 @@ def save_file():
 
     enc = get_file_encoding_of_loaded_file(os.path.basename(file_path))
 
-    if hasattr(str, 'decode'):
-        file_content = file_data['file_content']
-    else:
-        file_content = file_data['file_content'].encode(enc)
+    file_content = file_data['file_content'].encode(enc)
 
     # write to file
     try:
         with open(file_path, 'wb+') as output_file:
-            if hasattr(str, 'decode'):
-                output_file.write(file_content.encode('utf-8'))
-            else:
-                output_file.write(file_content)
+            output_file.write(file_content)
     except IOError as e:
         err_msg = gettext("Error: {0}").format(e.strerror)
         return internal_server_error(errormsg=err_msg)
diff --git a/web/pgadmin/utils/crypto.py b/web/pgadmin/utils/crypto.py
index b33590bec..44d945fe6 100644
--- a/web/pgadmin/utils/crypto.py
+++ b/web/pgadmin/utils/crypto.py
@@ -106,15 +106,8 @@ def pqencryptpassword(password, user):
 
     # Place salt at the end because it may be known by users trying to crack
     # the MD5 output.
-    # Handling of non-ascii password (Python2)
-    if hasattr(str, 'decode'):
-        password = password.encode('utf-8')
-        user = user.encode('utf-8')
-    else:
-        password = password.encode()
-        user = user.encode()
-
-    m.update(password)
-    m.update(user)
+
+    m.update(password.encode())
+    m.update(user.encode())
 
     return "md5" + m.hexdigest()
diff --git a/web/pgadmin/utils/driver/psycopg2/connection.py b/web/pgadmin/utils/driver/psycopg2/connection.py
index 08cf20c8d..75f46198e 100644
--- a/web/pgadmin/utils/driver/psycopg2/connection.py
+++ b/web/pgadmin/utils/driver/psycopg2/connection.py
@@ -249,11 +249,8 @@ class Connection(BaseConnection):
 
             try:
                 password = decrypt(encpass, crypt_key)
-                # Handling of non ascii password (Python2)
-                if hasattr(str, 'decode'):
-                    password = password.decode('utf-8').encode('utf-8')
                 # password is in bytes, for python3 we need it in string
-                elif isinstance(password, bytes):
+                if isinstance(password, bytes):
                     password = password.decode()
             except Exception as e:
                 manager.stop_ssh_tunnel()
@@ -271,14 +268,9 @@ class Connection(BaseConnection):
             passfile = manager.passfile if manager.passfile else None
 
         try:
-            if hasattr(str, 'decode'):
-                database = self.db.encode('utf-8')
-                user = manager.user.encode('utf-8')
-                conn_id = self.conn_id.encode('utf-8')
-            else:
-                database = self.db
-                user = manager.user
-                conn_id = self.conn_id
+            database = self.db
+            user = manager.user
+            conn_id = self.conn_id
 
             import os
             os.environ['PGAPPNAME'] = '{0} - {1}'.format(
@@ -325,7 +317,7 @@ class Connection(BaseConnection):
                 u":{msg}".format(
                     server_id=self.manager.sid,
                     conn_id=conn_id,
-                    msg=msg.decode('utf-8') if hasattr(str, 'decode') else msg
+                    msg=msg
                 )
             )
             return False, msg
@@ -761,19 +753,6 @@ WHERE
             else:
                 quote = csv.QUOTE_NONE
 
-            if hasattr(str, 'decode'):
-                # Decode the field_separator
-                try:
-                    field_separator = field_separator.decode('utf-8')
-                except Exception as e:
-                    current_app.logger.error(e)
-
-                # Decode the quote_char
-                try:
-                    quote_char = quote_char.decode('utf-8')
-                except Exception as e:
-                    current_app.logger.error(e)
-
             csv_writer = csv.DictWriter(
                 res_io, fieldnames=header, delimiter=field_separator,
                 quoting=quote,
@@ -1621,40 +1600,6 @@ Failed to reset the connection to the server due to following error:
 
         return resp
 
-    def decode_to_utf8(self, value):
-        """
-        This method will decode values to utf-8
-        Args:
-            value: String to be decode
-
-        Returns:
-            Decoded string
-        """
-        is_error = False
-        if hasattr(str, 'decode'):
-            try:
-                value = value.decode('utf-8')
-            except UnicodeDecodeError:
-                # Let's try with python's preferred encoding
-                # On Windows lc_messages mostly has environment dependent
-                # encoding like 'French_France.1252'
-                try:
-                    import locale
-                    pref_encoding = locale.getpreferredencoding()
-                    value = value.decode(pref_encoding)\
-                        .encode('utf-8')\
-                        .decode('utf-8')
-                except Exception:
-                    is_error = True
-            except Exception:
-                is_error = True
-
-        # If still not able to decode then
-        if is_error:
-            value = value.decode('ascii', 'ignore')
-
-        return value
-
     def _formatted_exception_msg(self, exception_obj, formatted_msg):
         """
         This method is used to parse the psycopg2.Error object and returns the
@@ -1673,8 +1618,6 @@ Failed to reset the connection to the server due to following error:
             errmsg = exception_obj.diag.message_detail
         else:
             errmsg = str(exception_obj)
-        # errmsg might contains encoded value, lets decode it
-        errmsg = self.decode_to_utf8(errmsg)
 
         # if formatted_msg is false then return from the function
         if not formatted_msg:
@@ -1689,8 +1632,8 @@ Failed to reset the connection to the server due to following error:
         if exception_obj.diag.severity is not None \
                 and exception_obj.diag.message_primary is not None:
             ex_diag_message = u"{0}:  {1}".format(
-                self.decode_to_utf8(exception_obj.diag.severity),
-                self.decode_to_utf8(exception_obj.diag.message_primary)
+                exception_obj.diag.severity,
+                exception_obj.diag.message_primary
             )
             # If both errors are different then only append it
             if errmsg and ex_diag_message and \
@@ -1698,9 +1641,7 @@ Failed to reset the connection to the server due to following error:
                     errmsg.strip().strip('\n').lower():
                 errmsg += ex_diag_message
         elif exception_obj.diag.message_primary is not None:
-            message_primary = self.decode_to_utf8(
-                exception_obj.diag.message_primary
-            )
+            message_primary = exception_obj.diag.message_primary
             if message_primary.lower() not in errmsg.lower():
                 errmsg += message_primary
 
@@ -1708,39 +1649,35 @@ Failed to reset the connection to the server due to following error:
             if not errmsg.endswith('\n'):
                 errmsg += '\n'
             errmsg += gettext('SQL state: ')
-            errmsg += self.decode_to_utf8(exception_obj.diag.sqlstate)
+            errmsg += exception_obj.diag.sqlstate
 
         if exception_obj.diag.message_detail is not None and \
                 'Detail:'.lower() not in errmsg.lower():
             if not errmsg.endswith('\n'):
                 errmsg += '\n'
             errmsg += gettext('Detail: ')
-            errmsg += self.decode_to_utf8(
-                exception_obj.diag.message_detail
-            )
+            errmsg += exception_obj.diag.message_detail
 
         if exception_obj.diag.message_hint is not None and \
                 'Hint:'.lower() not in errmsg.lower():
             if not errmsg.endswith('\n'):
                 errmsg += '\n'
             errmsg += gettext('Hint: ')
-            errmsg += self.decode_to_utf8(exception_obj.diag.message_hint)
+            errmsg += exception_obj.diag.message_hint
 
         if exception_obj.diag.statement_position is not None and \
                 'Character:'.lower() not in errmsg.lower():
             if not errmsg.endswith('\n'):
                 errmsg += '\n'
             errmsg += gettext('Character: ')
-            errmsg += self.decode_to_utf8(
-                exception_obj.diag.statement_position
-            )
+            errmsg += exception_obj.diag.statement_position
 
         if exception_obj.diag.context is not None and \
                 'Context:'.lower() not in errmsg.lower():
             if not errmsg.endswith('\n'):
                 errmsg += '\n'
             errmsg += gettext('Context: ')
-            errmsg += self.decode_to_utf8(exception_obj.diag.context)
+            errmsg += exception_obj.diag.context
 
         notices = self.get_notices()
         return errmsg if notices == '' else notices + '\n' + errmsg
diff --git a/web/pgadmin/utils/driver/psycopg2/server_manager.py b/web/pgadmin/utils/driver/psycopg2/server_manager.py
index 81eb49b23..ea1d9efe1 100644
--- a/web/pgadmin/utils/driver/psycopg2/server_manager.py
+++ b/web/pgadmin/utils/driver/psycopg2/server_manager.py
@@ -366,9 +366,6 @@ WHERE db.oid = {0}""".format(did))
         if did is not None:
             if did in self.db_info and 'datname' in self.db_info[did]:
                 database = self.db_info[did]['datname']
-                if hasattr(str, 'decode') and \
-                        not isinstance(database, unicode):
-                    database = database.decode('utf-8')
                 if database is None:
                     return False
             else:
@@ -479,12 +476,8 @@ WHERE db.oid = {0}""".format(did))
 
             try:
                 tunnel_password = decrypt(tunnel_password, crypt_key)
-                # Handling of non ascii password (Python2)
-                if hasattr(str, 'decode'):
-                    tunnel_password = \
-                        tunnel_password.decode('utf-8').encode('utf-8')
                 # password is in bytes, for python3 we need it in string
-                elif isinstance(tunnel_password, bytes):
+                if isinstance(tunnel_password, bytes):
                     tunnel_password = tunnel_password.decode()
 
             except Exception as e:
diff --git a/web/pgadmin/utils/session.py b/web/pgadmin/utils/session.py
index 177a996b8..b8af3d468 100644
--- a/web/pgadmin/utils/session.py
+++ b/web/pgadmin/utils/session.py
@@ -68,12 +68,7 @@ class ManagedSession(CallbackDict, SessionMixin):
 
     def sign(self, secret):
         if not self.hmac_digest:
-            if hasattr(string, 'lowercase'):
-                population = string.lowercase
-            # If script is running under python3
-            elif hasattr(string, 'ascii_lowercase'):
-                population = string.ascii_lowercase
-            population += string.digits
+            population = string.ascii_lowercase + string.digits
 
             self.randval = ''.join(random.sample(population, 20))
             self.hmac_digest = _calc_hmac(
-- 
2.27.0

