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.

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