예제 #1
0
    def __init__(self, peer, uri):
        super().__init__(peer, "connection")

        self.peer = peer
        self.uri = uri
        self.to_send_bytes = bytearray()
        self.last_send = 0
        self.connected_on = 0
        self._last_communication = 0
        self._peer_timeout = Settings.get_int("peer_timeout")
        self._connection_timeout = Settings.get_int("connection_timeout") / 1000

        self.connection = TcpClient(uri.hostname, uri.port, self._connection_timeout)
        self.buffer = bytearray()

        self.buffer_in_size = 0
        self.buffer_out_size = 0

        self._next_message_length = 1
        self._buffer_position = 0
        self._receive_state = ReceiveState.ReceiveLength
        self._receive_buffer_size = 32768

        self.in_thread = None
        self.reading_handshake = True
예제 #2
0
 def __init__(self, host, port):
     self.host = host
     self.port = port
     self.last_announce = 0
     self.transaction_id = 0
     self.connection_id = 0
     self.connection_id_retrieved = 0
     self.connection = UdpClient(host, port, Settings.get_int("connection_timeout") / 1000)
     self.tracker_peer_request_amount = Settings.get_int("tracker_peer_request_amount")
예제 #3
0
    def __init__(self, torrent):
        super().__init__(torrent, "download")

        self.torrent = torrent

        self.init = False
        self.prio = False
        self.last_get_result = 0, 0
        self.last_get_time = 0

        self.queue = []
        self.slow_peer_piece_offset = 0
        self._ticks = 0

        self.start_piece = 0
        self.end_piece = 0
        self.stream_end_buffer_pieces = 0
        self.stream_play_buffer_high_priority = 0
        self.max_chunk_size = Settings.get_int("max_chunk_size")

        self.download_mode = DownloadMode.Full
        self.peers_per_piece = [(100, 2, 5), (95, 1, 2), (0, 1, 1)]

        self._event_id_stopped = EventManager.register_event(
            EventType.TorrentStopped, self.unregister)
        self._event_id_torrent_state = EventManager.register_event(
            EventType.TorrentStateChange, self.init_queue)

        self.queue_log = ""
예제 #4
0
    def __init__(self, peer):
        super().__init__(peer, "meta")
        self.peer = peer

        self.handshake_send = False
        self.handshake_successful = False
        self.extension_handshake_send = False
        self.bitfield_done = False
        self.metadata_requested = False
        self.pause_handled = False
        self.port_send = False
        self.last_peer_exchange = current_time()

        self._low_peer_max_speed = Settings.get_int(
            "low_peer_max_download_buffer") / 3
        self._medium_peer_max_speed = Settings.get_int(
            "medium_peer_max_download_buffer") / 3
예제 #5
0
파일: VLCPlayer.py 프로젝트: JKorf/MediaPi
    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
예제 #6
0
    def __init__(self, peer):
        super().__init__(peer, "download")

        self.peer = peer
        self.stopped = False
        self.downloading = []

        self._block_size = Settings.get_int("block_size")
        self._low_peer_max_blocks = Settings.get_int(
            "low_peer_max_download_buffer") // self._block_size
        self._medium_peer_max_blocks = Settings.get_int(
            "medium_peer_max_download_buffer") // self._block_size
        self._fast_peer_max_blocks = Settings.get_int(
            "fast_peer_max_download_buffer") // self._block_size

        self.timed_out_blocks = 0

        # Logging props
        self.downloading_log = ""
예제 #7
0
    def __init__(self, base_path, file_name, print_to_output):
        self.base_path = base_path
        self.base_file_name = file_name
        self.print_to_output = print_to_output
        self.file = None
        self.file_size = 0
        self.file_number = 1
        self.max_log_file_size = Settings.get_int("max_log_file_size")

        self.running = True

        self.process_thread = None
        self.queue = []
        self.queue_event = threading.Event()
