Browse Source

Refactor utils.py

doc-issue-template
MrS0m30n3 10 years ago
parent
commit
48ac33e4ee
7 changed files with 68 additions and 109 deletions
  1. 6
      youtube_dl_gui/DownloadThread.py
  2. 8
      youtube_dl_gui/MainFrame.py
  3. 7
      youtube_dl_gui/OptionsFrame.py
  4. 6
      youtube_dl_gui/OptionsManager.py
  5. 14
      youtube_dl_gui/OptionsParser.py
  6. 14
      youtube_dl_gui/UpdateThread.py
  7. 122
      youtube_dl_gui/utils.py

6
youtube_dl_gui/DownloadThread.py

@ -3,6 +3,7 @@
''' Youtube-dlG module to download videos & handle each download. '''
import time
import os.path
from threading import Thread
from wx import CallAfter
@ -13,8 +14,7 @@ from .OptionsParser import OptionsParser
from .DownloadObject import YoutubeDLDownloader
from .utils import (
get_youtubedl_filename,
fix_path
YOUTUBEDL_BIN
)
@ -256,5 +256,5 @@ class DownloadThread(Thread):
def _get_youtubedl_path(self):
''' Retrieve youtube-dl path. '''
path = self.opt_manager.options['youtubedl_path']
path = fix_path(path) + get_youtubedl_filename()
path = os.path.join(path, YOUTUBEDL_BIN)
return path

8
youtube_dl_gui/MainFrame.py

@ -17,9 +17,9 @@ from .OptionsManager import OptionsManager
from .DownloadThread import DownloadManager, DownloadThread
from .utils import (
get_youtubedl_filename,
YOUTUBEDL_BIN,
get_config_path,
get_icon_path,
get_icon_file,
shutdown_sys,
get_time,
open_dir
@ -81,7 +81,7 @@ class MainFrame(wx.Frame):
self.log_manager = log_manager
self.download_manager = None
self.update_thread = None
self.app_icon = get_icon_path()
self.app_icon = get_icon_file()
if self.app_icon is not None:
self.app_icon = wx.Icon(self.app_icon, wx.BITMAP_TYPE_PNG)
@ -177,7 +177,7 @@ class MainFrame(wx.Frame):
def _youtubedl_exist(self):
''' Return True if youtube-dl executable exists. '''
path = os.path.join(self.opt_manager.options['youtubedl_path'],
get_youtubedl_filename())
YOUTUBEDL_BIN)
return os.path.exists(path)

7
youtube_dl_gui/OptionsFrame.py

