You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

391 lines
9.6 KiB

10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
7 years ago
7 years ago
7 years ago
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. """Youtubedlg module that contains util functions.
  4. Attributes:
  5. _RANDOM_OBJECT (object): Object that it's used as a default parameter.
  6. YOUTUBEDL_BIN (string): Youtube-dl binary filename.
  7. """
  8. from __future__ import unicode_literals
  9. import os
  10. import sys
  11. import json
  12. import math
  13. import locale
  14. import subprocess
  15. try:
  16. from twodict import TwoWayOrderedDict
  17. except ImportError as error:
  18. print error
  19. sys.exit(1)
  20. from .info import __appname__
  21. from .version import __version__
  22. _RANDOM_OBJECT = object()
  23. YOUTUBEDL_BIN = 'youtube-dl'
  24. if os.name == 'nt':
  25. YOUTUBEDL_BIN += '.exe'
  26. FILESIZE_METRICS = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
  27. KILO_SIZE = 1024.0
  28. def get_encoding():
  29. """Return system encoding. """
  30. try:
  31. encoding = locale.getpreferredencoding()
  32. 'TEST'.encode(encoding)
  33. except:
  34. encoding = 'UTF-8'
  35. return encoding
  36. def convert_item(item, to_unicode=False):
  37. """Convert item between 'unicode' and 'str'.
  38. Args:
  39. item (-): Can be any python item.
  40. to_unicode (boolean): When True it will convert all the 'str' types
  41. to 'unicode'. When False it will convert all the 'unicode'
  42. types back to 'str'.
  43. """
  44. if to_unicode and isinstance(item, str):
  45. # Convert str to unicode
  46. return item.decode(get_encoding(), 'ignore')
  47. if not to_unicode and isinstance(item, unicode):
  48. # Convert unicode to str
  49. return item.encode(get_encoding(), 'ignore')
  50. if hasattr(item, '__iter__'):
  51. # Handle iterables
  52. temp_list = []
  53. for sub_item in item:
  54. if isinstance(item, dict):
  55. temp_list.append((convert_item(sub_item, to_unicode), convert_item(item[sub_item], to_unicode)))
  56. else:
  57. temp_list.append(convert_item(sub_item, to_unicode))
  58. return type(item)(temp_list)
  59. return item
  60. def convert_on_bounds(func):
  61. """Decorator to convert string inputs & outputs.
  62. Covert string inputs & outputs between 'str' and 'unicode' at the
  63. application bounds using the preferred system encoding. It will convert
  64. all the string params (args, kwargs) to 'str' type and all the
  65. returned strings values back to 'unicode'.
  66. """
  67. def wrapper(*args, **kwargs):
  68. returned_value = func(*convert_item(args), **convert_item(kwargs))
  69. return convert_item(returned_value, True)
  70. return wrapper
  71. # See: https://github.com/MrS0m30n3/youtube-dl-gui/issues/57
  72. # Patch os functions to convert between 'str' and 'unicode' on app bounds
  73. os_sep = unicode(os.sep)
  74. os_getenv = convert_on_bounds(os.getenv)
  75. os_makedirs = convert_on_bounds(os.makedirs)
  76. os_path_isdir = convert_on_bounds(os.path.isdir)
  77. os_path_exists = convert_on_bounds(os.path.exists)
  78. os_path_dirname = convert_on_bounds(os.path.dirname)
  79. os_path_abspath = convert_on_bounds(os.path.abspath)
  80. os_path_realpath = convert_on_bounds(os.path.realpath)
  81. os_path_expanduser = convert_on_bounds(os.path.expanduser)
  82. # Patch locale functions
  83. locale_getdefaultlocale = convert_on_bounds(locale.getdefaultlocale)
  84. # Patch Windows specific functions
  85. if os.name == 'nt':
  86. os_startfile = convert_on_bounds(os.startfile)
  87. def remove_file(filename):
  88. if os_path_exists(filename):
  89. os.remove(filename)
  90. return True
  91. return False
  92. def remove_shortcuts(path):
  93. """Return given path after removing the shortcuts. """
  94. return path.replace('~', os_path_expanduser('~'))
  95. def absolute_path(filename):
  96. """Return absolute path to the given file. """
  97. return os_path_dirname(os_path_realpath(os_path_abspath(filename)))
  98. def open_file(file_path):
  99. """Open file in file_path using the default OS application.
  100. Returns:
  101. True on success else False.
  102. """
  103. file_path = remove_shortcuts(file_path)
  104. if not os_path_exists(file_path):
  105. return False
  106. if os.name == "nt":
  107. os_startfile(file_path)
  108. else:
  109. subprocess.call(("xdg-open", file_path))
  110. return True
  111. def encode_tuple(tuple_to_encode):
  112. """Turn size tuple into string. """
  113. return '%s/%s' % (tuple_to_encode[0], tuple_to_encode[1])
  114. def decode_tuple(encoded_tuple):
  115. """Turn tuple string back to tuple. """
  116. s = encoded_tuple.split('/')
  117. return int(s[0]), int(s[1])
  118. def check_path(path):
  119. """Create path if not exist. """
  120. if not os_path_exists(path):
  121. os_makedirs(path)
  122. def get_config_path():
  123. """Return user config path.
  124. Note:
  125. Windows = %AppData% + app_name
  126. Linux = ~/.config + app_name
  127. """
  128. if os.name == 'nt':
  129. path = os_getenv('APPDATA')
  130. else:
  131. path = os.path.join(os_path_expanduser('~'), '.config')
  132. return os.path.join(path, __appname__.lower())
  133. def shutdown_sys(password=None):
  134. """Shuts down the system.
  135. Returns True if no errors occur else False.
  136. Args:
  137. password (string): SUDO password for linux.
  138. Note:
  139. On Linux you need to provide sudo password if you don't
  140. have elevated privileges.
  141. """
  142. _stderr = subprocess.PIPE
  143. _stdin = None
  144. info = None
  145. encoding = get_encoding()
  146. if os.name == 'nt':
  147. cmd = ['shutdown', '/s', '/t', '1']
  148. # Hide subprocess window
  149. info = subprocess.STARTUPINFO()
  150. info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  151. else:
  152. if password:
  153. _stdin = subprocess.PIPE
  154. password = ('%s\n' % password).encode(encoding)
  155. cmd = ['sudo', '-S', '/sbin/shutdown', '-h', 'now']
  156. else:
  157. cmd = ['/sbin/shutdown', '-h', 'now']
  158. cmd = [item.encode(encoding, 'ignore') for item in cmd]
  159. shutdown_proc = subprocess.Popen(cmd,
  160. stderr=_stderr,
  161. stdin=_stdin,
  162. startupinfo=info)
  163. output = shutdown_proc.communicate(password)[1]
  164. return not output or output == "Password:"
  165. def to_string(data):
  166. """Convert data to string.
  167. Works for both Python2 & Python3. """
  168. return '%s' % data
  169. def get_time(seconds):
  170. """Convert given seconds to days, hours, minutes and seconds.
  171. Args:
  172. seconds (float): Time in seconds.
  173. Returns:
  174. Dictionary that contains the corresponding days, hours, minutes
  175. and seconds of the given seconds.
  176. """
  177. dtime = dict(seconds=0, minutes=0, hours=0, days=0)
  178. dtime['days'] = int(seconds / 86400)
  179. dtime['hours'] = int(seconds % 86400 / 3600)
  180. dtime['minutes'] = int(seconds % 86400 % 3600 / 60)
  181. dtime['seconds'] = int(seconds % 86400 % 3600 % 60)
  182. return dtime
  183. def get_locale_file():
  184. """Search for youtube-dlg locale file.
  185. Returns:
  186. The path to youtube-dlg locale file if exists else None.
  187. Note:
  188. Paths that get_locale_file() func searches.
  189. __main__ dir, library dir
  190. """
  191. DIR_NAME = "locale"
  192. SEARCH_DIRS = [
  193. os.path.join(absolute_path(sys.argv[0]), DIR_NAME),
  194. os.path.join(os_path_dirname(__file__), DIR_NAME),
  195. ]
  196. for directory in SEARCH_DIRS:
  197. if os_path_isdir(directory):
  198. return directory
  199. return None
  200. def get_icon_file():
  201. """Search for youtube-dlg app icon.
  202. Returns:
  203. The path to youtube-dlg icon file if exists, else returns None.
  204. """
  205. ICON_NAME = "youtube-dl-gui.png"
  206. pixmaps_dir = get_pixmaps_dir()
  207. if pixmaps_dir is not None:
  208. icon_file = os.path.join(pixmaps_dir, ICON_NAME)
  209. if os_path_exists(icon_file):
  210. return icon_file
  211. return None
  212. def get_pixmaps_dir():
  213. """Return absolute path to the pixmaps icons folder.
  214. Note:
  215. Paths we search: __main__ dir, library dir
  216. """
  217. search_dirs = [
  218. os.path.join(absolute_path(sys.argv[0]), "data"),
  219. os.path.join(os_path_dirname(__file__), "data")
  220. ]
  221. for directory in search_dirs:
  222. pixmaps_dir = os.path.join(directory, "pixmaps")
  223. if os_path_exists(pixmaps_dir):
  224. return pixmaps_dir
  225. return None
  226. def to_bytes(string):
  227. """Convert given youtube-dl size string to bytes."""
  228. value = 0.0
  229. for index, metric in enumerate(reversed(FILESIZE_METRICS)):
  230. if metric in string:
  231. value = float(string.split(metric)[0])
  232. break
  233. exponent = index * (-1) + (len(FILESIZE_METRICS) - 1)
  234. return round(value * (KILO_SIZE ** exponent), 2)
  235. def format_bytes(bytes):
  236. """Format bytes to youtube-dl size output strings."""
  237. if bytes == 0.0:
  238. exponent = 0
  239. else:
  240. exponent = int(math.log(bytes, KILO_SIZE))
  241. suffix = FILESIZE_METRICS[exponent]
  242. output_value = bytes / (KILO_SIZE ** exponent)
  243. return "%.2f%s" % (output_value, suffix)
  244. def build_command(options_list, url):
  245. """Build the youtube-dl command line string."""
  246. def escape(option):
  247. """Wrap option with double quotes if it contains special symbols."""
  248. special_symbols = [" ", "(", ")"]
  249. for symbol in special_symbols:
  250. if symbol in option:
  251. return "\"{}\"".format(option)
  252. return option
  253. # If option has special symbols wrap it with double quotes
  254. # Probably not the best solution since if the option already contains
  255. # double quotes it will be a mess, see issue #173
  256. options = [escape(option) for option in options_list]
  257. # Always wrap the url with double quotes
  258. url = "\"{}\"".format(url)
  259. return " ".join([YOUTUBEDL_BIN] + options + [url])
  260. def get_default_lang():
  261. """Get default language using the 'locale' module."""
  262. default_lang, _ = locale_getdefaultlocale()
  263. if not default_lang:
  264. default_lang = "en_US"
  265. return default_lang