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.

512 lines
14 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
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
  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 locale
  12. import subprocess
  13. from .info import __appname__
  14. from .version import __version__
  15. _RANDOM_OBJECT = object()
  16. YOUTUBEDL_BIN = 'youtube-dl'
  17. if os.name == 'nt':
  18. YOUTUBEDL_BIN += '.exe'
  19. def get_encoding():
  20. """Return system encoding. """
  21. try:
  22. encoding = locale.getpreferredencoding()
  23. 'TEST'.encode(encoding)
  24. except:
  25. encoding = 'UTF-8'
  26. return encoding
  27. def convert_on_bounds(func):
  28. """Decorator to convert string inputs & outputs.
  29. Covert string inputs & outputs between 'str' and 'unicode' at the
  30. application bounds using the preferred system encoding. It will convert
  31. all the string params (args, kwargs) to 'str' type and all the
  32. returned strings values back to 'unicode'.
  33. """
  34. def convert_item(item, to_unicode=False):
  35. """The actual function which handles the conversion.
  36. Args:
  37. item (-): Can be any python item.
  38. to_unicode (boolean): When True it will convert all the 'str' types
  39. to 'unicode'. When False it will convert all the 'unicode'
  40. types back to 'str'.
  41. """
  42. if to_unicode and isinstance(item, str):
  43. # Convert str to unicode
  44. return item.decode(get_encoding(), 'ignore')
  45. if not to_unicode and isinstance(item, unicode):
  46. # Convert unicode to str
  47. return item.encode(get_encoding(), 'ignore')
  48. if hasattr(item, '__iter__'):
  49. # Handle iterables
  50. temp_list = []
  51. for sub_item in item:
  52. if isinstance(item, dict):
  53. temp_list.append((sub_item, covert_item(item[sub_item])))
  54. else:
  55. temp_list.append(convert_item(sub_item))
  56. return type(item)(temp_list)
  57. return item
  58. def wrapper(*args, **kwargs):
  59. returned_value = func(*convert_item(args), **convert_item(kwargs))
  60. return convert_item(returned_value, True)
  61. return wrapper
  62. # See: https://github.com/MrS0m30n3/youtube-dl-gui/issues/57
  63. # Patch os functions to convert between 'str' and 'unicode' on app bounds
  64. os_getenv = convert_on_bounds(os.getenv)
  65. os_makedirs = convert_on_bounds(os.makedirs)
  66. os_path_isdir = convert_on_bounds(os.path.isdir)
  67. os_path_exists = convert_on_bounds(os.path.exists)
  68. os_path_dirname = convert_on_bounds(os.path.dirname)
  69. os_path_abspath = convert_on_bounds(os.path.abspath)
  70. os_path_realpath = convert_on_bounds(os.path.realpath)
  71. os_path_expanduser = convert_on_bounds(os.path.expanduser)
  72. # Patch Windows specific functions
  73. if os.name == 'nt':
  74. os_startfile = convert_on_bounds(os.startfile)
  75. def remove_shortcuts(path):
  76. """Return given path after removing the shortcuts. """
  77. return path.replace('~', os_path_expanduser('~'))
  78. def absolute_path(filename):
  79. """Return absolute path to the given file. """
  80. return os_path_dirname(os_path_realpath(os_path_abspath(filename)))
  81. def open_dir(path):
  82. """Open path using default file navigator.
  83. Return True if path exists else False. """
  84. path = remove_shortcuts(path)
  85. if not os_path_exists(path):
  86. return False
  87. if os.name == 'nt':
  88. os_startfile(path)
  89. else:
  90. subprocess.call(('xdg-open', path))
  91. return True
  92. def encode_tuple(tuple_to_encode):
  93. """Turn size tuple into string. """
  94. return '%s/%s' % (tuple_to_encode[0], tuple_to_encode[1])
  95. def decode_tuple(encoded_tuple):
  96. """Turn tuple string back to tuple. """
  97. s = encoded_tuple.split('/')
  98. return int(s[0]), int(s[1])
  99. def check_path(path):
  100. """Create path if not exist. """
  101. if not os_path_exists(path):
  102. os_makedirs(path)
  103. def get_config_path():
  104. """Return user config path.
  105. Note:
  106. Windows = %AppData% + app_name
  107. Linux = ~/.config + app_name
  108. """
  109. if os.name == 'nt':
  110. path = os_getenv('APPDATA')
  111. else:
  112. path = os.path.join(os_path_expanduser('~'), '.config')
  113. return os.path.join(path, __appname__.lower())
  114. def shutdown_sys(password=None):
  115. """Shuts down the system.
  116. Returns True if no errors occur else False.
  117. Args:
  118. password (string): SUDO password for linux.
  119. Note:
  120. On Linux you need to provide sudo password if you don't
  121. have elevated privileges.
  122. """
  123. _stderr = subprocess.PIPE
  124. _stdin = None
  125. info = None
  126. encoding = get_encoding()
  127. if os.name == 'nt':
  128. cmd = ['shutdown', '/s', '/t', '1']
  129. # Hide subprocess window
  130. info = subprocess.STARTUPINFO()
  131. info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  132. else:
  133. if password:
  134. _stdin = subprocess.PIPE
  135. password = ('%s\n' % password).encode(encoding)
  136. cmd = ['sudo', '-S', '/sbin/shutdown', '-h', 'now']
  137. else:
  138. cmd = ['/sbin/shutdown', '-h', 'now']
  139. cmd = [item.encode(encoding, 'ignore') for item in cmd]
  140. shutdown_proc = subprocess.Popen(cmd,
  141. stderr=_stderr,
  142. stdin=_stdin,
  143. startupinfo=info)
  144. output = shutdown_proc.communicate(password)[1]
  145. return not output or output == "Password:"
  146. def to_string(data):
  147. """Convert data to string.
  148. Works for both Python2 & Python3. """
  149. return '%s' % data
  150. def get_time(seconds):
  151. """Convert given seconds to days, hours, minutes and seconds.
  152. Args:
  153. seconds (float): Time in seconds.
  154. Returns:
  155. Dictionary that contains the corresponding days, hours, minutes
  156. and seconds of the given seconds.
  157. """
  158. dtime = dict(seconds=0, minutes=0, hours=0, days=0)
  159. dtime['days'] = int(seconds / 86400)
  160. dtime['hours'] = int(seconds % 86400 / 3600)
  161. dtime['minutes'] = int(seconds % 86400 % 3600 / 60)
  162. dtime['seconds'] = int(seconds % 86400 % 3600 % 60)
  163. return dtime
  164. def get_locale_file():
  165. """Search for youtube-dlg locale file.
  166. Returns:
  167. The path to youtube-dlg locale file if exists else None.
  168. Note:
  169. Paths that get_locale_file() func searches.
  170. __main__ dir, library dir, /usr/share/youtube-dlg/locale
  171. """
  172. DIR_NAME = 'locale'
  173. SEARCH_DIRS = [
  174. os.path.join(absolute_path(sys.argv[0]), DIR_NAME),
  175. os.path.join(os_path_dirname(__file__), DIR_NAME),
  176. os.path.join('/usr', 'share', __appname__.lower(), DIR_NAME)
  177. ]
  178. if sys.platform == 'darwin':
  179. SEARCH_DIRS.append('/usr/local/Cellar/youtube-dl-gui/{version}/share/locale'.format(version=__version__))
  180. for directory in SEARCH_DIRS:
  181. if os_path_isdir(directory):
  182. return directory
  183. return None
  184. def get_icon_file():
  185. """Search for youtube-dlg app icon.
  186. Returns:
  187. The path to youtube-dlg icon file if exists, else returns None.
  188. Note:
  189. Paths that get_icon_file() function searches.
  190. __main__ dir, library dir, /usr/share/pixmaps, $XDG_DATA_DIRS
  191. """
  192. SIZES = ('256x256', '128x128', '64x64', '48x48', '32x32', '16x16')
  193. ICON_NAME = 'youtube-dl-gui_%s.png'
  194. ICONS_LIST = [ICON_NAME % size for size in SIZES]
  195. search_dirs = [
  196. os.path.join(absolute_path(sys.argv[0]), 'icons'),
  197. os.path.join(os_path_dirname(__file__), 'icons'),
  198. ]
  199. # Append $XDG_DATA_DIRS on search_dirs
  200. path = os_getenv('XDG_DATA_DIRS')
  201. if path is not None:
  202. for xdg_path in path.split(':'):
  203. xdg_path = os.path.join(xdg_path, 'icons', 'hicolor')
  204. for size in SIZES:
  205. search_dirs.append(os.path.join(xdg_path, size, 'apps'))
  206. # Also append /usr/share/pixmaps on search_dirs
  207. search_dirs.append('/usr/share/pixmaps')
  208. for directory in search_dirs:
  209. for icon in ICONS_LIST:
  210. icon_file = os.path.join(directory, icon)
  211. if os_path_exists(icon_file):
  212. return icon_file
  213. return None
  214. class TwoWayOrderedDict(dict):
  215. """Custom data structure which implements a two way ordrered dictionary.
  216. TwoWayOrderedDict it's a custom dictionary in which you can get the
  217. key:value relationship but you can also get the value:key relationship.
  218. It also remembers the order in which the items were inserted and supports
  219. almost all the features of the build-in dict.
  220. Note:
  221. Ways to create a new dictionary.
  222. *) d = TwoWayOrderedDict(a=1, b=2) (Unordered)
  223. *) d = TwoWayOrderedDict({'a': 1, 'b': 2}) (Unordered)
  224. *) d = TwoWayOrderedDict([('a', 1), ('b', 2)]) (Ordered)
  225. *) d = TwoWayOrderedDict(zip(['a', 'b', 'c'], [1, 2, 3])) (Ordered)
  226. Examples:
  227. >>> d = TwoWayOrderedDict(a=1, b=2)
  228. >>> d['a']
  229. 1
  230. >>> d[1]
  231. 'a'
  232. >>> print d
  233. TwoWayOrderedDict([('a', 1), ('b', 2)])
  234. """
  235. _PREV = 0
  236. _KEY = 1
  237. _NEXT = 2
  238. def __init__(self, *args, **kwargs):
  239. self._items = item = []
  240. self._items += [item, None, item] # Double linked list [prev, key, next]
  241. self._items_map = {} # Map link list items into keys to speed up lookup
  242. self._load(args, kwargs)
  243. def __setitem__(self, key, value):
  244. if key in self:
  245. # If self[key] == key for example {'b': 'b'} and we
  246. # do d['b'] = 2 then we dont want to remove the 'b'
  247. # from our linked list because we will lose the order
  248. if self[key] in self._items_map and key != self[key]:
  249. self._remove_mapped_key(self[key])
  250. dict.__delitem__(self, self[key])
  251. if value in self:
  252. # If value == key we dont have to remove the
  253. # value from the items_map because the value is
  254. # the key and we want to keep the key in our
  255. # linked list in order to keep the order.
  256. if value in self._items_map and key != value:
  257. self._remove_mapped_key(value)
  258. if self[value] in self._items_map:
  259. self._remove_mapped_key(self[value])
  260. # Check if self[value] is in the dict
  261. # for cases like {'a': 'a'} where we
  262. # have only one copy instead of {'a': 1, 1: 'a'}
  263. if self[value] in self:
  264. dict.__delitem__(self, self[value])
  265. if key not in self._items_map:
  266. last = self._items[self._PREV] # self._items prev always points to the last item
  267. last[self._NEXT] = self._items[self._PREV] = self._items_map[key] = [last, key, self._items]
  268. dict.__setitem__(self, key, value)
  269. dict.__setitem__(self, value, key)
  270. def __delitem__(self, key):
  271. if self[key] in self._items_map:
  272. self._remove_mapped_key(self[key])
  273. if key in self._items_map:
  274. self._remove_mapped_key(key)
  275. dict.__delitem__(self, self[key])
  276. # Check if key is in the dict
  277. # for cases like {'a': 'a'} where we
  278. # have only one copy instead of {'a': 1, 1: 'a'}
  279. if key in self:
  280. dict.__delitem__(self, key)
  281. def __len__(self):
  282. return len(self._items_map)
  283. def __iter__(self):
  284. curr = self._items[self._NEXT]
  285. while curr is not self._items:
  286. yield curr[self._KEY]
  287. curr = curr[self._NEXT]
  288. def __reversed__(self):
  289. curr = self._items[self._PREV]
  290. while curr is not self._items:
  291. yield curr[self._KEY]
  292. curr = curr[self._PREV]
  293. def __repr__(self):
  294. return '%s(%r)' % (self.__class__.__name__, self.items())
  295. def __eq__(self, other):
  296. if isinstance(other, self.__class__):
  297. return self.items() == other.items()
  298. return False
  299. def __ne__(self, other):
  300. return not self == other
  301. def _remove_mapped_key(self, key):
  302. """Remove the given key both from the linked list
  303. and the map dictionary. """
  304. prev, __, next = self._items_map.pop(key)
  305. prev[self._NEXT] = next
  306. next[self._PREV] = prev
  307. def _load(self, args, kwargs):
  308. """Load items into our dictionary. """
  309. for item in args:
  310. if type(item) == dict:
  311. item = item.iteritems()
  312. for key, value in item:
  313. self[key] = value
  314. for key, value in kwargs.items():
  315. self[key] = value
  316. def items(self):
  317. return [(key, self[key]) for key in self]
  318. def values(self):
  319. return [self[key] for key in self]
  320. def keys(self):
  321. return list(self)
  322. def pop(self, key, default=_RANDOM_OBJECT):
  323. try:
  324. value = self[key]
  325. del self[key]
  326. except KeyError as error:
  327. if default == _RANDOM_OBJECT:
  328. raise error
  329. value = default
  330. return value
  331. def popitem(self, last=True):
  332. """Remove and return a (key, value) pair from the dictionary.
  333. If the dictionary is empty calling popitem() raises a KeyError.
  334. Args:
  335. last (bool): When False popitem() will remove the first item
  336. from the list.
  337. Note:
  338. popitem() is useful to destructively iterate over a dictionary.
  339. Raises:
  340. KeyError
  341. """
  342. if not self:
  343. raise KeyError('popitem(): dictionary is empty')
  344. if last:
  345. __, key, __ = self._items[self._PREV]
  346. else:
  347. __, key, __ = self._items[self._NEXT]
  348. value = self.pop(key)
  349. return key, value
  350. def update(self, *args, **kwargs):
  351. self._load(args, kwargs)
  352. def setdefault(self, key, default=None):
  353. try:
  354. return self[key]
  355. except KeyError:
  356. self[key] = default
  357. return default
  358. def copy(self):
  359. return self.__class__(self.items())
  360. def clear(self):
  361. self._items = item = []
  362. self._items += [item, None, item]
  363. self._items_map = {}
  364. dict.clear(self)