@ -8,10 +8,7 @@ import wx
from .LogManager import LogGUI
from .version import __version__
from .utils import (
get_icon_path,
fix_path
)
from .data import (
__descriptionfull__,
@ -1174,7 +1171,7 @@ class GeneralTab(TabPanel):
def save_options(self):
''' Save panel options to OptionsHandler object. '''
self.opt_manager.options['save_path'] = fix_path(self.savepath_box.GetValue())
self.opt_manager.options['save_path'] = self.savepath_box.GetValue()
class CMDTab(TabPanel):

6
youtube_dl_gui/OptionsManager.py

@ -6,9 +6,7 @@ import json
import os.path
from .utils import (
check_path,
get_home,
fix_path
check_path
)
@ -55,7 +53,7 @@ class OptionsManager(object):
def load_default(self):
''' Load default options. '''
self.options = {
'save_path': get_home(),
'save_path': os.path.expanduser('~'),
'video_format': 'default',
'second_video_format': 'none',
'to_audio': False,

14
youtube_dl_gui/OptionsParser.py

@ -2,8 +2,10 @@
''' Parse OptionsManager.options. '''
import os.path
from .utils import (
fix_path
remove_shortcuts
)
SUBS_LANG = {
@ -184,15 +186,17 @@ class OptionsParser():
self.options_list.append('--embed-subs')
def _set_output_options(self):
save_path = fix_path(self._options['save_path'])
save_path = self._options['save_path']
self.options_list.append('-o')
if self._options['output_format'] == 'id':
self.options_list.append(save_path + '%(id)s.%(ext)s')
save_path = os.path.join(save_path, '%(id)s.%(ext)s')
elif self._options['output_format'] == 'title':
self.options_list.append(save_path + '%(title)s.%(ext)s')
save_path = os.path.join(save_path, '%(title)s.%(ext)s')
elif self._options['output_format'] == 'custom':
self.options_list.append(save_path + self._options['output_template'])
save_path = os.path.join(save_path, self._options['output_template'])
self.options_list.append(save_path)
if self._options['restrict_filenames']:
self.options_list.append('--restrict-filenames')

14
youtube_dl_gui/UpdateThread.py

@ -2,6 +2,7 @@
''' Youtube-dlG module to download youtube-dl. '''
import os.path
from threading import Thread
from urllib2 import urlopen, URLError, HTTPError
@ -10,9 +11,8 @@ from wx.lib.pubsub import setuparg1
from wx.lib.pubsub import pub as Publisher
from .utils import (
get_youtubedl_filename,
check_path,
fix_path
YOUTUBEDL_BIN,
check_path
)
@ -34,17 +34,15 @@ class UpdateThread(Thread):
def __init__(self, download_path, quiet):
super(UpdateThread, self).__init__()
self.download_path = fix_path(download_path)
self.download_path = download_path
self.quiet = quiet
self.start()
def run(self):
self._callafter("Downloading latest youtube-dl. Please wait...")
youtubedl = get_youtubedl_filename()
source_file = self.LATEST_YOUTUBE_DL + youtubedl
destination_file = self.download_path + youtubedl
source_file = self.LATEST_YOUTUBE_DL + YOUTUBEDL_BIN
destination_file = os.path.join(self.download_path, YOUTUBEDL_BIN)
check_path(self.download_path)

122
youtube_dl_gui/utils.py

@ -7,37 +7,18 @@ import sys
import subprocess
def path_seperator():
''' Return path seperator for current OS. '''
return '\\' if os.name == 'nt' else '/'
YOUTUBEDL_BIN = 'youtube-dl'
if os.name == 'nt':
YOUTUBEDL_BIN += '.exe'
def fix_path(path):
''' Add path seperator at the end of the path
if not exist and replace ~ with user $HOME '''
if path == '':
return path
if path[-1:] != path_seperator():
path += path_seperator()
path_list = path.split(path_seperator())
for index, item in enumerate(path_list):
if item == '~':
path_list[index] = get_home()
path = path_seperator().join(path_list)
def remove_shortcuts(path):
''' Return the path after removing the shortcuts. '''
path = path.replace('~', os.path.expanduser('~'))
return path
def get_home():
''' Return user $HOME path. '''
return os.path.expanduser("~")
def abs_path(filename):
def absolute_path(filename):
''' Return absolute path. '''
path = os.path.realpath(os.path.abspath(filename))
return os.path.dirname(path)
@ -45,6 +26,8 @@ def abs_path(filename):
def open_dir(path):
''' Open path using default file navigator. '''
path = remove_shortcuts(path)
if os.name == 'nt':
os.startfile(path)
else:
@ -57,21 +40,12 @@ def check_path(path):
os.makedirs(path)
def get_youtubedl_filename():
''' Return youtube-dl executable name. '''
youtubedl_fl = 'youtube-dl'
if os.name == 'nt':
youtubedl_fl += '.exe'
return youtubedl_fl
def get_config_path():
''' Return user config path. Windows=AppData, Linux=~/.config. '''
if os.name == 'nt':
path = os.getenv('APPDATA')
else:
path = fix_path(get_home()) + '.config'
path = os.path.join(os.path.expanduser('~'), '.config')
return path
@ -83,76 +57,64 @@ def shutdown_sys(password=''):
if os.name == 'nt':
subprocess.call(['shutdown', '/s', '/t', '1'])
else:
if password == '':
if not password:
subprocess.call(['/sbin/shutdown', '-h', 'now'])
else:
shutdown_proc = subprocess.Popen(
['sudo', '-S', '/sbin/shutdown', '-h', 'now'],
stdin=subprocess.PIPE
)
shutdown_proc.communicate(password + '\n')
subprocess.Popen(['sudo', '-S', '/sbin/shutdown', '-h', 'now'],
stdin=subprocess.PIPE).communicate(password + '\n')
def get_time(seconds):
''' Return day, hours, minutes, seconds from given seconds. '''
dtime = {'seconds': 0, 'minutes': 0, 'hours': 0, 'days': 0}
if seconds < 60:
dtime['seconds'] = seconds
elif seconds < 3600:
dtime['minutes'] = seconds / 60
dtime['seconds'] = seconds % 60
elif seconds < 86400:
dtime['hours'] = seconds / 3600
dtime['minutes'] = seconds % 3600 / 60
dtime['seconds'] = seconds % 3600 % 60
else:
dtime['days'] = seconds / 86400
dtime['hours'] = seconds % 86400 / 3600
dtime['minutes'] = seconds % 86400 % 3600 / 60
dtime['seconds'] = seconds % 86400 % 3600 % 60
dtime = dict(seconds=0, minutes=0, hours=0, days=0)
dtime['days'] = seconds / 86400
dtime['hours'] = seconds % 86400 / 3600
dtime['minutes'] = seconds % 86400 % 3600 / 60
dtime['seconds'] = seconds % 86400 % 3600 % 60
return dtime
def get_icon_path():
def get_icon_file():
''' Return path to the icon file if exist else return None.
Search __main__ dir, $XDG_DATA_DIRS, /usr/share/pixmaps in that order. '''
SIZES = ('256x256', '128x128', '64x64', '48x48', '32x32', '16x16')
ICON_NAME = 'youtube-dl-gui_%s.png'
ICONS_LIST = [ICON_NAME % size for size in SIZES]
# __main__ dir
path = os.path.join(abs_path(sys.argv[0]), 'icons')
path = os.path.join(absolute_path(sys.argv[0]), 'icons')
for icon in ICONS_LIST:
icon_path = os.path.join(path, icon)
icon_file = os.path.join(path, icon)
if os.path.exists(icon_path):
return icon_path
if os.path.exists(icon_file):
return icon_file
# $XDG_DATA_DIRS/icons
path = os.getenv('XDG_DATA_DIRS')
if os.name != 'nt':
# $XDG_DATA_DIRS/icons
path = os.getenv('XDG_DATA_DIRS')
if path is not None:
for temp_path in path.split(':'):
temp_path = os.path.join(temp_path, 'icons', 'hicolor')
if path is not None:
for xdg_path in path.split(':'):
xdg_path = os.path.join(xdg_path, 'icons', 'hicolor')
for size in SIZES:
icon_path = os.path.join(temp_path, size, 'apps')
icon_path = fix_path(icon_path) + ICON_NAME % size
for size in SIZES:
icon_name = ICON_NAME % size
icon_file = os.path.join(xdg_path, size, 'apps', icon_name)
if os.path.exists(icon_path):
return icon_path
if os.path.exists(icon_file):
return icon_file
# /usr/share/pixmaps
path = '/usr/share/pixmaps/'
for icon in ICONS_LIST:
icon_path = path + icon
# /usr/share/pixmaps
path = '/usr/share/pixmaps'
for icon in ICONS_LIST:
icon_file = os.path.join(path, icon)
if os.path.exists(icon_path):
return icon_path
if os.path.exists(icon_file):
return icon_file
return None
Loading…
Cancel
Save