/sickbeard/encodingKludge.py

https://github.com/junalmeida/Sick-Beard · Python · 69 lines · 39 code · 10 blank · 20 comment · 20 complexity · 05c83dd3d592bb7422af38f4bbbde024 MD5 · raw file

  1. # Author: Nic Wolfe <nic@wolfeden.ca>
  2. # URL: http://code.google.com/p/sickbeard/
  3. #
  4. # This file is part of Sick Beard.
  5. #
  6. # Sick Beard is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # Sick Beard is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Sick Beard. If not, see <http://www.gnu.org/licenses/>.
  18. import os
  19. from sickbeard import logger
  20. import sickbeard
  21. # This module tries to deal with the apparently random behavior of python when dealing with unicode <-> utf-8
  22. # encodings. It tries to just use unicode, but if that fails then it tries forcing it to utf-8. Any functions
  23. # which return something should always return unicode.
  24. def fixStupidEncodings(x, silent=False):
  25. if type(x) == str:
  26. try:
  27. return x.decode(sickbeard.SYS_ENCODING)
  28. except UnicodeDecodeError:
  29. logger.log(u"Unable to decode value: "+repr(x), logger.ERROR)
  30. return None
  31. elif type(x) == unicode:
  32. return x
  33. else:
  34. logger.log(u"Unknown value passed in, ignoring it: "+str(type(x))+" ("+repr(x)+":"+repr(type(x))+")", logger.DEBUG if silent else logger.ERROR)
  35. return None
  36. return None
  37. def fixListEncodings(x):
  38. if type(x) != list and type(x) != tuple:
  39. return x
  40. else:
  41. return filter(lambda x: x != None, map(fixStupidEncodings, x))
  42. def callPeopleStupid(x):
  43. try:
  44. return x.encode(sickbeard.SYS_ENCODING)
  45. except UnicodeEncodeError:
  46. logger.log(u"YOUR COMPUTER SUCKS! Your data is being corrupted by a bad locale/encoding setting. Report this error on the forums or IRC please: "+repr(x)+", "+sickbeard.SYS_ENCODING, logger.ERROR)
  47. return x.encode(sickbeard.SYS_ENCODING, 'ignore')
  48. def ek(func, *args):
  49. result = None
  50. if os.name == 'nt':
  51. result = func(*args)
  52. else:
  53. result = func(*[callPeopleStupid(x) if type(x) in (str, unicode) else x for x in args])
  54. if type(result) in (list, tuple):
  55. return fixListEncodings(result)
  56. elif type(result) == str:
  57. return fixStupidEncodings(result)
  58. else:
  59. return result