From d18734910d86b3b3777dd3708e41753dcbfb21d8 Mon Sep 17 00:00:00 2001 From: DYefremov Date: Thu, 26 Nov 2020 13:36:45 +0300 Subject: [PATCH] small http api refactoring --- app/connections.py | 103 ++++++++++++++++++++------------------ app/ui/control.py | 22 ++++---- app/ui/main_app_window.py | 20 ++++---- app/ui/transmitter.py | 16 +++--- 4 files changed, 82 insertions(+), 79 deletions(-) diff --git a/app/connections.py b/app/connections.py index 23c7eb39..6cd7e1f7 100644 --- a/app/connections.py +++ b/app/connections.py @@ -35,36 +35,6 @@ class DownloadType(Enum): EPG = 5 -class HttpRequestType(Enum): - ZAP = "zap?sRef=" - INFO = "about" - SIGNAL = "signal" - STREAM = "stream.m3u?ref=" - STREAM_CURRENT = "streamcurrent.m3u" - CURRENT = "getcurrent" - TEST = None - TOKEN = "session" - # Player - PLAY = "mediaplayerplay?file=" - PLAYER_LIST = "mediaplayerlist?path=playlist" - PLAYER_PLAY = "mediaplayercmd?command=play" - PLAYER_NEXT = "mediaplayercmd?command=next" - PLAYER_PREV = "mediaplayercmd?command=previous" - PLAYER_STOP = "mediaplayercmd?command=stop" - PLAYER_REMOVE = "mediaplayerremove?file=" - # Remote control - POWER = "powerstate?newstate=" - REMOTE = "remotecontrol?command=" - VOL = "vol?set=set" - # EPG - EPG = "epgservice?sRef=" - # Timer - TIMER = "" - TIMER_LIST = "timerlist" - # Screenshot - GRUB = "grab?format=jpg&" - - class TestException(Exception): pass @@ -319,7 +289,7 @@ def http(user, password, url, callback, use_ssl=False): while True: url, message = yield - resp = get_response(HttpRequestType.TEST, url, data).get("e2statetext", None) + resp = get_response(HttpAPI.Request.TEST, url, data).get("e2statetext", None) callback("HTTP: {} {}\n".format(message, "Successful." if resp and message else "")) @@ -353,6 +323,35 @@ def telnet(host, port=23, user="", password="", timeout=5): class HttpAPI: __MAX_WORKERS = 4 + class Request(Enum): + ZAP = "zap?sRef=" + INFO = "about" + SIGNAL = "signal" + STREAM = "stream.m3u?ref=" + STREAM_CURRENT = "streamcurrent.m3u" + CURRENT = "getcurrent" + TEST = None + TOKEN = "session" + # Player + PLAY = "mediaplayerplay?file=" + PLAYER_LIST = "mediaplayerlist?path=playlist" + PLAYER_PLAY = "mediaplayercmd?command=play" + PLAYER_NEXT = "mediaplayercmd?command=next" + PLAYER_PREV = "mediaplayercmd?command=previous" + PLAYER_STOP = "mediaplayercmd?command=stop" + PLAYER_REMOVE = "mediaplayerremove?file=" + # Remote control + POWER = "powerstate?newstate=" + REMOTE = "remotecontrol?command=" + VOL = "vol?set=set" + # EPG + EPG = "epgservice?sRef=" + # Timer + TIMER = "" + TIMER_LIST = "timerlist" + # Screenshot + GRUB = "grab?format=jpg&" + class Remote(str, Enum): """ Args for HttpRequestType [REMOTE] class. """ UP = "103" @@ -396,14 +395,18 @@ class HttpAPI: url = self._base_url + req_type.value data = self._data - if req_type is HttpRequestType.ZAP or req_type is HttpRequestType.STREAM: + if req_type is self.Request.ZAP or req_type is self.Request.STREAM: url += urllib.parse.quote(ref) - elif req_type is HttpRequestType.PLAY or req_type is HttpRequestType.PLAYER_REMOVE: + elif req_type is self.Request.PLAY or req_type is self.Request.PLAYER_REMOVE: url += "{}{}".format(ref_prefix, urllib.parse.quote(ref).replace("%3A", "%253A")) - elif req_type is HttpRequestType.GRUB: + elif req_type is self.Request.GRUB: data = None # Must be disabled for token-based security. url = "{}/{}{}".format(self._main_url, req_type.value, ref) - elif req_type in (HttpRequestType.REMOTE, HttpRequestType.POWER, HttpRequestType.VOL, HttpRequestType.EPG): + elif req_type in (self.Request.REMOTE, + self.Request.POWER, + self.Request.VOL, + self.Request.EPG, + self.Request.TIMER): url += ref def done_callback(f): @@ -419,12 +422,12 @@ class HttpAPI: self._main_url = "http{}://{}:{}".format("s" if use_ssl else "", self._settings.host, self._settings.http_port) self._base_url = "{}/web/".format(self._main_url) init_auth(user, password, self._main_url, use_ssl) - url = "{}/web/{}".format(self._main_url, HttpRequestType.TOKEN.value) + url = "{}/web/{}".format(self._main_url, self.Request.TOKEN.value) s_id = get_session_id(user, password, url) if s_id != "0": self._data = urllib.parse.urlencode({"user": user, "password": password, "sessionid": s_id}).encode("utf-8") - self.send(HttpRequestType.INFO, None, self.init_callback) + self.send(self.Request.INFO, None, self.init_callback) def init_callback(self, info): if info: @@ -447,30 +450,30 @@ class HttpAPI: def get_response(req_type, url, data=None): try: with urlopen(Request(url, data=data), timeout=10) as f: - if req_type is HttpRequestType.STREAM or req_type is HttpRequestType.STREAM_CURRENT: + if req_type is HttpAPI.Request.STREAM or req_type is HttpAPI.Request.STREAM_CURRENT: return {"m3u": f.read().decode("utf-8")} - elif req_type is HttpRequestType.GRUB: + elif req_type is HttpAPI.Request.GRUB: return {"img_data": f.read()} - elif req_type is HttpRequestType.CURRENT: + elif req_type is HttpAPI.Request.CURRENT: for el in ETree.fromstring(f.read().decode("utf-8")).iter("e2event"): return {el.tag: el.text for el in el.iter()} # return first[current] event from the list - elif req_type is HttpRequestType.PLAYER_LIST: + elif req_type is HttpAPI.Request.PLAYER_LIST: return [{el.tag: el.text for el in el.iter()} for el in ETree.fromstring(f.read().decode("utf-8")).iter("e2file")] - elif req_type is HttpRequestType.EPG: + elif req_type is HttpAPI.Request.EPG: return {"event_list": [{el.tag: el.text for el in el.iter()} for el in - ETree.fromstring(f.read().decode("utf-8")).iter("e2event")]} - elif req_type is HttpRequestType.TIMER_LIST: + ETree.fromstring(f.read().decode("utf-8")).iter("e2event")]} + elif req_type is HttpAPI.Request.TIMER_LIST: return {"timer_list": [{el.tag: el.text for el in el.iter()} for el in - ETree.fromstring(f.read().decode("utf-8")).iter("e2timer")]} + ETree.fromstring(f.read().decode("utf-8")).iter("e2timer")]} else: return {el.tag: el.text for el in ETree.fromstring(f.read().decode("utf-8")).iter()} except HTTPError as e: - if req_type is HttpRequestType.TEST: + if req_type is HttpAPI.Request.TEST: raise e return {"error_code": e.code} except (URLError, RemoteDisconnected, ConnectionResetError) as e: - if req_type is HttpRequestType.TEST: + if req_type is HttpAPI.Request.TEST: raise e except ETree.ParseError as e: log("Parsing response error: {}".format(e)) @@ -497,11 +500,11 @@ def init_auth(user, password, url, use_ssl=False): def get_session_id(user, password, url): data = urllib.parse.urlencode(dict(user=user, password=password)).encode("utf-8") - return get_response(HttpRequestType.TOKEN, url, data=data).get("e2sessionid", "0") + return get_response(HttpAPI.Request.TOKEN, url, data=data).get("e2sessionid", "0") def get_post_data(base_url, password, user): - s_id = get_session_id(user, password, "{}/web/{}".format(base_url, HttpRequestType.TOKEN.value)) + s_id = get_session_id(user, password, "{}/web/{}".format(base_url, HttpAPI.Request.TOKEN.value)) data = None if s_id != "0": data = urllib.parse.urlencode({"user": user, "password": password, "sessionid": s_id}).encode("utf-8") @@ -527,7 +530,7 @@ def test_http(host, port, user, password, timeout=5, use_ssl=False, skip_message data = get_post_data(base_url, password, user) try: - return get_response(HttpRequestType.TEST, "{}/web/{}".format(base_url, params), data).get("e2statetext", "") + return get_response(HttpAPI.Request.TEST, "{}/web/{}".format(base_url, params), data).get("e2statetext", "") except (RemoteDisconnected, URLError, HTTPError) as e: raise TestException(e) diff --git a/app/ui/control.py b/app/ui/control.py index 3dd641d9..cd9d3c80 100644 --- a/app/ui/control.py +++ b/app/ui/control.py @@ -7,7 +7,7 @@ from gi.repository import GLib from .uicommons import Gtk, Gdk, UI_RESOURCES_PATH from ..commons import run_task, run_with_delay, log, run_idle -from ..connections import HttpRequestType, HttpAPI +from ..connections import HttpAPI class ControlBox(Gtk.HBox): @@ -132,14 +132,14 @@ class ControlBox(Gtk.HBox): self._remote_revealer.set_reveal_child(state) if state: - self._http_api.send(HttpRequestType.VOL, "state", self.update_volume) + self._http_api.send(HttpAPI.Request.VOL, "state", self.update_volume) def on_remote_action(self, action): - self._http_api.send(HttpRequestType.REMOTE, action, self.on_response) + self._http_api.send(HttpAPI.Request.REMOTE, action, self.on_response) @run_with_delay(0.5) def on_volume_changed(self, button, value): - self._http_api.send(HttpRequestType.VOL, "{:.0f}".format(value), self.on_response) + self._http_api.send(HttpAPI.Request.VOL, "{:.0f}".format(value), self.on_response) def update_volume(self, vol): if "error_code" in vol: @@ -153,7 +153,7 @@ class ControlBox(Gtk.HBox): if self._screenshot_check_button.get_active(): ref = "mode=all" if self._http_api.is_owif else "d=" - self._http_api.send(HttpRequestType.GRUB, ref, self.update_screenshot) + self._http_api.send(HttpAPI.Request.GRUB, ref, self.update_screenshot) @run_task def update_screenshot(self, data): @@ -177,15 +177,15 @@ class ControlBox(Gtk.HBox): loader.close() def on_screenshot_all(self, action, value=None): - self._http_api.send(HttpRequestType.GRUB, "mode=all" if self._http_api.is_owif else "d=", + self._http_api.send(HttpAPI.Request.GRUB, "mode=all" if self._http_api.is_owif else "d=", self.on_screenshot) def on_screenshot_video(self, action, value=None): - self._http_api.send(HttpRequestType.GRUB, "mode=video" if self._http_api.is_owif else "v=", + self._http_api.send(HttpAPI.Request.GRUB, "mode=video" if self._http_api.is_owif else "v=", self.on_screenshot) def on_screenshot_osd(self, action, value=None): - self._http_api.send(HttpRequestType.GRUB, "mode=osd" if self._http_api.is_owif else "o=", + self._http_api.send(HttpAPI.Request.GRUB, "mode=osd" if self._http_api.is_owif else "o=", self.on_screenshot) @run_task @@ -211,7 +211,7 @@ class ControlBox(Gtk.HBox): GLib.idle_add(self._screenshot_button_box.set_sensitive, True) def on_power_action(self, action): - self._http_api.send(HttpRequestType.POWER, action, lambda resp: log("Power status changed...")) + self._http_api.send(HttpAPI.Request.POWER, action, lambda resp: log("Power status changed...")) def update_signal(self, sig): self._snr_value_label.set_text(sig.get("e2snrdb", "0 dB").strip()) @@ -222,7 +222,7 @@ class ControlBox(Gtk.HBox): def on_service_changed(self, ref): self._app._wait_dialog.show() - self._http_api.send(HttpRequestType.EPG, ref, self.update_epg_data) + self._http_api.send(HttpAPI.Request.EPG, ref, self.update_epg_data) @run_idle def update_epg_data(self, epg): @@ -238,7 +238,7 @@ class ControlBox(Gtk.HBox): def update_timer_list(self): self._app._wait_dialog.show() - self._http_api.send(HttpRequestType.TIMER_LIST, "", self.update_timers_data) + self._http_api.send(HttpAPI.Request.TIMER_LIST, "", self.update_timers_data) @run_idle def update_timers_data(self, timers): diff --git a/app/ui/main_app_window.py b/app/ui/main_app_window.py index a2915976..213e8b14 100644 --- a/app/ui/main_app_window.py +++ b/app/ui/main_app_window.py @@ -9,8 +9,8 @@ from urllib.parse import urlparse, unquote from gi.repository import GLib, Gio from app.commons import run_idle, log, run_task, run_with_delay, init_logger -from app.connections import (HttpAPI, HttpRequestType, download_data, DownloadType, upload_data, test_http, - TestException, HttpApiException, STC_XML_FILE) +from app.connections import (HttpAPI, download_data, DownloadType, upload_data, test_http, TestException, + HttpApiException, STC_XML_FILE) from app.eparser import get_blacklist, write_blacklist, parse_m3u from app.eparser import get_services, get_bouquets, write_bouquets, write_services, Bouquets, Bouquet, Service from app.eparser.ecommons import CAS, Flag, BouquetService @@ -2464,7 +2464,7 @@ class Application(Gtk.Application): if is_record: self._recorder.stop() else: - self._http_api.send(HttpRequestType.STREAM_CURRENT, None, self.record) + self._http_api.send(HttpAPI.Request.STREAM_CURRENT, None, self.record) def record(self, data): url = self.get_url_from_m3u(data) @@ -2529,7 +2529,7 @@ class Application(Gtk.Application): if self._player and self._player.is_playing(): self._player.stop() - self._http_api.send(HttpRequestType.STREAM, ref, self.watch) + self._http_api.send(HttpAPI.Request.STREAM, ref, self.watch) def on_watch(self, item=None): """ Switch to the channel and watch in the player """ @@ -2538,7 +2538,7 @@ class Application(Gtk.Application): self._player_box.set_visible(True) GLib.idle_add(self._app_info_box.set_visible, False) - self._http_api.send(HttpRequestType.STREAM_CURRENT, None, self.watch) + self._http_api.send(HttpAPI.Request.STREAM_CURRENT, None, self.watch) def watch(self, data): url = self.get_url_from_m3u(data) @@ -2598,7 +2598,7 @@ class Application(Gtk.Application): self.show_error_dialog("No connection to the receiver!") self.set_playback_elms_active() - self._http_api.send(HttpRequestType.ZAP, ref, zap) + self._http_api.send(HttpAPI.Request.ZAP, ref, zap) def get_service_ref(self, path): row = self._fav_model[path][:] @@ -2620,7 +2620,7 @@ class Application(Gtk.Application): GLib.idle_add(self._receiver_info_box.set_visible, False) return False - self._http_api.send(HttpRequestType.INFO, None, self.update_receiver_info) + self._http_api.send(HttpAPI.Request.INFO, None, self.update_receiver_info) return True def update_receiver_info(self, info): @@ -2648,8 +2648,8 @@ class Application(Gtk.Application): def update_service_info(self): if self._http_api: - self._http_api.send(HttpRequestType.SIGNAL, None, self.update_signal) - self._http_api.send(HttpRequestType.CURRENT, None, self.update_status) + self._http_api.send(HttpAPI.Request.SIGNAL, None, self.update_signal) + self._http_api.send(HttpAPI.Request.CURRENT, None, self.update_status) def update_signal(self, sig): if self._control_box: @@ -2697,7 +2697,7 @@ class Application(Gtk.Application): self._control_revealer.add(self._control_box) if state: - self._http_api.send(HttpRequestType.VOL, "state", self._control_box.update_volume) + self._http_api.send(HttpAPI.Request.VOL, "state", self._control_box.update_volume) def on_http_status_visible(self, img): self._control_button.set_active(False) diff --git a/app/ui/transmitter.py b/app/ui/transmitter.py index 4835fc33..611dd777 100644 --- a/app/ui/transmitter.py +++ b/app/ui/transmitter.py @@ -6,7 +6,7 @@ from gi.repository import GLib from app.commons import log from app.settings import IS_DARWIN -from app.connections import HttpRequestType +from app.connections import HttpAPI from app.tools.yt import YouTube from app.ui.iptv import get_yt_icon from .uicommons import Gtk, Gdk, UI_RESOURCES_PATH @@ -128,7 +128,7 @@ class LinksTransmitter: else: self._url_entry.set_icon_from_stock(Gtk.EntryIconPosition.SECONDARY, None) - self._http_api.send(HttpRequestType.PLAY, url, self.on_done, self.__STREAM_PREFIX) + self._http_api.send(HttpAPI.Request.PLAY, url, self.on_done, self.__STREAM_PREFIX) yield True def on_done(self, res): @@ -138,21 +138,21 @@ class LinksTransmitter: GLib.idle_add(self._tool_bar.set_sensitive, True) def on_previous(self, item): - self._http_api.send(HttpRequestType.PLAYER_PREV, None, self.on_done) + self._http_api.send(HttpAPI.Request.PLAYER_PREV, None, self.on_done) def on_next(self, item): - self._http_api.send(HttpRequestType.PLAYER_NEXT, None, self.on_done) + self._http_api.send(HttpAPI.Request.PLAYER_NEXT, None, self.on_done) def on_play(self, item): - self._http_api.send(HttpRequestType.PLAYER_PLAY, None, self.on_done) + self._http_api.send(HttpAPI.Request.PLAYER_PLAY, None, self.on_done) def on_stop(self, item): - self._http_api.send(HttpRequestType.PLAYER_STOP, None, self.on_done) + self._http_api.send(HttpAPI.Request.PLAYER_STOP, None, self.on_done) def on_clear(self, item): """ Remove added links in the playlist. """ GLib.idle_add(self._tool_bar.set_sensitive, False) - self._http_api.send(HttpRequestType.PLAYER_LIST, None, self.clear_playlist) + self._http_api.send(HttpAPI.Request.PLAYER_LIST, None, self.clear_playlist) def clear_playlist(self, res): GLib.idle_add(self._tool_bar.set_sensitive, not res) @@ -163,7 +163,7 @@ class LinksTransmitter: for ref in res: GLib.idle_add(self._tool_bar.set_sensitive, False) - self._http_api.send(HttpRequestType.PLAYER_REMOVE, + self._http_api.send(HttpAPI.Request.PLAYER_REMOVE, ref.get("e2servicereference", ""), self.on_done, self.__STREAM_PREFIX)