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.

363 lines
9.3 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
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
  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 locale
  13. import subprocess
  14. try:
  15. from twodict import TwoWayOrderedDict
  16. except ImportError as error:
  17. print error
  18. sys.exit(1)
  19. from .info import __appname__
  20. from .version import __version__
  21. _RANDOM_OBJECT = object()
  22. YOUTUBEDL_BIN = 'youtube-dl'
  23. if os.name == 'nt':
  24. YOUTUBEDL_BIN += '.exe'
  25. def get_encoding():
  26. """Return system encoding. """
  27. try:
  28. encoding = locale.getpreferredencoding()
  29. 'TEST'.encode(encoding)
  30. except:
  31. encoding = 'UTF-8'
  32. return encoding
  33. def convert_on_bounds(func):
  34. """Decorator to convert string inputs & outputs.
  35. Covert string inputs & outputs between 'str' and 'unicode' at the
  36. application bounds using the preferred system encoding. It will convert
  37. all the string params (args, kwargs) to 'str' type and all the
  38. returned strings values back to 'unicode'.
  39. """
  40. def convert_item(item, to_unicode=False):
  41. """The actual function which handles the conversion.
  42. Args:
  43. item (-): Can be any python item.
  44. to_unicode (boolean): When True it will convert all the 'str' types
  45. to 'unicode'. When False it will convert all the 'unicode'
  46. types back to 'str'.
  47. """
  48. if to_unicode and isinstance(item, str):
  49. # Convert str to unicode
  50. return item.decode(get_encoding(), 'ignore')
  51. if not to_unicode and isinstance(item, unicode):
  52. # Convert unicode to str
  53. return item.encode(get_encoding(), 'ignore')
  54. if hasattr(item, '__iter__'):
  55. # Handle iterables
  56. temp_list = []
  57. for sub_item in item:
  58. if isinstance(item, dict):
  59. temp_list.append((sub_item, covert_item(item[sub_item])))
  60. else:
  61. temp_list.append(convert_item(sub_item))
  62. return type(item)(temp_list)
  63. return item
  64. def wrapper(*args, **kwargs):
  65. returned_value = func(*convert_item(args), **convert_item(kwargs))
  66. return convert_item(returned_value, True)
  67. return wrapper
  68. # See: https://github.com/MrS0m30n3/youtube-dl-gui/issues/57
  69. # Patch os functions to convert between 'str' and 'unicode' on app bounds
  70. os_getenv = convert_on_bounds(os.getenv)
  71. os_makedirs = convert_on_bounds(os.makedirs)
  72. os_path_isdir = convert_on_bounds(os.path.isdir)
  73. os_path_exists = convert_on_bounds(os.path.exists)
  74. os_path_dirname = convert_on_bounds(os.path.dirname)
  75. os_path_abspath = convert_on_bounds(os.path.abspath)
  76. os_path_realpath = convert_on_bounds(os.path.realpath)
  77. os_path_expanduser = convert_on_bounds(os.path.expanduser)
  78. # Patch Windows specific functions
  79. if os.name == 'nt':
  80. os_startfile = convert_on_bounds(os.startfile)
  81. def remove_file(filename):
  82. if os_path_exists(filename):
  83. os.remove(filename)
  84. return True
  85. return False
  86. def remove_shortcuts(path):
  87. """Return given path after removing the shortcuts. """
  88. return path.replace('~', os_path_expanduser('~'))
  89. def absolute_path(filename):
  90. """Return absolute path to the given file. """
  91. return os_path_dirname(os_path_realpath(os_path_abspath(filename)))
  92. def open_file(file_path):
  93. """Open file in file_path using the default OS application.
  94. Returns:
  95. True on success else False.
  96. """
  97. file_path = remove_shortcuts(file_path)
  98. if not os_path_exists(file_path):
  99. return False
  100. if os.name == "nt":
  101. os_startfile(file_path)
  102. else:
  103. subprocess.call(("xdg-open", file_path))
  104. return True
  105. def encode_tuple(tuple_to_encode):
  106. """Turn size tuple into string. """
  107. return '%s/%s' % (tuple_to_encode[0], tuple_to_encode[1])
  108. def decode_tuple(encoded_tuple):
  109. """Turn tuple string back to tuple. """
  110. s = encoded_tuple.split('/')
  111. return int(s[0]), int(s[1])
  112. def check_path(path):
  113. """Create path if not exist. """
  114. if not os_path_exists(path):
  115. os_makedirs(path)
  116. def get_config_path():
  117. """Return user config path.
  118. Note:
  119. Windows = %AppData% + app_name
  120. Linux = ~/.config + app_name
  121. """
  122. if os.name == 'nt':
  123. path = os_getenv('APPDATA')
  124. else:
  125. path = os.path.join(os_path_expanduser('~'), '.config')
  126. return os.path.join(path, __appname__.lower())
  127. def shutdown_sys(password=None):
  128. """Shuts down the system.
  129. Returns True if no errors occur else False.
  130. Args:
  131. password (string): SUDO password for linux.
  132. Note:
  133. On Linux you need to provide sudo password if you don't
  134. have elevated privileges.
  135. """
  136. _stderr = subprocess.PIPE
  137. _stdin = None
  138. info = None
  139. encoding = get_encoding()
  140. if os.name == 'nt':
  141. cmd = ['shutdown', '/s', '/t', '1']
  142. # Hide subprocess window
  143. info = subprocess.STARTUPINFO()
  144. info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  145. else:
  146. if password:
  147. _stdin = subprocess.PIPE
  148. password = ('%s\n' % password).encode(encoding)
  149. cmd = ['sudo', '-S', '/sbin/shutdown', '-h', 'now']
  150. else:
  151. cmd = ['/sbin/shutdown', '-h', 'now']
  152. cmd = [item.encode(encoding, 'ignore') for item in cmd]
  153. shutdown_proc = subprocess.Popen(cmd,
  154. stderr=_stderr,
  155. stdin=_stdin,
  156. startupinfo=info)
  157. output = shutdown_proc.communicate(password)[1]
  158. return not output or output == "Password:"
  159. def to_string(data):
  160. """Convert data to string.
  161. Works for both Python2 & Python3. """
  162. return '%s' % data
  163. def get_time(seconds):
  164. """Convert given seconds to days, hours, minutes and seconds.
  165. Args:
  166. seconds (float): Time in seconds.
  167. Returns:
  168. Dictionary that contains the corresponding days, hours, minutes
  169. and seconds of the given seconds.
  170. """
  171. dtime = dict(seconds=0, minutes=0, hours=0, days=0)
  172. dtime['days'] = int(seconds / 86400)
  173. dtime['hours'] = int(seconds % 86400 / 3600)
  174. dtime['minutes'] = int(seconds % 86400 % 3600 / 60)
  175. dtime['seconds'] = int(seconds % 86400 % 3600 % 60)
  176. return dtime
  177. def get_locale_file():
  178. """Search for youtube-dlg locale file.
  179. Returns:
  180. The path to youtube-dlg locale file if exists else None.
  181. Note:
  182. Paths that get_locale_file() func searches.
  183. __main__ dir, library dir, /usr/share/youtube-dlg/locale
  184. """
  185. DIR_NAME = 'locale'
  186. SEARCH_DIRS = [
  187. os.path.join(absolute_path(sys.argv[0]), DIR_NAME),
  188. os.path.join(os_path_dirname(__file__), DIR_NAME),
  189. os.path.join('/usr', 'share', __appname__.lower(), DIR_NAME)
  190. ]
  191. if sys.platform == 'darwin':
  192. SEARCH_DIRS.append('/usr/local/Cellar/youtube-dl-gui/{version}/share/locale'.format(version=__version__))
  193. for directory in SEARCH_DIRS:
  194. if os_path_isdir(directory):
  195. return directory
  196. return None
  197. def get_icon_file():
  198. """Search for youtube-dlg app icon.
  199. Returns:
  200. The path to youtube-dlg icon file if exists, else returns None.
  201. Note:
  202. Paths that get_icon_file() function searches.
  203. __main__ dir, library dir, $XDG_DATA_DIRS
  204. """
  205. ICON_NAME = "youtube-dl-gui.png"
  206. SIZES = ("256", "128", "64", "48", "32", "16")
  207. DIR_TEMPLATE = os.path.join("icons", "hicolor", "{size}x{size}", "apps", ICON_NAME)
  208. ICONS = [DIR_TEMPLATE.format(size=size) for size in SIZES]
  209. search_dirs = [
  210. os.path.join(absolute_path(sys.argv[0]), "data"),
  211. os.path.join(os_path_dirname(__file__), "data"),
  212. ]
  213. # Append $XDG_DATA_DIRS on search_dirs
  214. path = os_getenv("XDG_DATA_DIRS")
  215. if path is not None:
  216. for xdg_path in path.split(':'):
  217. search_dirs.append(xdg_path)
  218. # Also append /usr/share/pixmaps on search_dirs
  219. #search_dirs.append("/usr/share/pixmaps")
  220. for directory in search_dirs:
  221. for icon in ICONS:
  222. icon_file = os.path.join(directory, icon)
  223. if os_path_exists(icon_file):
  224. return icon_file
  225. return None
  226. def get_pixmaps_dir():
  227. """Return absolute path to the pixmaps icons folder."""
  228. # TODO probably will need support for other directories py2exe etc
  229. return os.path.join(absolute_path(__file__), "data", "pixmaps")
  230. def json_load(filename):
  231. if os_path_exists(filename):
  232. with open(filename) as input_json_file:
  233. return json.load(input_json_file)
  234. return []
  235. def json_store(filename, item):
  236. with open(filename, 'w') as output_json_file:
  237. json.dump(item, output_json_file)
  238. def read_formats():
  239. """Returns a twodict containing all the formats from 'data/formats'."""
  240. # TODO Support for other directories? Test with py2exe
  241. formats_file = os.path.join(absolute_path(__file__), "data", "formats")
  242. if os_path_exists(formats_file):
  243. formats_dict = TwoWayOrderedDict()
  244. with open(formats_file) as input_file:
  245. for line in input_file:
  246. format_id, format_label = line.split('-')
  247. formats_dict[format_id.strip()] = format_label.strip()
  248. return formats_dict
  249. return None