예제 #8
0
    def __init__(self, torrent):
        super().__init__(torrent, "peers")

        self.torrent = torrent
        self.potential_peers = []
        self.connecting_peers = []
        self.connected_peers = []
        self.disconnected_peers = []
        self.cant_connect_peers = []
        self.complete_peer_list = []
        self.max_peers_connected = Settings.get_int("max_peers_connected")
        self.max_peers_connecting = Settings.get_int("max_peers_connecting")
        self._peer_request_interval = Settings.get_int("peer_request_interval")
        self._peer_request_interval_no_potential = Settings.get_int(
            "peer_request_interval_no_potential")
        self.random = Random()
        self.download_start = 0
        self.start_time = current_time()
        self.last_peer_request = 0
        self.checked_no_peers = False

        self._event_id_stopped = EventManager.register_event(
            EventType.TorrentStopped, self.unregister)
        self._event_id_torrent_change = EventManager.register_event(
            EventType.TorrentStateChange, self.torrent_state_change)
        self._event_id_peers_found = EventManager.register_event(
            EventType.PeersFound, self.add_potential_peers)

        self.high_speed_peers = 0
        self.medium_speed_peers = 0

        # Log properties
        self.potential_peers_log = 0
        self.connecting_peers_log = 0
        self.connected_peers_log = 0
        self.disconnected_peers_log = 0
        self.cant_connect_peers_log = 0
예제 #9
0
    def init_queue(self, old_state, new_state):
        if not self.init and new_state == TorrentState.Downloading and self.torrent.media_file is not None:
            self.init = True

            self.start_piece = self.torrent.media_file.start_piece(
                self.torrent.piece_length)
            self.end_piece = self.torrent.media_file.end_piece(
                self.torrent.piece_length)
            self.stream_end_buffer_pieces = self.torrent.data_manager.get_piece_by_offset(
                self.torrent.media_file.end_byte -
                Settings.get_int("stream_end_buffer_tolerance")).index
            self.stream_play_buffer_high_priority = max(
                1500000 // self.torrent.piece_length, 2)  # TODO setting

            self.requeue(0)
예제 #10
0
    def start(self):
        APIController.slaves = SlaveCollection()

        log_verbosity = Settings.get_int("log_level")
        if log_verbosity > 0:
            flask_logger = logging.getLogger('werkzeug')
            flask_logger.setLevel(logging.INFO)

        if Settings.get_bool("slave"):
            thread = CustomThread(self.internal_start_slave, "API controller",
                                  [])
            thread.start()
        else:
            thread = CustomThread(self.internal_start_master, "API controller",
                                  [])
            thread.start()
예제 #11
0
    def __init__(self, name, port, arg=None):
        super().__init__(arg, name)

        self.name = name
        self.torrent = arg

        self.port = port
        self.thread = None
        self.chunk_length = Settings.get_int("max_chunk_size")
        self.server = StreamServer(self.name, port, self.handle_request)

        self.sockets_writing_data = []

        self.running = False
        self.bytes_send = 0
        self.id = 0
예제 #12
0
    def __init__(self, torrent):
        super().__init__(torrent, "data")
        self.torrent = torrent
        self._pieces = dict()
        self.init_done = False
        self.total_pieces = 0
        self.piece_length = 0
        self.bitfield = None
        self.hashes = []

        self.block_size = Settings.get_int("block_size")
        self.broadcasted_hash_data = False
        self._event_id_stopped = EventManager.register_event(
            EventType.TorrentStopped, self.unregister)
        self.blocks_done_length = 0
        self.last_piece_index = 0
예제 #13
0
    def init():
        if Settings.get_int("log_level") == 0:
            import logging
            logging.getLogger('requests').setLevel(logging.WARNING)
            logging.basicConfig(level=logging.DEBUG)

        from MediaPlayer.MediaManager import MediaManager
        from MediaPlayer.Player.VLCPlayer import VLCPlayer
        from Updater import Updater
        from Shared.State import StateManager
        from Shared.Stats import Stats

        StateManager().state_data.register_callback(lambda old, new: SlaveClientController.broadcast("state", new))
        VLCPlayer().player_state.register_callback(lambda old, new: SlaveClientController.broadcast("player", new))
        MediaManager().media_data.register_callback(lambda old, new: SlaveClientController.broadcast("media", new))
        MediaManager().torrent_data.register_callback(lambda old, new: SlaveClientController.broadcast("torrent", new))
        Stats().cache.register_callback(lambda old, new: SlaveClientController.broadcast("stats", new))
        Updater().update_state.register_callback(lambda old, new: SlaveClientController.broadcast("update", new))
예제 #14
0
    def __init__(self):
        self.own_node = None

        self.routing_table = Table(self)
        self.table_lock = Lock()

        self.socket = Socket(Settings.get_int("dht_port"), self.on_node_seen,
                             self.on_node_timeout, self.on_query)
        self.engine = Engine("DHT Engine", 5000)
        self.engine.add_work_item("DHT Refresh buckets", 1000 * 60,
                                  self.refresh_buckets, False)
        self.engine.add_work_item("DHT Save nodes", 1000 * 60 * 5,
                                  self.save_nodes, False)

        self.running_tasks = []
        self.torrent_nodes = dict()

        EventManager.register_event(EventType.RequestPeers, self.search_peers)
        EventManager.register_event(EventType.NewDHTNode, self.add_node)
예제 #15
0
    def __init__(self, parent, index, block_start_index, start_byte, length):
        super().__init__(parent, "piece " + str(index))

        self.index = index
        self.block_start_index = block_start_index
        self.start_byte = start_byte
        self.end_byte = start_byte + length
        self.length = length
        self.done = False
        self.written = False
        self.cleared = False
        self.max_priority_set_time = 0

        self._data = None
        self._blocks = dict()
        self.initialized = False

        self.validated = False
        self.block_writes = 0
        self.total_blocks = 0
        self.block_size = Settings.get_int("block_size")
        self.priority = 0
예제 #16
0
 def __init__(self, uri):
     self.uri = uri
     self.host = uri.hostname
     self.last_announce = 0
     self.tracker_peer_request_amount = Settings.get_int("tracker_peer_request_amount")
예제 #17
0
파일: start.py 프로젝트: JKorf/MediaPi
    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)
