def play(self, player, torrent, list_item=None, file_id=None):
        """
        :type list_item: dict
        :type torrent: Torrent
        :type player: AbstractPlayer
        """
        list_item = list_item or {}
        self.engine.on_playback_resumed = player.play
        self.engine.on_playback_paused = player.pause
        self.engine.on_poll = self._poll_engine

        list_item.setdefault('label', torrent.name)
        try:
            with closing(self.engine) as engine:
                with closing(self.buffering_progress) as progress:
                    progress.open()
                    self.log.info("Starting AceStream engine...")
                    progress.update_status(TorrentStatus.STARTING_ENGINE)
                    engine.connect()
                    self.log.info("Loading transport file...")
                    progress.name = torrent.name
                    progress.update_status(TorrentStatus.DOWNLOADING_METADATA)
                    files = engine.load_data(torrent.data)
                    if file_id is not None:
                        if file_id not in files:
                            raise AceStreamError(33048, "Invalid file index specified (%d)" % file_id)
                    else:
                        if not files:
                            raise AceStreamError(33050, "No playable files detected")
                        file_id = files.iterkeys().next()
                    self.log.info("Start prebuffering...")
                    engine.play_data(torrent.data, [file_id])
                    while True:
                        status = engine.get_status()
                        if status.url:
                            list_item['path'] = status.url
                            break
                        state = self._convert_state(status)
                        update_status = [state, status.download, status.down_speed, status.up_speed,
                                         0, status.peers, status.progress]
                        progress.update_status(*update_status)
                        self._poll_engine(self.POLL_DELAY)

                with closing(self.playing_progress) as progress:
                    with nested(player.attached(player.PLAYBACK_PAUSED, self.playing_progress.open),
                                player.attached(player.PLAYBACK_RESUMED, self.playing_progress.close),
                                player.attached(player.PLAYBACK_STARTED, self.engine.on_start),
                                player.attached(player.PLAYBACK_PAUSED, self.engine.on_pause),
                                player.attached(player.PLAYBACK_RESUMED, self.engine.on_resume),
                                player.attached(player.PLAYBACK_STOPPED, self.engine.on_stop),
                                player.attached(player.PLAYBACK_SEEK, self.engine.on_seek)):
                        self.log.info("Starting playback...")
                        player.play(list_item)
                        progress.name = torrent.name
                        progress.size = torrent.files[file_id].length
                        start = time.time()
                        while player.is_playing() or time.time()-start < self.playback_start_timeout:
                            status = engine.get_status()
                            state = self._convert_state(status)
                            update_status = [state, int(round(progress.size*status.progress/100.0)),
                                             status.down_speed, status.up_speed, 0, status.peers, status.progress]
                            progress.update_status(*update_status)
                            player.get_percent()
                            self._poll_engine(self.POLL_DELAY)

                        # handling PLAYBACK_STOPPED and PLAYBACK_ENDED events
                        sleep(1000)
        except AbortError:
            self.log.info("Playback aborted.")
        except Error as err:
            raise self._convert_engine_error(err)
        if file_id in self.engine.saved_files:
            return [self.engine.saved_files[file_id]]
        return []
import datetime
from mediapoisk.common import sleep, abort_requested
from mediapoisk.library import update_library
from mediapoisk.plugin import plugin
from xbmcswift2 import xbmc
import mediapoisk.plugin.main


def safe_update():
    try:
        update_library()
        plugin.close_storages()
    except Exception as e:
        plugin.log.exception(e)

if __name__ == '__main__':
    sleep(5000)
    safe_update()
    next_run = None
    while not abort_requested():
        now = datetime.datetime.now()
        if not next_run:
            next_run = now
            next_run += datetime.timedelta(hours=12)
            plugin.log.info("Scheduling next library update at %s" % next_run)
        elif now > next_run:
            if not xbmc.Player().isPlaying():
                safe_update()
                next_run = None
        sleep(1000)
 def _poll_engine(self, delay):
     sleep(int(delay*1000))
     if self._aborted():
         raise AbortError()