Skip to content

Commit

Permalink
Merge pull request #3 from Tastyep/develop
Browse files Browse the repository at this point in the history
Preparing 1.0.1

- Rewrite and test the setup script
- Provide systemd configuration file to make opencast a service bootable at startup
- Format code using yapf

More in commits
  • Loading branch information
Tastyep authored Nov 13, 2019
2 parents a789494 + 4db6a5a commit 696e9be
Show file tree
Hide file tree
Showing 16 changed files with 205 additions and 270 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
*.pyc
*~
*.xpi
Pipfile.lock
69 changes: 42 additions & 27 deletions OpenCast.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,40 @@ PROJECT_NAME="OpenCast"
LOG_DIR="log"
LOG_FILE="$PROJECT_NAME.log"

function is_server_running() {
lsof -t -i :2020
}

function wait_for_server() {
while [ ! "$(is_server_running)" ]; do
sleep 1
done
}

function element_in() {
local e match="$1"
shift
for e; do [[ "$e" == "$match" ]] && return 0; done
return 1
}

function start() {
if [ "$(lsof -t -i :2020)" ]; then
if [ "$(is_server_running)" ]; then
echo "$PROJECT_NAME server is already running."
return
fi

echo "Checking for updates."
cd "$PROJECT_DIR" || exit 1
if [[ "$1" == "-u" ]]; then
update
fi

git pull
cd "$PROJECT_DIR" || exit 1
mkdir -p "$LOG_DIR"

echo "Starting $PROJECT_NAME server."
pipenv run python -m "$PROJECT_NAME" &

wait_for_server
pid="$(pgrep -f "python -m $PROJECT_NAME")"
echo "$pid" >"$PROJECT_DIR/$PROJECT_NAME.pid"
}
Expand All @@ -33,6 +54,12 @@ function restart() {
stop && start
}

function update() {
echo "Checking for updates."

(cd "$PROJECT_DIR" && git pull && pipenv update)
}

function status() {
echo -n "$PROJECT_NAME is ... "
[ "$(lsof -t -i :2020)" ] && echo "UP" || echo "DOWN"
Expand All @@ -47,26 +74,14 @@ function tests() {
pipenv run python -m unittest discover -v -p "*_test.py"
}

case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
status)
status
;;
logs)
logs
;;
test)
tests
;;
*)
echo "Usage: $0 {start|stop|restart|status|logs|test}"
;;
esac
COMMANDS=("start" "stop" "restart" "update" "status" "logs" "tests")
if element_in "$1" "${COMMANDS[@]}"; then
COMMAND="$1"
shift
"$COMMAND" "$@"
else
echo "Usage: $0 {$(
IFS='|'
echo "${COMMANDS[*]}"
)}"
fi
8 changes: 7 additions & 1 deletion OpenCast/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ def _real_main(argv):
config.load_from_file('{}/config.ini'.format(app_path))

s = Server()
s.run()
try:
s.run()
except Exception as e:
logger = logging.getLogger(__name__)
logger.debug("opencast stopped: {}".format(str(e)))
finally:
pass


def main(argv=None):
Expand Down
15 changes: 6 additions & 9 deletions OpenCast/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ class Singleton(type):

def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(
Singleton, cls).__call__(*args, **kwargs)
cls._instances[cls] = super(Singleton,
cls).__call__(*args, **kwargs)
return cls._instances[cls]


Expand Down Expand Up @@ -59,10 +59,8 @@ def _load_cache(self):
parser = self._parser[key]

for entry_name in dir(category):
if (
entry_name.startswith('__') or
not self._parser.has_option(key, entry_name)
):
if (entry_name.startswith('__')
or not self._parser.has_option(key, entry_name)):
continue
self._parse_entry(parser, category, entry_name)

Expand All @@ -78,9 +76,8 @@ def _parse_entry(self, parser, category, entry_name):
value = parser.getboolean(entry_name, fallback=entry)
else:
value = parser.get(entry_name, fallback=entry)
if (type(entry) is str and
(value.startswith(("'", '"')) and
value[0] is value[-1])):
if (type(entry) is str and (value.startswith(
("'", '"')) and value[0] is value[-1])):
value = value[1:-1]
setattr(category, entry_name, value)

