def internal_start_master(self): from Webserver.Controllers.AuthController import AuthController from Webserver.Controllers.AccessController import AccessController from Webserver.Controllers.MediaPlayer.MovieController import MovieController from Webserver.Controllers.MediaPlayer.ShowController import ShowController from Webserver.Controllers.MediaPlayer.PlayController import PlayController from Webserver.Controllers.MediaPlayer.HDController import HDController from Webserver.Controllers.MediaPlayer.RadioController import RadioController from Webserver.Controllers.MediaPlayer.TorrentController import TorrentController from Webserver.Controllers.MediaPlayer.YouTubeController import YouTubeController from Webserver.Controllers.DataController import DataController from Webserver.Controllers.Home.TradfriController import TradfriController from Webserver.Controllers.Home.ToonController import ToonController from Webserver.Controllers.UtilController import UtilController from Webserver.Controllers.Home.RuleController import RuleController from Webserver.Controllers.Websocket2.UIWebsocketController import UIWebsocketController from Webserver.Controllers.Websocket2.SlaveWebsocketController import SlaveWebsocketController self.ui_websocket_controller = UIWebsocketController("/UI") self.slave_websocket_controller = SlaveWebsocketController("/Slave") UIWebsocketController.init() YouTubeController.init() socketio.on_namespace(self.ui_websocket_controller) socketio.on_namespace(self.slave_websocket_controller) APIController.slaves.add_slave( SlaveClient(1, Settings.get_string("name"), None)) socketio.run(app, host='0.0.0.0', port=int(Settings.get_string("api_port")), log_output=True)
def __init__(self): self.git_repo = "https://github.com/jkorf/MediaPi.git" self.git_branch = "NewUI" self.base_folder = Settings.get_string("base_folder") self.update_folder = Settings.get_string("base_folder") + "Updates/" self.ignore_directories = ("/Solution", "/UI/homebase", "/UI/Web") self.copied_files = 0 self.last_version = Database().get_stat_string("CurrentGitVersion") self.last_update = Database().get_stat("LastUpdate") self.update_state = UpdateState(self.last_version, self.last_update)
def __init__(self): self.subtitle_sources = [ SubtitlesOpenSubtitles(), ] self.sub_file_directory = Settings.get_string("base_folder") + "/subs/" self.sub_files = [] self.file_size = 0 self.file_length = 0 self.file_name = None self.first_64k = None self.last_64k = None # create subtitles directory if not os.path.exists(self.sub_file_directory): os.makedirs(self.sub_file_directory) # remove old subtitles files file_list = glob.glob(self.sub_file_directory + "*.srt") for f in file_list: os.remove(f) EventManager.register_event(EventType.SearchSubtitles, self.search_subtitles)
def __init__(self): self.state_data = StateData() self.monitoring = sys.platform == "linux" or sys.platform == "linux2" self.state_data.name = Settings.get_string("name") self.watch_thread = CustomThread(self.update_state, "State observer") self.watch_thread.start() self.memory_thread = CustomThread(self.check_memory, "Memory observer") self.memory_thread.start()
def get_log_files(): list_of_files = glob.glob( Settings.get_string("base_folder") + "/Logs/*/*.txt") latest_files = sorted(list_of_files, key=os.path.getctime, reverse=True) return [(os.path.basename(x), x, os.path.getsize(x)) for x in latest_files]
def connect(): SlaveClientController.running = True Logger().write(LogVerbosity.Debug, "Connecting to master") SlaveClientController.socket = SocketIO(Settings.get_string("master_ip"), port=int(Settings.get_string("api_port"))) SlaveClientController.slave_ns = SlaveClientController.socket.define(Handler, "/Slave") while SlaveClientController.running: SlaveClientController.socket.wait(1)
def __init__(self, torrent): super().__init__(torrent, "cache") self.open_cache_files = [] self.piece_length = 0 self.total_length = 0 self.media_start_byte = 0 self.media_start_piece_offset = 0 self.path = Settings.get_string("base_folder") + "Solution/cache/" self.bytes_written = 0
def cleanup_logging(self): try: base_path = Settings.get_string("base_folder") + "/Logs/" for f in os.listdir(base_path): file_path = base_path + f creation_time = os.stat(file_path).st_mtime if (current_time() / 1000 - creation_time) >= 60 * 60 * 24 * 7: shutil.rmtree(file_path, True) except Exception as e: self.write_error(e, "Log cleaning failed")
def get_instance_parameters(): params = [ "--verbose=" + str(Settings.get_int("vlc_log_level")), "--network-caching=" + str(Settings.get_int("network_caching")), "--ipv4-timeout=500", "--image-duration=-1" ] if sys.platform == "linux" or sys.platform == "linux2": log_path = Settings.get_string( "base_folder") + "/Logs/" + datetime.datetime.now().strftime( '%Y-%m-%d %H-%M-%S') params.append( "--logfile=" + log_path + '/vlc_' + datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S') + ".txt") params.append("--file-logging") params.append("--file-caching=5000") return params
def start_file(self, url, time): actual_url = url if Settings.get_bool("slave"): actual_url = "http://" + Settings.get_string( "master_ip") + ":50015/file/" + urllib.parse.quote(url) self.stop_play() VLCPlayer().play(actual_url, time) if Settings.get_bool("slave"): self.history_id, = SlaveClientController.request_master( "add_watched_file", 5, url, current_time()) else: self.history_id = Database().add_watched_file(url, current_time()) self.media_data.start_update() self.media_data.type = "File" self.media_data.title = os.path.basename(url) self.media_data.url = url self.media_data.image = None self.media_data.stop_update() TVManager().switch_input_to_pi()
def __init__(self): self.log_level = 0 self.log_time = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S') self.raspberry = sys.platform == "linux" or sys.platform == "linux2" self.log_path = Settings.get_string( "base_folder") + "/Logs/" + datetime.datetime.now().strftime( '%Y-%m-%d %H-%M-%S') self.file_size = 0 self.exception_lock = threading.Lock() self.running = False self.last_id = 1 self.log_processor = LogProcessor(self.log_path, 'log_' + self.log_time, True and not self.raspberry) self.state_log_processor = LogProcessor(self.log_path, 'state_' + self.log_time, False)
def __init__(self): Logger().start(Settings.get_int("log_level")) sys.excepthook = self.handle_exception Logger().write(LogVerbosity.Info, "Starting") self.running = True self.version = datetime.fromtimestamp( self.get_latest_change()).strftime("%Y-%m-%d %H:%M:%S") self.is_slave = Settings.get_bool("slave") self.pi = sys.platform == "linux" or sys.platform == "linux2" Logger().write( LogVerbosity.Info, "Python version " + str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2])) Logger().write(LogVerbosity.Info, "MediaPlayer build [" + self.version + "]") Logger().write(LogVerbosity.Info, "Slave: " + str(self.is_slave)) if self.is_slave: Logger().write( LogVerbosity.Info, "Master ip: " + str(Settings.get_string("master_ip"))) Logger().write(LogVerbosity.Info, "Pi: " + str(self.pi)) Logger().write(LogVerbosity.Info, "UI: " + str(Settings.get_bool("UI"))) Logger().write(LogVerbosity.Debug, "Initializing database") Database().init_database() Logger().write(LogVerbosity.Debug, "Initializing singletons") self.init_singletons() Logger().write(LogVerbosity.Debug, "Initializing sounds and folders") self.init_sound() self.init_folders() Logger().write(LogVerbosity.Debug, "Initializing API") APIController().start() Logger().write(LogVerbosity.Debug, "Initializing WiFi controller") WiFiController().check_wifi() Logger().write(LogVerbosity.Debug, "Initializing stats") Stats().start() Stats().set('start_time', current_time()) Logger().write(LogVerbosity.Debug, "Initializing presence manager") PresenceManager().start() Logger().write(LogVerbosity.Debug, "Initializing rule manager") RuleManager().start() Logger().write(LogVerbosity.Debug, "Initializing TV manager") TVManager().start() if not self.is_slave: Logger().write(LogVerbosity.Debug, "Initializing TradeFriManager") TradfriManager().init() Logger().write(LogVerbosity.Debug, "Initializing master file server") self.file_listener = StreamListener("MasterFileServer", 50015) self.file_listener.start_listening() Logger().write(LogVerbosity.Important, "Started") if Settings.get_bool("UI"): from UI.TV.GUI import App self.gui = App.initialize() else: while self.running: time.sleep(5)
def init_UI(self): self.parent.title("TV UI") self.configure(background='black') w = self.parent.winfo_screenwidth() h = self.parent.winfo_screenheight() self.master.geometry("{0}x{1}+0+0".format(w, h)) self.parent.bind("<Escape>", self.fullscreen_cancel) self.fullscreen_toggle() self.background_canvas = tk.Canvas(self.parent, width=w, height=h, highlightthickness=0, background="#000") self.background_image = self.set_canvas_image(self.background_canvas, "background.jpg", 0, 0, w, h) self.info_background = self.create_rectangle(self.background_canvas, w - 250, 0, w, h, fill="#FFF", alpha=0.7, outline="#AAA") self.name_label = self.background_canvas.create_text( w - 125, 30, anchor="n", font=("Purisa", 20), text=Settings.get_string("name"), fill="#444") playing_position = 96 self.playing_label = self.background_canvas.create_text( w - 220, playing_position, anchor="nw", font=("Purisa", 14), text="", fill="#999") self.playing_value = self.background_canvas.create_text( w - 220, playing_position + 22, anchor="nw", font=("Purisa", 16), text="", fill="#444") self.time_label = self.background_canvas.create_text( w - 125, h - 80, font=("Purisa", 28), text=time.strftime('%H:%M'), fill="#444") self.date_label = self.background_canvas.create_text( w - 125, h - 40, font=("Purisa", 20), text=time.strftime('%a %d %b'), fill="#444") loading_position = 96 self.loading_speed_label = self.background_canvas.create_text( w - 230, loading_position, anchor="nw", font=("Purisa", 16), text="Speed:", fill="#444", state="hidden") self.loading_buffered_label = self.background_canvas.create_text( w - 230, loading_position + 24, anchor="nw", font=("Purisa", 16), text="Buffered:", fill="#444", state="hidden") self.loading_peers_connected_label = self.background_canvas.create_text( w - 230, loading_position + 48, anchor="nw", font=("Purisa", 16), text="Connected:", fill="#444", state="hidden") self.loading_peers_available_label = self.background_canvas.create_text( w - 230, loading_position + 72, anchor="nw", font=("Purisa", 16), text="Available:", fill="#444", state="hidden") self.loading_speed_value = self.background_canvas.create_text( w - 20, loading_position, anchor="ne", font=("Purisa", 16), text="", fill="#444", state="hidden") self.loading_buffered_value = self.background_canvas.create_text( w - 20, loading_position + 24, anchor="ne", font=("Purisa", 16), text="", fill="#444", state="hidden") self.loading_peers_connected_value = self.background_canvas.create_text( w - 20, loading_position + 48, anchor="ne", font=("Purisa", 16), text="", fill="#444", state="hidden") self.loading_peers_available_value = self.background_canvas.create_text( w - 20, loading_position + 72, anchor="ne", font=("Purisa", 16), text="", fill="#444", state="hidden") self.player_frame = tk.Frame(self.parent, width=w, height=h, highlightthickness=0, background="black") self.status_image_frame = tk.Canvas(self.parent, width=84, height=84, highlightthickness=0, background="#DDD") self.status_image_frame.pause_image = ImageTk.PhotoImage( Image.open(self.base_image_path + "paused.png")) self.pause_image = self.status_image_frame.create_image( 10, 10, anchor='nw', image=self.status_image_frame.pause_image) self.weather_icon_image = self.background_canvas.create_image( w - 125, h - 230, image=None) self.weather_temp = self.background_canvas.create_text(w - 125, h - 150, font=("Purisa", 20), text="", fill="#444") self.background_canvas.create_line(w - 240, 70, w - 10, 70, fill="#888") self.background_canvas.create_line(w - 240, h - 120, w - 10, h - 120, fill="#888") self.state = UIState.Home
def __init__(self): self.path = Settings.get_string("base_folder") + "Solution/" self.db_name = "database.data" self.slave = Settings.get_bool("slave") self.current_version = 13
def init(self): if self.initialized: Logger().write(LogVerbosity.Info, "already init") return if sys.platform != "linux" and sys.platform != "linux2": Logger().write(LogVerbosity.Info, "Lighting: Not initializing, no coap client available on windows") self.initialized = True self.tradfri_state.update_group(DeviceGroup(1, "Test group", True, 128, 6)) self.tradfri_state.update_group(DeviceGroup(2, "Test group 2", False, 18, 6)) return if current_time() - self.last_init < 5000: Logger().write(LogVerbosity.Info, "Tried initialization less than 5s ago") return Logger().write(LogVerbosity.All, "Start LightManager init") self.enabled = True if not self.initialized: ip = Settings.get_string("tradfri_hub_ip") identity = Database().get_stat_string("LightingId") key = Database().get_stat_string("LightingKey") if identity is None or key is None: Logger().write(LogVerbosity.Info, "Lighting: No identity/key found, going to generate new") # We don't have all information to connect, reset and start from scratch Database().remove_stat("LightingId") Database().remove_stat("LightingKey") key = None identity = uuid.uuid4().hex Database().update_stat("LightingId", identity) # Generate and save a new id self.api_factory = APIFactory(host=ip, psk_id=identity) else: self.api_factory = APIFactory(host=ip, psk_id=identity, psk=key) self.api = self.api_factory.request self.gateway = Gateway() if key is None: try: security_code = SecureSettings.get_string("tradfri_hub_code") # the code at the bottom of the hub key = self.api_factory.generate_psk(security_code) Database().update_stat("LightingKey", key) # Save the new key Logger().write(LogVerbosity.Info, "Lighting: New key retrieved") except Exception as e: Logger().write_error(e, "Unhandled exception") return else: Logger().write(LogVerbosity.Info, "Lighting: Previously saved key found") try: self.initialized = True groups = self.get_device_groups() for group in groups: self.tradfri_state.update_group(group) except Exception as e: Logger().write(LogVerbosity.Info, "Failed to init tradfri, clearing previous key to try generate new") self.initialized = False Database().remove_stat("LightingId") Database().remove_stat("LightingKey") Logger().write_error(e, "Failed to get groups from hub")
class MovieController: movies_api_path = Settings.get_string("movie_api") server_uri = "http://localhost:50009/torrent" @staticmethod @app.route('/movies', methods=['GET']) def get_movies(): page = int(request.args.get('page')) order_by = request.args.get('orderby') keywords = request.args.get('keywords') include_previous_pages = request.args.get('page') == "true" search_string = "" if keywords: search_string = "&keywords=" + urllib.parse.quote(keywords) if include_previous_pages: data = [] current_page = 0 while current_page != page: current_page += 1 data += MovieController.request_movies( MovieController.movies_api_path + "movies/" + str(current_page) + "?sort=" + urllib.parse.quote( order_by) + search_string) else: data = MovieController.request_movies(MovieController.movies_api_path + "movies/" + str(page) + "?sort=" + urllib.parse.quote(order_by) + search_string) return to_JSON(data).encode() @staticmethod def request_movies(url): data = RequestFactory.make_request(url) if data is not None: return MovieController.parse_movie_data(data.decode('utf-8')) else: EventManager.throw_event(EventType.Error, ["get_error", "Could not get movie data"]) Logger().write(LogVerbosity.Info, "Error fetching movies") return [] @staticmethod @app.route('/movie', methods=['GET']) def get_movie_by_id(): movie_id = request.args.get('id') Logger().write(LogVerbosity.Debug, "Get movie by id " + movie_id) response = RequestFactory.make_request(MovieController.movies_api_path + "movie/" + movie_id) data = json.loads(response.decode('utf-8')) seen = Database().get_history_for_id(movie_id) data['seen'] = len(seen) > 0 if len(seen) > 0: seen = seen[-1] data['played_for'] = seen.played_for data['length'] = seen.length return json.dumps(data).encode('utf-8') @staticmethod def parse_movie_data(data): json_data = json.loads(data) if isinstance(json_data, list): return [Movie.parse_movie(x) for x in json_data] else: return Movie.parse_movie(json_data)
def init_folders(): folder = Settings.get_string("base_folder") directory = os.path.dirname(folder) + "/" + "subs" if not os.path.exists(directory): os.makedirs(directory)
class TorrentController: base_url = Settings.get_string("torrent_api") @staticmethod @app.route('/torrents/top', methods=['GET']) def top(): category = request.args.get('category') if category == "TV": category = "television" elif category == "Movies": category = "movies" return to_JSON( TorrentController.get_torrents(TorrentController.base_url + "/top-100-" + category)) @staticmethod @app.route('/torrents', methods=['GET']) def search(): terms = request.args.get('keywords') category = request.args.get('category') return to_JSON( TorrentController.get_torrents(TorrentController.base_url + "/category-search/" + terms + "/" + category + "/1/")) @staticmethod def get_magnet_url(url): torrent_result = RequestFactory.make_request( TorrentController.base_url + url, timeout=10) parsed = BeautifulSoup(torrent_result, "lxml") magnet_link = parsed.findAll('a', href=re.compile('^magnet:\?xt=urn:btih:')) if len(magnet_link) == 0: return None return magnet_link[0].attrs['href'] @staticmethod def get_torrents(url): search_result = RequestFactory.make_request(url, timeout=10) if search_result is None: return [] parsed = BeautifulSoup(search_result, "lxml") table_rows = parsed.find_all('tr') torrent_rows = [ row.contents for row in table_rows if len([ child for child in row.contents if isinstance(child, Tag) and child.name == "td" and ('name' in child.attrs['class'] or 'seeds' in child.attrs['class']) ]) != 0 ] result = [] for row in torrent_rows: childs = [x for x in row if isinstance(x, Tag)] name = [x for x in childs if 'name' in x.attrs['class']][0].text seeds = int([x for x in childs if 'seeds' in x.attrs['class']][0].text) leeches = int([x for x in childs if 'leeches' in x.attrs['class']][0].text) size = [x for x in childs if 'size' in x.attrs['class']][0].contents[0] torrent = [x for x in childs if 'name' in x.attrs['class'] ][0].contents[1].attrs['href'] result.append(TorrentModel(name, seeds, leeches, size, torrent)) return result
class ShowController: shows_api_path = Settings.get_string("serie_api") server_uri = "http://localhost:50009/torrent" @staticmethod @app.route('/shows', methods=['GET']) def get_shows(): page = int(request.args.get('page')) order_by = request.args.get('orderby') keywords = request.args.get('keywords') include_previous_pages = request.args.get('page') == "true" search_string = "" if keywords: search_string = "&keywords=" + urllib.parse.quote(keywords) if include_previous_pages: data = [] current_page = 0 while current_page != page: current_page += 1 data += ShowController.request_shows( ShowController.shows_api_path + "shows/" + str(current_page) + "?sort=" + urllib.parse.quote(order_by) + search_string) else: data = ShowController.request_shows(ShowController.shows_api_path + "shows/" + str(page) + "?sort=" + urllib.parse.quote(order_by) + search_string) return to_JSON(data).encode() @staticmethod def request_shows(url): data = RequestFactory.make_request(url) if data is not None: return ShowController.parse_show_data(data.decode('utf-8')) else: EventManager.throw_event(EventType.Error, ["get_error", "Could not get show data"]) Logger().write(LogVerbosity.Info, "Error fetching shows") return [] @staticmethod @app.route('/show', methods=['GET']) def get_by_id(): show_id = request.args.get('id') data = ShowController.get_by_id_internal(show_id) return json.dumps(data).encode('utf-8') @staticmethod def get_by_id_internal(show_id): Logger().write(LogVerbosity.Debug, "Get show by id " + show_id) response = RequestFactory.make_request(ShowController.shows_api_path + "show/" + show_id) data = json.loads(response.decode('utf-8')) seen_episodes = [] data['favorite'] = False if not Settings.get_bool("slave"): seen_episodes = Database().get_history_for_id(show_id) data['favorite'] = show_id in [ x.id for x in Database().get_favorites() ] for episode in data['episodes']: seen = [ x for x in seen_episodes if episode['season'] == x.season and episode['episode'] == x.episode ] episode['seen'] = len(seen) != 0 if len(seen) == 0: continue seen = seen[-1] episode['seen'] = True episode['played_for'] = seen.played_for episode['length'] = seen.length return data @staticmethod @app.route('/show/favorite', methods=['POST']) def add_favorite(): show_id = request.args.get('id') title = urllib.parse.unquote(request.args.get('title')) image = urllib.parse.unquote(request.args.get('image')) Logger().write(LogVerbosity.Info, "Add show favorite: " + show_id) Database().add_favorite(show_id, "Show", title, image) return "OK" @staticmethod @app.route('/show/favorite', methods=['DELETE']) def remove_favorite(): show_id = request.args.get('id') Logger().write(LogVerbosity.Info, "Remove show favorite: " + show_id) Database().remove_favorite(show_id) return "OK" @staticmethod def parse_show_data(data): json_data = json.loads(data) if isinstance(json_data, list): return [ Show(x['imdb_id'], ShowController.get_poster(x), x['title'], x['rating']['percentage']) for x in json_data ] else: return Show(json_data['imdb_id'], ShowController.get_poster(json_data), json_data['title'], json_data['rating']['percentage']) @staticmethod def get_poster(show): poster = "" if 'images' in show: if 'poster' in show['images']: poster = show['images']['poster'] elif len(show['images']) > 0: poster = show['images'][0] return poster
def initialize(self): Logger().write(LogVerbosity.Info, "Connected to master") self.emit("init", Settings.get_string("name"), SecureSettings.get_string("master_key"), self.handle_init_response)