def setup(): global timer reactor.callWhenRunning(create_shell_server) reactor.startRunning() timer = RepeatingTimer(0.01, catch_up, daemon=True) timer.start() logging.info("Debug terminal initialized.")
def start(self): """ Sends a ping request to the server in an interval. """ print("[Pinger] Started") thread = RepeatingTimer(self.ping_interval, self.ping) thread.daemon = True thread.start()
class Updating (Buffer): def __init__ (self, session, interval=None, *args, **kwargs): self._update_types = dict(initial=1, auto=2, forced=3, default=2) super(Updating, self).__init__(session, *args, **kwargs) self.update_lock = threading.Lock() self.set_flag('updatable', True) if not interval and interval != 0: try: interval = self.buffer_metadata['interval'] except: interval = session.config.get('updates', {}).get('checkInterval', 0) self.buffer_metadata['interval'] = interval self.interval = self.buffer_metadata['interval'] if not hasattr(self, 'item_name'): self.item_name = _("message") self.item_name_plural = _("messages") self.item_sound = "" if hasattr(self.session, 'default_sound'): self.item_sound = self.session.default_sound if self.interval: self.setup_timer() def shutdown(self, *args, **kwargs): self.deactivate_timer() super(Updating, self).shutdown(*args, **kwargs) def deactivate_timer(self): if self.buffer_metadata['interval']: try: self.timer.stop() logging.debug("%s: Deactivated update timer in buffer %s" % (self.session, self)) except: logging.exception("%s: Error shutting down update timer in session %s." % (self.session, self)) def set_new_interval (self, interval=None): if interval == None: interval = self.buffer_metadata['interval'] if self.buffer_metadata['interval']: self.deactivate_timer() self.buffer_metadata['interval'] = interval if interval: self.setup_timer(run_immediately=False) def setup_timer (self, run_immediately=True): if self.buffer_metadata['interval']: self.timer = RepeatingTimer(self.buffer_metadata['interval'], self.update) self.timer.start() if run_immediately: logging.info("%s: performing immediate update in buffer %s" % (self.session, self)) call_threaded(self.update, update_type=self._update_types['initial']) @set_update_type def update(self, update_type=None, *args, **kwargs): """The Update method. Called to check for new information and consolidate it into this buffer.""" if hasattr(self, 'init_done_event'): self.init_done_event.wait() if not self.get_flag('updatable') and update_type == self._update_types['forced']: raise UpdateError("Buffer %r is not updatable." % self) if not self.update_lock.acquire(False): if update_type == self._update_types['forced']: output.speak(_("Update already in progress; please wait."), True) return try: if update_type == self._update_types['forced']: output.speak(self.update_message, True) logging.debug("Synchronizer: Updating buffer %s." % self) try: new = self.retrieve_update(update_type=update_type) except: return logging.exception("%s: Error during update process in buffer %s" % (self.session, self)) self.handle_update(new, update_type=update_type, *args, **kwargs) finally: self.update_lock.release() @set_update_type def handle_update(self, data, update_type=None, *args, **kwargs): data = self.process_update(data, update_type=update_type) if data and self.session.buffer_exists(self): #Add new items to buffer storage try: self.extend(items=data, update_type=update_type, *args, **kwargs) except: return logging.exception("%s: Error writeing new items to storage in buffer %s." % (self.session, self)) #Send an event out with the new items we got for any buffers that depend on this buffer's data. try: dispatcher.send(sender=self, signal=signals.buffer_updated, items=data, update_type=update_type, **kwargs) except: logging.exception("%s: Error sending buffer_updated event in buffer %s." % (self.session, self)) self.report_update(data, update_type=update_type) def retrieve_update(self, *args, **kwargs): #Dumby method. Replace with code to update this buffer. raise NotImplementedError def process_update(self, update, *args, **kwargs): return self.find_new_data(update) @set_update_type def report_update(self, items, msg="", update_type=None, *args, **kwargs): if not msg: use_default_msg = True else: use_default_msg = False counter = len(items) if not counter: if update_type == self._update_types['forced']: self.speak(_("No new %s.") % self.item_name_plural, honor_mute=False) return try: self.play(self.item_sound) except: pass if sessions.current_session is not self.session: msg = _("%s: %s") % (self.session, msg) if use_default_msg: if counter == 1: item_name = _(self.item_name) else: item_name = _(self.item_name_plural) msg = ngettext("%(msg)s1 %(item_name)s.", "%(msg)s%(num)d %(item_name)s.", counter) % {'msg': msg, 'item_name': item_name, 'num': counter} if update_type != self._update_types['auto']: self.speak(_(msg), honor_mute=False) else: self.speak(_(msg)) def extend(self, items=[], *args, **kwargs): super(Updating, self).extend(items) @property def update_message(self): return _("Checking for %s.") % self.item_name_plural
class Updating(Buffer): def __init__(self, session, interval=None, *args, **kwargs): self._update_types = dict(initial=1, auto=2, forced=3, default=2) super(Updating, self).__init__(session, *args, **kwargs) self.update_lock = threading.Lock() self.set_flag('updatable', True) if not interval and interval != 0: try: interval = self.buffer_metadata['interval'] except: interval = session.config.get('updates', {}).get('checkInterval', 0) self.buffer_metadata['interval'] = interval self.interval = self.buffer_metadata['interval'] if not hasattr(self, 'item_name'): self.item_name = _("message") self.item_name_plural = _("messages") self.item_sound = "" if hasattr(self.session, 'default_sound'): self.item_sound = self.session.default_sound if self.interval: self.setup_timer() def shutdown(self, *args, **kwargs): self.deactivate_timer() super(Updating, self).shutdown(*args, **kwargs) def deactivate_timer(self): if self.buffer_metadata['interval']: try: self.timer.stop() logging.debug("%s: Deactivated update timer in buffer %s" % (self.session, self)) except: logging.exception( "%s: Error shutting down update timer in session %s." % (self.session, self)) def set_new_interval(self, interval=None): if interval == None: interval = self.buffer_metadata['interval'] if self.buffer_metadata['interval']: self.deactivate_timer() self.buffer_metadata['interval'] = interval if interval: self.setup_timer(run_immediately=False) def setup_timer(self, run_immediately=True): if self.buffer_metadata['interval']: self.timer = RepeatingTimer(self.buffer_metadata['interval'], self.update) self.timer.start() if run_immediately: logging.info("%s: performing immediate update in buffer %s" % (self.session, self)) call_threaded(self.update, update_type=self._update_types['initial']) @set_update_type def update(self, update_type=None, *args, **kwargs): """The Update method. Called to check for new information and consolidate it into this buffer.""" if hasattr(self, 'init_done_event'): self.init_done_event.wait() if not self.get_flag( 'updatable') and update_type == self._update_types['forced']: raise UpdateError("Buffer %r is not updatable." % self) if not self.update_lock.acquire(False): if update_type == self._update_types['forced']: output.speak(_("Update already in progress; please wait."), True) return try: if update_type == self._update_types['forced']: output.speak(self.update_message, True) logging.debug("Synchronizer: Updating buffer %s." % self) try: new = self.retrieve_update(update_type=update_type) except: return logging.exception( "%s: Error during update process in buffer %s" % (self.session, self)) self.handle_update(new, update_type=update_type, *args, **kwargs) finally: self.update_lock.release() @set_update_type def handle_update(self, data, update_type=None, *args, **kwargs): data = self.process_update(data, update_type=update_type) if data and self.session.buffer_exists(self): #Add new items to buffer storage try: self.extend(items=data, update_type=update_type, *args, **kwargs) except: return logging.exception( "%s: Error writeing new items to storage in buffer %s." % (self.session, self)) #Send an event out with the new items we got for any buffers that depend on this buffer's data. try: dispatcher.send(sender=self, signal=signals.buffer_updated, items=data, update_type=update_type, **kwargs) except: logging.exception( "%s: Error sending buffer_updated event in buffer %s." % (self.session, self)) self.report_update(data, update_type=update_type) def retrieve_update(self, *args, **kwargs): #Dumby method. Replace with code to update this buffer. raise NotImplementedError def process_update(self, update, *args, **kwargs): return self.find_new_data(update) @set_update_type def report_update(self, items, msg="", update_type=None, *args, **kwargs): if not msg: use_default_msg = True else: use_default_msg = False counter = len(items) if not counter: if update_type == self._update_types['forced']: self.speak(_("No new %s.") % self.item_name_plural, honor_mute=False) return try: self.play(self.item_sound) except: pass if sessions.current_session is not self.session: msg = _("%s: %s") % (self.session, msg) if use_default_msg: if counter == 1: item_name = _(self.item_name) else: item_name = _(self.item_name_plural) msg = ngettext("%(msg)s1 %(item_name)s.", "%(msg)s%(num)d %(item_name)s.", counter) % { 'msg': msg, 'item_name': item_name, 'num': counter } if update_type != self._update_types['auto']: self.speak(_(msg), honor_mute=False) else: self.speak(_(msg)) def extend(self, items=[], *args, **kwargs): super(Updating, self).extend(items) @property def update_message(self): return _("Checking for %s.") % self.item_name_plural
class Sound (Configuration, Interface): MAX_OUTPUT_RESETS = 2 #How many times do we let the play method reset the output if sounds won't play to pickup soundcard changes? def __init__ (self, *args, **kwargs): super(Sound, self).__init__(*args, **kwargs) self.setup_sound() self.currently_playing = None self.sounds = [] self.announce_session_mute(first=True) self.sound_cleaner = RepeatingTimer(30, self.cleanup_sounds) self.sound_cleaner.start() self.delete_old_tempfiles() @staticmethod def delete_old_tempfiles(): for f in glob(os.path.join(tempfile.gettempdir(), 'tmp*.wav')): try: os.remove(f) except: pass def setup_sound(self, forced=False): if forced or not getattr(global_vars, 'sound_output', None): logging.debug("Initializing sound subsystem.") if hasattr(global_vars, 'sound_output') and global_vars.sound_output: global_vars.sound_output.free() try: global_vars.sound_output = sound_output.Output() global_vars.sound_input = sound_input.Input() global_vars.sound_output.volume = config.main['sounds']['volume'] except: global_vars.sound_output = None global_vars.sound_input = None if hasattr(global_vars, 'sound_output') and 'sounds' in self.config and 'defaultSound' in self.config['sounds']: self.default_sound = self.config['sounds']['defaultSound'] def play(self, file, this_retry=0, honor_mute=True): if honor_mute and (config.main['sounds']['mute'] or self.config['sounds']['mute']): return if not os.path.split(file)[0]: #it's just the file! try: file = self.find_sound_file(os.path.split(file)[1]) except IOError: #The file wasn't found return try: snd = stream.FileStream(file=unicode(file), flags=stream.BASS_UNICODE) snd.play() except BassError as e: if this_retry < self.MAX_OUTPUT_RESETS: self.setup_sound(forced=True) return self.play(file, this_retry=this_retry+1) raise e self.sounds.append(snd) return snd def play_stream (self, url): try: snd = stream.URLStream(url=str(url.encode('utf-8'))) except BassError as e: if e.code == 32: output.speak(_("No internet connection could be opened."), True) else: logging.exception("Unable to play stream") output.speak(_("Unable to play audio."), True) raise e snd.play() self.sounds.append(snd) return snd def record_sound(self, filename): try: val = recording.WaveRecording(filename=filename) except BassError as e: global_vars.sound_input = sound_input.Input() val = recording.WaveRecording(filename=filename) return val def find_sound_file (self, file): #Check if the session has a soundpack and if so play the sound from that if not 'soundPack' in self.config['sounds']: sound_file = paths.sounds_path('standard\\%s' % file) else: if not os.path.exists(paths.sounds_path(self.config['sounds']['soundPack'])): logging.warning("Unable to find soundpack %s" % self.config['sounds']['soundPack']) return sound_file = paths.sounds_path(r'%s\%s' % (self.config['sounds']['soundPack'], file)) if not os.path.exists(sound_file): logging.warning('Unable to find sound file %r' % file) raise IOError, "Unable to find sound file" return sound_file def toggle_session_mute (self): self.config['sounds']['mute'] = not self.config['sounds']['mute'] def announce_session_mute (self, first=False): if not self.config['sounds']['mute'] and not first: output.speak(_("Session mute off"), True) elif self.config['sounds']['mute']: output.speak(_("Session mute on"), not first) if first: self.announce_global_mute(first=first) def announce_global_mute (self, first=False): if not config.main['sounds']['mute'] and not first: output.speak(_("Global mute off"), True) elif config.main['sounds']['mute']: output.speak(_("Global mute on"), not first) def toggle_global_mute(self): config.main['sounds']['mute'] = not config.main['sounds']['mute'] config.main.write() def cleanup_sounds(self): old_len = len(self.sounds) for i in self.sounds: if i.is_active(): continue try: i.free() except: pass self.sounds.remove(i) if not self.sounds: self.setup_sound() def get_volume (self): return global_vars.sound_output.volume def set_volume (self, volume): if volume <= 0: volume = 0 config.main['sounds']['volume'] = volume global_vars.sound_output.volume = volume config.main.write() volume = property(get_volume, set_volume) def shutdown(self, *args, **kwargs): try: self.sound_cleaner.stop() logging.debug("%s: Sound Cleaner: Deactivated timer." % self) except: logging.exception("%s: Sound Cleaner: Error shutting down timer." % self) for i in self.sounds: i.stop() self.cleanup_sounds() super(Sound, self).shutdown(*args, **kwargs) def recode_audio(self, filename, quality=4.5): subprocess.call(r'"%s" -q %r "%s"' % (paths.app_path('oggenc2.exe'), quality, filename)) def user_playback(self, path, stream=False): if self.currently_playing is not None: self.stop_user_playback() if not stream: self.currently_playing = self.play(path, honor_mute=False) else: self.currently_playing = self.play_stream(path) def stop_user_playback(self): try: self.currently_playing.stop() self.currently_playing.free() except BassError: pass self.currently_playing = None