Expand Down
19 changes: 10 additions & 9 deletions OpenCast/video_controller.py → OpenCast/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
logger = logging.getLogger(__name__)


class VideoController(object):
class Controller(object):
def __init__(self, player, downloader):
self._player = player
self._downloader = downloader
Expand Down Expand Up @@ -62,12 +62,13 @@ def shift_subtitle(self, increase):

def change_volume(self, increase):
self._player.change_volume(increase)
logger.debug("[controller] change player volume, increase: {}"
.format(increase))
logger.debug(
"[controller] change player volume, increase: {}".format(increase))

def seek_time(self, forward, long):
logger.debug("[controller] seek video time, forward={}, long={}"
.format(forward, long))
logger.debug(
"[controller] seek video time, forward={}, long={}".format(
forward, long))
self._player.seek(forward, long)

# Getter methods
Expand All @@ -91,16 +92,16 @@ def _queue_video(self, video, dl_callback, first):
playlist_id = uuid.uuid4()
urls = self._downloader.extract_playlist(video.url)
videos = [Video(u, playlist_id) for u in urls]
logger.debug("[controller] playlist url unfolded to {}"
.format(videos))
logger.debug(
"[controller] playlist url unfolded to {}".format(videos))
self._downloader.queue(videos, dl_callback, first)
else:
logger.debug("[controller] queue single video: {}".format(video))
self._downloader.queue([video], dl_callback, first)


def make_video_controller():
def make_controller():
player = player_wrapper.make_wrapper()
downloader = video_downloader.make_video_downloader()

return VideoController(player, downloader)
return Controller(player, downloader)
14 changes: 6 additions & 8 deletions OpenCast/download_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,19 @@ def log_download(self, d):

def _log_download_info(self, d):
filename = d.get('filename', 'unknown')
self._logger.info("[downloader] {} | {} | {}"
.format(filename,
self._format_ratio(d),
self._format_speed(d)))
self._logger.info("[downloader] {} | {} | {}".format(
filename, self._format_ratio(d), self._format_speed(d)))

def _log_download_error(self, d):
filename = d.get('filename', 'unknown')
self._logger.error("[downloader] error downloading {}: {}"
.format(filename, d))
self._logger.error("[downloader] error downloading {}: {}".format(
filename, d))

def _log_download_finished(self, d):
filename = d.get('filename', 'unknown')
total = d.get('total_bytes', 0)
self._logger.info("[downloader] finished downloading {} ({})"
.format(filename, size(total)))
self._logger.info("[downloader] finished downloading {} ({})".format(
filename, size(total)))

def _format_ratio(self, d):
downloaded = d.get('downloaded_bytes', None)
Expand Down
43 changes: 22 additions & 21 deletions OpenCast/player_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ def _stop_impl(self, stop_browsing=False):

def is_stopped():
return not self.playing()

if not self._sync(5000, 500, is_stopped):
logger.error("[player] cannot stop")

Expand Down Expand Up @@ -177,14 +178,14 @@ def impl():

def seek(self, forward, long):
if forward:
if long: # Up arrow, + 5 minutes
if long: # Up arrow, + 5 minutes
self._exec_command('seek', 300)
else: # Right arrow, + 30 seconds
else: # Right arrow, + 30 seconds
self._exec_command('seek', 30)
else:
if long: # Down arrow, - 5 minutees
if long: # Down arrow, - 5 minutees
self._exec_command('seek', -300)
else: # Left arrow, - 30 seconds
else: # Left arrow, - 30 seconds
self._exec_command('seek', -30)

def playing(self):
Expand All @@ -210,19 +211,20 @@ def _make_player(self, video):
command += ['--blank']

