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.

387 lines
10 KiB

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