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.

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