for tries in range(5):
logger.debug("[player] opening {} with opt: {}".format(video, command))
logger.debug("[player] opening {} with opt: {}".format(
video, command))
try:
self._player = self._player_factory(video.path,
command,
'org.mpris.MediaPlayer2.omxplayer1',
self._on_exit)
self._player = self._player_factory(
video.path, command, 'org.mpris.MediaPlayer2.omxplayer1',
self._on_exit)
return True
except SystemError:
logger.error("[player] couldn't connect to dbus")
# Kill instance if it is a dbus problem
for proc in psutil.process_iter():
if "omxplayer" in proc.name():
logger.debug("[player] killing process {}".format(proc.name()))
logger.debug("[player] killing process {}".format(
proc.name()))
proc.kill()

return False
Expand All @@ -234,8 +236,9 @@ def _play(self):
self._prev_impl()

if self._history.browsing():
logger.debug("[player] picking video from history at index ({})"
.format(self._history.index()))
logger.debug(
"[player] picking video from history at index ({})".format(
self._history.index()))
video = self._history.current_item()
self._history.next()
else:
Expand All @@ -260,15 +263,15 @@ def _play(self):
def _play_videos(self):
def should_play():
def impl():
logger.debug("[player] should_play: playing: {}, play_next: {}, qSize: {}, browsing: {}, loop {}, hSize: {}"
.format(self.playing(), self._play_next, len(self._queue), self._history.browsing(), config.loop_last, self._history.size()))
logger.debug(
"[player] should_play: playing: {}, play_next: {}, qSize: {}, browsing: {}, loop {}, hSize: {}"
.format(self.playing(), self._play_next, len(self._queue),
self._history.browsing(), config.loop_last,
self._history.size()))
return (self._stopped or
(not self.playing() and self._play_next and
(len(self._queue) > 0 or self._history.browsing() or
(config.loop_last and self._history.size() > 0)
)
)
)
(config.loop_last and self._history.size() > 0))))

logger.debug("[player] should_play()")
f = self._executor.submit(impl)
Expand Down Expand Up @@ -307,9 +310,7 @@ def _on_exit(self, player, code):

def player_factory():
def make_player(path, command, dbus_name, exit_callback):
player = OMXPlayer(Path(path),
command,
dbus_name=dbus_name)
player = OMXPlayer(Path(path), command, dbus_name=dbus_name)

player.exitEvent += exit_callback
return player
Expand Down
19 changes: 12 additions & 7 deletions OpenCast/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from . import (
config,
video_controller,
controller,
)

logger = logging.getLogger(__name__)
Expand All @@ -24,7 +24,7 @@
class Server(object):
def __init__(self):
self._app = Bottle()
self._controller = video_controller.make_video_controller()
self._controller = controller.make_controller()

TEMPLATE_PATH.insert(0, os.path.join(app_path, 'views'))
SimpleTemplate.defaults['get_url'] = self._app.get_url
Expand All @@ -33,13 +33,18 @@ def run(self):
serverConfig = config.config['Server']

self._set_routes()
logger.info("[server] started on {}:{}"
.format(serverConfig.host, serverConfig.port))
run(self._app, host=serverConfig.host, port=serverConfig.port,
reloader=False, debug=True, quiet=True)
logger.info("[server] started on {}:{}".format(serverConfig.host,
serverConfig.port))
run(self._app,
host=serverConfig.host,
port=serverConfig.port,
reloader=False,
debug=True,
quiet=True)

def _set_routes(self):
self._app.route('/static/<filename>', name='static',
self._app.route('/static/<filename>',
name='static',
callback=self._serve_file)
self._app.route('/', callback=self._remote)
self._app.route('/remote', callback=self._remote)
Expand Down
15 changes: 9 additions & 6 deletions OpenCast/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,17 @@ def __init__(self, url, playlist_id=None):

def __repr__(self):
title = '' if self._title is None else str(self._title)
playlist_id = '' if self._playlist_id is None else str(self._playlist_id)
return str({'title': title,
'url': str(self._url),
'playlist_id': playlist_id})
playlist_id = '' if self._playlist_id is None else str(
self._playlist_id)
return str({
'title': title,
'url': str(self._url),
'playlist_id': playlist_id
})

def __eq__(self, other):
return (self._url == other._url and
self._playlist_id == other._playlist_id)
return (self._url == other._url
and self._playlist_id == other._playlist_id)

@property
def url(self):
Expand Down
Loading

0 comments on commit 696e9be

Please sign in to comment.