def echo(self, r_clients, w_clients): # def read_requests(self, r_clients): responses = {} for sock in r_clients: try: data = sock.recv(1024) m = Message() m.decode(data) responses[sock] = m print('Message received', m) log.debug(f'data = {responses[sock]}') except Exception as e: self.client_disconnect(e, sock) try: if responses[sock]: print('responses: ', responses) if responses[sock].action == 'auth_info': self.auth(responses[sock].__dict__()) elif responses[sock].action == 'info_request': self.send_info() elif responses[sock].action == 'message': self.write_responses(responses[sock], w_clients) except KeyError: print('Client disconnected')
def run(self): # well this is just fugly. call it "experimental" while Config.running: try: scrobble_item = self.queue.get(0) try: song = scrobble_item.song type = scrobble_item.type error = scrobble_item.error etime = scrobble_item.etime try: (tracknumber, artist, album, track) = [escape(item) for item in song.tags] except ValueError: log.info("skipping scrobble for {} (bad tags)".format(song.path)) continue if type == NOW_PLAYING: log.debug(u"scrobbling now playing %s %s %s" % (artist, track, album)) self.login() scrobbler.now_playing( artist, track) # now_playing auto flushes, apparently. don't call # flush here or it will throw an exception, which is not # what we want. elif type == PLAYED: # See: http://exhuma.wicked.lu/projects/python/scrobbler/api/public/scrobbler-module.html#login # if mimetype is wrong, length == 0 if song.length < 30: log.warn(u"song length %s" % song.length) # wait 60 seconds before re-trying # submission if error: if (time.time() - etime) < 60: break log.debug(u"scrobbling played %s %s %s %s" % (artist, track, album, song.length)) self.login() scrobbler.submit( artist, track, int(time.mktime(datetime.datetime.now().timetuple())), source=escape(u'P'), length=song.length, album=album) scrobbler.flush() except Exception as e: log.exception(u"scrobble error: %s" % e) # put it back scrobble_item.error = True scrobble_item.etime = time.time() self.queue.put(scrobble_item) except Queue.Empty: pass # AS API enforced limit -- do not change. time.sleep(10)
def process(self, session): # Get lap number and distance lap_number = self.get_lap_number() if not lap_number: # If we can't retrieve lap number, we can't do anything here log.debug( "Can't retrieve lap number from lap packet - not processing") return session lap_distance = self.get_lap_distance() # session.lap_distance = lap_distance # Enable this for motion packet / minimap # Handle in- and outlaps - essentially ignore everything, just update lap before outlap # Race sessions have 1 outlap at the end if session.is_race() or session.is_qualifying_one_shot(): is_out_or_inlap = self.is_race_inlap(session, lap_number) # Quali sessions have inlaps and outlaps elif session.is_qualifying_non_one_shot(): is_out_or_inlap = self.is_quali_out_or_inlap(session, lap_number) else: # time trial, practive is_out_or_inlap = False if is_out_or_inlap: if not session.current_lap_in_outlap_logging_status: log.info("Skipping lap #%s because it's an in-/outlap" % lap_number) # In normal quali, the inlap is #n+1; In race it's #n last_valid_lap_number = lap_number if not session.is_qualifying_non_one_shot( ) else lap_number - 1 self.update_previous_lap( session, last_valid_lap_number + 1) # +1 because we're updating the previous lap session.complete_lap_v2(last_valid_lap_number) # Make sure to not log for this lap anymore session.current_lap_in_outlap_logging_status = True return session else: # Perform clean-up of previous in-/outlap data if session.current_lap_in_outlap_logging_status: # Drop all data of this lap, so that telemetry gets reset lap_number_to_drop = lap_number + 1 if not session.is_qualifying_non_one_shot( ) else lap_number session.drop_lap_data(lap_number_to_drop) # Reset outlap logger session.current_lap_in_outlap_logging_status = False # Handle new laps if self.is_new_lap(session, lap_number): # Update previous lap with sector 3 time self.update_previous_lap(session, lap_number) # Start new lap, which in turn starts telemetry session.start_new_lap(lap_number) # Push lap-1 to F1Laps session.complete_lap_v2(lap_number - 1) # Update current lap and telemetry session = self.update_current_lap(session) session = self.update_telemetry(session) return session
def _read_config(self): try: f = open(get_path_executable_parent(self.config_file_name), "r") file_content = f.readlines() f.close() return file_content except Exception as ex: log.debug("Could not read config file (%s)" % ex) return None
def process(self, session): # if the user is spectating, we don't create a session if self.isSpectating: log.debug("Session is in spectating mode") return None if not self.is_active_session(session): return self.create_session() else: return self.update_session(session)
def startListening_(self, sender=None): """Start listening for changes to the screenshot dir.""" event_handler = ScreenshotHandler() self.observer = Observer() self.observer.schedule(event_handler, path=SCREENSHOT_DIR) self.observer.start() self.update_menu() log.debug('Listening for screen shots to be added to: %s' % (SCREENSHOT_DIR)) notify('UpShot started', 'and listening for screenshots!')
def startListening_(self, sender=None): """Start listening for changes to the screenshot dir.""" event_handler = ScreenshotHandler() self.observer = Observer() self.observer.schedule(event_handler, path=SCREENSHOT_DIR) self.observer.start() self.update_menu() log.debug('Listening for screen shots to be added to: %s' % ( SCREENSHOT_DIR)) notify('UpShot started', 'and listening for screenshots!')
def frame(self, frame_number): if not self.current_lap: log.debug( "Attempted to get/set a telemetry frame without a current lap") return None frame_dict = self.current_lap.frame_dict if frame_number not in frame_dict: frame_dict[frame_number] = [] for i in range(0, len(KEY_INDEX_MAP)): frame_dict[frame_number].append(None) return frame_dict[frame_number]
def __norm_jd_mat(self): """ 归一化判断矩阵 :return: """ log.debug("\n{}".format(self.__judgement_matrix)) x, y = self.__judgement_matrix.shape for i in range(y): self.__judgement_matrix[:, i] = self.__judgement_matrix[:, i] / sum( self.__judgement_matrix[:, i]) log.debug(self.__judgement_matrix)
def __calc_weight_vector(self): """ 计算权值向量 :return: """ temp = [] x, y = self.__judgement_matrix.shape for i in range(x): row = self.__judgement_matrix[i, :] temp.append(reduce(lambda x, y: x * y, row)**(1. / (y * 1.))) log.debug(temp) self.__weight_vector = np.array(temp)
def _write_config(self): file_lines = [] for key, value in self.config.items(): file_lines.append("%s=%s" % (key, value)) if not file_lines: return try: with open(get_path_executable_parent(self.config_file_name), 'w+') as f: f.writelines("%s\n" % l for l in file_lines) except Exception as ex: log.debug("Could not write to config file: %s" % ex)
def read_requests(self, r_clients): responses = {} for sock in r_clients: try: data = sock.recv(1024) responses[sock] = data.decode('utf-8') log.debug(f'data = {responses[sock]}') except Exception as e: log.error( f'Клиент {sock.fileno()} {sock.getpeername()} отключился\n\t\t{e}' ) self.clients.remove(sock) return responses
def get_socket(self): # Open and bind socket new_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) new_socket.setsockopt(socket.SOL_SOCKET, self.get_socket_reuse_option(), 1) if self.use_udp_broadcast: # Enable broadcasting mode log.info("Using UDP broadcast mode") new_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) new_socket.bind(("", self.host_port)) else: log.info("Using UDP unicast mode") new_socket.bind((self.host_ip, self.host_port)) log.debug("Socket opened and bound") return new_socket
def unpack_udp_packet(packet): """ Important function - processes each packet First reads the header, which maps to the right body packet Returns the mapped body packet """ header = PacketHeader.from_buffer_copy(packet) packet_type = HeaderFieldsToPacketType.get(header.packetId) log.debug("Found packet type %s ID %s" % (packet_type, header.packetId)) if packet_type: return packet_type.from_buffer_copy(packet) else: log.debug("Received unknown packet_type %s" % packet_type) return None
def stopListening_(self, sender=None): """Stop listening to changes ot the screenshot dir.""" if self.observer is not None: self.observer.stop() self.observer.join() self.observer = None log.debug('Stop listening for screenshots.') if sender == self.menuitems['quit']: notify('UpShot shutting down', 'Not listening for screenshots anymore!') else: notify('UpShot paused', 'Not listening for screenshots for now!') self.update_menu()
def get_path_temporary(file_name): """ Get the path of the temporary folder created by bundled exes Used to retrive image files, like the F1Laps logo """ bundle_dir = None try: if getattr(sys, 'frozen'): bundle_dir = sys._MEIPASS except Exception as ex: log.debug("Could not find sys._MEIPASS (%s)" % ex) if not bundle_dir: bundle_dir = path.abspath(path.dirname(path.dirname(__file__))) path_to_file = path.abspath(path.join(bundle_dir, file_name)) return path_to_file
def get_path_executable_parent(file_name): """ Get the path of the executable's enclosing folder Used to create the config file next to the exe """ bundle_dir = None try: if getattr(sys, 'frozen'): bundle_dir = sys.executable except Exception as ex: log.debug("Could not find sys.frozen or sys.executable (%s)" % ex) if not bundle_dir: bundle_dir = path.abspath(path.dirname(__file__)) path_to_file = path.abspath(path.join(path.dirname(bundle_dir), file_name)) return path_to_file
def register_callback(self, callback): """ Callback is a callable we want to hold on to for later click handling. It'll be stored as a weak reference (i.e., garbage collectable) in self.callbacks. Returns serializable callback ID. """ callback_id = str(callback.__hash__()) # XXX: We're not cleaning these up because more than one notification # will have the same handler. If we do this a lot, this will leak memory. self.callbacks[callback_id] = callback log.debug('Registered callback ID %s' % callback_id) return callback_id
def click_handler(self, context): """ Handle a click by handing context data back to a previously registered callback. context is 'callback_id:string', e.g., '12345:/a/path/to/open'. """ if not context: return callback_id, data = context.split(':', 1) callback = self.callbacks.get(callback_id) if callback: log.debug('Click callback %s with context %s' % ( callback.__name__, data)) callback(data)
def create_session(self): session = F12021Session(session_uid=self.header.sessionUID) session.session_udp_uid = self.header.sessionUID session.set_session_type(self.sessionType) if not self.sessionType: log.warning("Got Session packet without sessionType") session.track_id = self.trackId session.ai_difficulty = self.aiDifficulty if self.networkGame == 1: session.is_online_game = True if self.weather not in session.weather_ids: session.weather_ids.append(self.weather) session.start() log.debug("Session vals: season %s weekend %s session %s UID %s" % (self.seasonLinkIdentifier, self.weekendLinkIdentifier, self.sessionLinkIdentifier, self.header.sessionUID)) return session
def click_handler(self, context): """ Handle a click by handing context data back to a previously registered callback. context is 'callback_id:string', e.g., '12345:/a/path/to/open'. """ if not context: return callback_id, data = context.split(':', 1) callback = self.callbacks.get(callback_id) if callback: log.debug('Click callback %s with context %s' % (callback.__name__, data)) callback(data)
def do_HEAD(self, icy_client): log.debug("head") #if icy_client: self.send_response(200, "ICY") # fixme verbose headers = { 'icy-notice1' : Config.notice_1, 'icy-notice2' : Config.notice_2, 'icy-name' : Config.icy_name, 'icy-genre' : Config.icy_genre, 'icy-url' : Config.icy_url, 'icy-pub' : Config.icy_pub, #'icy-br' : 128, 'icy-metaint' : Config.icy_metaint, 'content-type' : Config.content_type } [self.send_header(k, v) for k, v, in headers.iteritems()] self.end_headers()
def lap_should_be_sent_to_f1laps(self, lap_number): lap = self.lap_list.get(lap_number) lap_f1laps_status_key = "has_been_sent_to_f1laps" if not lap: log.info("Not sending lap #%s to F1Laps because it doesn't exist" % lap_number) return False if not bool( lap.get('sector_1_ms') and lap.get('sector_2_ms') and lap.get('sector_3_ms')): log.info( "Not sending lap #%s to F1Laps because it doesn't have non-zero values for all sectors" % lap_number) return False if lap.get(lap_f1laps_status_key): log.debug( "Not sending lap #%s to F1Laps because it has already been posted" % lap_number) return False # Mark this session as "already sent to F1Laps, don't send again" lap[lap_f1laps_status_key] = True return True
def process(self, session): log.debug( "Skipping incoming %s because it doesn't have a '.process()' method" % self.__class__.__name__) return session
def swallow_exceptions(*args, **kwargs): try: return f(*args, **kwargs) except Exception, e: log.debug(e)
def handle_screenshot_candidate(self, f): """Given a candidate file, handle it if it's a screenshot.""" # The file could be anything. Only act if it's a screenshot. if not utils.is_screenshot(f): log.debug('%s is missing or not a screenshot.' % f) return # Do not act on files that are too old (so we don't swallow old files # that are not new screenshots). now = time.time() filename_time = utils.timestamp_from_filename( f) # Parse time out of filename. if (now - os.path.getctime(f) > TIME_THRESHOLD or not filename_time or now - filename_time > TIME_THRESHOLD): log.debug('Ignoring %s, too old.' % f) return # Create target dir if needed. if not os.path.isdir(SHARE_DIR): log.debug('Creating share dir %s' % SHARE_DIR) os.makedirs(SHARE_DIR) # Determine target filename in share directory. log.debug('Moving %s to %s' % (f, SHARE_DIR)) if utils.get_pref('randomize'): # Randomize file names? ext = os.path.splitext(f)[1] while True: shared_name = utils.randname() + ext target_file = os.path.join(SHARE_DIR, shared_name) if not os.path.exists(target_file): log.debug('New file name is: %s' % shared_name) break else: shared_name = os.path.basename(f) target_file = os.path.join(SHARE_DIR, shared_name) # Move/copy file there. if (utils.get_pref('retinascale') and utils.resampleRetinaImage(f, target_file)): if not utils.get_pref('copyonly'): os.unlink(f) else: if utils.get_pref('copyonly'): shutil.copy(f, target_file) else: shutil.move(f, target_file) # Create shared URL. url = utils.share_url(urllib.quote(shared_name)) log.debug('Share URL is %s' % url) log.debug('Copying to clipboard.') utils.pbcopy(url) # Notify user. notify('Screenshot shared!', 'Your URL is: %s\n\n' 'Click here to view file.' % url, context=target_file, callback=self.notify_callback)
def quit_(self, sender=None): """Default quit event.""" log.debug('Terminating.') self.stopListening_(sender) NSApplication.sharedApplication().terminate_(sender)
def add_participant(self, **kwargs): participant = ParticipantBase(**kwargs) self.participants.append(participant) log.debug("Added Participant: %s" % participant)
def run(self): # well this is just fugly. call it "experimental" while Config.running: try: scrobble_item = self.queue.get(0) try: song = scrobble_item.song type = scrobble_item.type error = scrobble_item.error etime = scrobble_item.etime try: (tracknumber, artist, album, track) = [escape(item) for item in song.tags] except ValueError: log.info("skipping scrobble for {} (bad tags)".format( song.path)) continue if type == NOW_PLAYING: log.debug(u"scrobbling now playing %s %s %s" % (artist, track, album)) self.login() scrobbler.now_playing(artist, track) # now_playing auto flushes, apparently. don't call # flush here or it will throw an exception, which is not # what we want. elif type == PLAYED: # See: http://exhuma.wicked.lu/projects/python/scrobbler/api/public/scrobbler-module.html#login # if mimetype is wrong, length == 0 if song.length < 30: log.warn(u"song length %s" % song.length) # wait 60 seconds before re-trying # submission if error: if (time.time() - etime) < 60: break log.debug(u"scrobbling played %s %s %s %s" % (artist, track, album, song.length)) self.login() scrobbler.submit( artist, track, int( time.mktime( datetime.datetime.now().timetuple())), source=escape(u'P'), length=song.length, album=album) scrobbler.flush() except Exception as e: log.exception(u"scrobble error: %s" % e) # put it back scrobble_item.error = True scrobble_item.etime = time.time() self.queue.put(scrobble_item) except Queue.Empty: pass # AS API enforced limit -- do not change. time.sleep(10)
def cleanup(self): log.debug("cleaning up") self.manager.shutdown() self.server_close()
def do_GET(self): log.debug("post") # Handle well-behaved bots _path = self.path.strip() log.info("Request path: %s" % _path) if _path == "/robots.txt": self.send("User-agent: *\nDisallow: /\n") elif _path != "/": self.send_error(403, "Bad request.\n") else: # path is / # # examine some headers # Client candidates: """ cmus """ # GET / HTTP/1.0 # Host: 0x7be.org # User-Agent: cmus/v2.3.2 # Icy-MetaData: 1 """ mplayer """ # GET / HTTP/1.0 # Host: 0x7be.org:18944 # User-Agent: MPlayer/SVN-r31347-4.5.0 # Icy-MetaData: 1 # Connection: close # GET / HTTP/1.0 # Accept: */* # User-Agent: NSPlayer/4.1.0.3856 # Host: 0x7be.org:18944 # Pragma: xClientGUID={c77e7400-738a-11d2-9add-0020af0a3278} # Pragma: no-cache,rate=1.000000,stream-time=0,stream-offset=0:0, # request-context=1,max-duration=0 # Connection: Close """ squeezebox """ # Connection: close # Cache-Control: no-cache # Accept: */* # Host: localhost:18944 # User-Agent: iTunes/4.7.1 (Linux; N; Linux; i686-linux; EN; # utf8) SqueezeCenter, Squeezebox Server/7.4.1/28947 # Icy-Metadata: 1 H, icy_client = self.headers, False try: icy_client = (int(H['icy-metadata']) == 1) except KeyError, e: log.error("non-icy client: %s" % e) log.error(self.address_string()) if not icy_client: self.send_response(400, "Bad client.\n Try http://cmus.sourceforge.net/\n") return False user_agent = None try: user_agent = H['user-agent'] except KeyError, e: log.exception("Couldn't get user agent.") if user_agent: log.info("User-Agent: %s" % user_agent) self.do_HEAD( icy_client ) Streamer( self.request, self.server.port ).stream( icy_client )
def handle_screenshot_candidate(self, f): """Given a candidate file, handle it if it's a screenshot.""" # The file could be anything. Only act if it's a screenshot. if not utils.is_screenshot(f): log.debug('%s is missing or not a screenshot.' % f) return # Do not act on files that are too old (so we don't swallow old files # that are not new screenshots). now = time.time() filename_time = utils.timestamp_from_filename(f) # Parse time out of filename. if (now - os.path.getctime(f) > TIME_THRESHOLD or not filename_time or now - filename_time > TIME_THRESHOLD): log.debug('Ignoring %s, too old.' % f) return # Create target dir if needed. if not os.path.isdir(SHARE_DIR): log.debug('Creating share dir %s' % SHARE_DIR) os.makedirs(SHARE_DIR) # Determine target filename in share directory. log.debug('Moving %s to %s' % (f, SHARE_DIR)) if utils.get_pref('randomize'): # Randomize file names? ext = os.path.splitext(f)[1] while True: shared_name = utils.randname() + ext target_file = os.path.join(SHARE_DIR, shared_name) if not os.path.exists(target_file): log.debug('New file name is: %s' % shared_name) break else: shared_name = os.path.basename(f) target_file = os.path.join(SHARE_DIR, shared_name) # Move/copy file there. if (utils.get_pref('retinascale') and utils.resampleRetinaImage(f, target_file)): if not utils.get_pref('copyonly'): os.unlink(f) else: if utils.get_pref('copyonly'): shutil.copy(f, target_file) else: shutil.move(f, target_file) # Create shared URL. url = utils.share_url(urllib.quote(shared_name)) log.debug('Share URL is %s' % url) log.debug('Copying to clipboard.') utils.pbcopy(url) # Notify user. notify('Screenshot shared!', 'Your URL is: %s\n\n' 'Click here to view file.' % url, context=target_file, callback=self.notify_callback)