예제 #18
0
 def update(self):
     big_buffer_but_not_consequetive = self.torrent.bytes_total_in_buffer - self.torrent.bytes_ready_in_buffer > Settings.get_int("important_only_start_threshold")
     queued_high_priority_piece_timeout_while_downloading = len([x for x in self.torrent.download_manager.queue[0: 10] if x.max_priority_set_time != 0 and current_time() - x.max_priority_set_time > 10000]) > 0 and self.torrent.network_manager.average_download_counter.value > 200000
     if (big_buffer_but_not_consequetive or queued_high_priority_piece_timeout_while_downloading) and self.torrent.download_manager.download_mode == DownloadMode.Full:
         Logger().write(LogVerbosity.Info, "Entering ImportantOnly download mode: " + write_size(self.torrent.bytes_total_in_buffer) + " in buffer total")
         self.torrent.download_manager.download_mode = DownloadMode.ImportantOnly
     elif self.torrent.bytes_total_in_buffer - self.torrent.bytes_ready_in_buffer < Settings.get_int("important_only_stop_threshold") and self.torrent.download_manager.download_mode == DownloadMode.ImportantOnly:
         Logger().write(LogVerbosity.Info, "Leaving ImportantOnly download mode")
         self.torrent.download_manager.download_mode = DownloadMode.Full
예제 #19
0
 def init_buffer(self):
     self.init = True
     self.end_buffer_start_byte = self.torrent.media_file.length - Settings.get_int("stream_end_buffer_tolerance")
     self.start_buffer_end_byte = Settings.get_int("stream_start_buffer")
     self.change_stream_position(self.torrent.media_file.start_byte)