def broadcast_players(g_id): global pcb2 global cur_g_id data_dict = {} if pcb2 is None: cur_g_id = g_id pcb2 = PeriodicCallback(lambda: broadcast_players(g_id), 4000) pcb2.start() elif cur_g_id != g_id: cur_g_id = g_id pcb2.stop() pcb2 = PeriodicCallback(lambda: broadcast_players(g_id), 4000) pcb2.start() g_list = ww_redis_db.keys(g_id+"*") for v in g_list: v = v.decode("utf-8") if len(g_list) > 0: # find game with least spaces for g_key in g_list: game = ww_redis_db.hgetall(g_key) game = {k.decode('utf8'): v.decode('utf8') for k, v in game.items()} #convert from byte array to string dict players = game['players'].split("|") # obtain players in current game in the form of uuid data_dict[g_key.decode("utf-8")] = str(len(players)) data_dict["channel"] = "player_list" publish_data("player_list:"+g_id, data_dict) return data_dict
def send_swampdragon_push(sender, instance, created, **kwargs): if created: serializer = FeedPostSerializer(instance=instance) publish_data(channel='post-24', data=serializer.data)
def broadcast_match_info(): global pcb if pcb is None: pcb = PeriodicCallback(broadcast_match_info, 500) pcb.start() matches = MatchModel.objects.all() match_status = {} for match in matches: fixture = FixtureModel.objects.get(id=match.match_id) r = ResultModel.objects.get(id=match.match_id) if(r.result != 'None'): match_status['color'+str(match.match_id)] = 'info' continue dd = fixture.match_day - timezone.now() dd_str = None if(timezone.now() > fixture.match_day): dd_str = "Locked" match_status['color'+str(match.match_id)] = 'danger' else: dd_str = "%sd:%sh:%sm:%ss" %(str(dd.days),str((dd.seconds//3600)%24),str((dd.seconds%3600)//60), str((dd.seconds%3600)%60),) match_status['color'+str(match.match_id)] = 'success' match_status['time_left'+str(match.match_id)] = dd_str match_status['storedbet'+str(match.id)] = "%s %s" %(match.betting_side, match.betting_points,) match_status['odds'+str(match.match_id)] = "%s:%s" %(fixture.home_odds, fixture.away_odds,) publish_data('matchinfo', { 'match_status': match_status, })
def publish_all_games(): '''Finds all the games currently in redis and returns a JSON of their basic information''' data_dict = {} games_dict = {} all_redis_games = ww_redis_db.keys("g_list:*") ############################################################ # Get all games from redis as a JSON ############################################################ if len(all_redis_games) > 0: for redis_game_key in all_redis_games: g_id = str(redis_game_key.decode("utf-8")).split(":")[1] python_game = Game(g_id) games_dict["game:"+g_id] = python_game.as_JSON() else: log_handler.log( log_type = "INFO", log_code = "CurrentDev", log_message = "No games were found in Redis", log_detail = 5 ) ############################################################ # Publish information ############################################################ data_dict["games"] = games_dict data_dict["channel"] = "games_list" publish_data("lobbyinfo", data_dict) return data_dict
def emit(self, record): """ Handles an emitted log entry and stores it in the database, optionally linking it to the model object `obj` """ obj = record.__dict__.get('obj', None) if obj is None or not isinstance(obj, models.Model) or obj.pk is None: content_type, object_id = None, None else: content_type = apps.get_model('contenttypes', 'ContentType').objects.get_for_model(obj) object_id = obj.pk try: log_entry = apps.get_model('instance', 'LogEntry').objects.create( level=record.levelname, text=self.format(record), content_type=content_type, object_id=object_id ) except ProgrammingError: # This can occur if django tries to log something before migrations have created the log table. # Make sure that is actually what happened: assert 'instance_logentry' not in connection.introspection.table_names() # Send notice of entries related to any resource. Skip generic log entries that occur # in debug mode, like "GET /static/img/favicon/favicon-96x96.png": if content_type: log_event = { 'type': 'object_log_line', 'log_entry': LogEntrySerializer(log_entry).data } if hasattr(obj, 'event_context'): log_event.update(obj.event_context) # TODO: Filter out log entries for which the user doesn't have view rights # TODO: More targetted events - only emit events for what the user is looking at publish_data('log', log_event)
def logout(request): send_logout_notification = request.user.is_authenticated() data = {'id': request.user.id, 'action': 'logout'} response = LogoutView.as_view()(request) if send_logout_notification: publish_data('notifications', data) return response
def broadcast_sys_info(): global upCount, downCount, leftCount, rightCount global pcb, ser if pcb is None: pcb = PeriodicCallback(broadcast_sys_info, 100) pcb.start() valueRead = serialArduino.readline() choiceSearch = re.search("UP|DOWN|LEFT|RIGHT", str(valueRead)) try: left_sent = 0 right_sent = 0 up_sent = 0 down_sent = 0 choice = choiceSearch.group(0) print(choice) if choice == "UP": up_sent += 1 upCount += 1 elif choice == "DOWN": down_sent += 1 downCount += 1 elif choice == "LEFT": left_sent += 1 leftCount += 1 elif choice == "RIGHT": right_sent += 1 rightCount += 1 publish_data("sysinfo", {"left_t": left_sent, "right_t": right_sent, "top": up_sent, "down": down_sent}) except AttributeError: pass
def broadcast_games(): global pcb data_dict = {} games_dict = {} if pcb is None: pcb = PeriodicCallback(broadcast_games, 6000) pcb.start() g_list = ww_redis_db.keys("g_list:*") for v in g_list: v = v.decode("utf-8") if len(g_list) > 0: # find game with least spaces for g_key in g_list: g_id = str(g_key.decode("utf-8")).split(":")[1] game = Game(g_id) games_dict["game:"+g_id] = game.as_JSON() data_dict["game"] = games_dict data_dict["channel"] = "lobbyinfo" publish_data("lobbyinfo", data_dict) return data_dict
def push_system_message(msg): data_dict = {} data_dict["message"] = msg data_dict["channel"] = "sysmsg" publish_data("sysmsg", data_dict) return data_dict
def on_post_save(sender, instance, created, **kwargs): """ Called when an instance is saved """ self = instance publish_data('notification', { 'type': 'server_update', 'server_pk': self.pk, })
def publish_detailed_game(g_id, p_id=None): '''Finds the specified game and creates a detailed JSON, optionally filtering for a specific player''' data_dict = {} # the entire dict to publish games_dict = {} # the dict containing a single record of the game as a JSON string. Kept as a dict to maintain compatibility with other games_dict parsers publish_channel = "game:" + g_id # default publishing to everyone subscribed to the game information_channel = publish_channel # information will always be a game ############################################################ # Get detailed game as a JSON ############################################################ try: redis_game = ww_redis_db.hgetall("g_list:"+g_id) if p_id: requesting_player = user.Player(p_id) publish_channel = "player:" + p_id # publish only to the requesting player if len(redis_game) > 0: #g_id is valid python_game = Game(g_id) full_json = python_game.as_JSON(meta=True, players=True, cur_events=True, hist_events=True) if p_id: filtered_json = python_game.filter_JSON(full_json, requesting_player.knows_about) games_dict["game:"+g_id] = filtered_json else: games_dict["game:"+g_id] = full_json else: log_handler.log( log_type = "ERROR", log_code = "CurrentDev", log_message = "No games were found!", log_detail = 3, context_id = g_id ) raise ValueError("There are no games in redis") ############################################################ # Publish information ############################################################ data_dict["games"] = games_dict data_dict["channel"] = information_channel publish_data(publish_channel, data_dict) return data_dict ############################################################ # Dismiss the error and log. ############################################################ except: logging.exception('') log_handler.log( log_type = "ERROR", log_code = "CurrentDev", log_message = "Could not publish this detailed game", log_detail = 3, context_id = g_id )
def save(self, *args, **kwargs): """ Save this OpenEdXAppServer """ super().save(*args, **kwargs) # Notify anyone monitoring for changes via swampdragon/websockets: publish_data('notification', { 'type': 'openedx_appserver_update', 'appserver_id': self.pk, 'instance_id': self.owner.pk, # This is the ID of the InstanceReference })
def save(self, *args, **kwargs): """ Save this InstanceReference This also gets called whenever the Instance subclass has changed. """ super().save(*args, **kwargs) # Notify anyone monitoring for changes via swampdragon/websockets: publish_data('notification', { 'type': 'instance_update', 'instance_id': self.pk, })
def messages_info(self): global pcb print self.connection.user message_count = Recipient.objects.count_unread_messages_for(self.connection.user) if pcb is None: pcb = PeriodicCallback(self.messages_info, 1000) pcb.start() publish_data('messages_info', { 'messages_data': message_count, })
def publish(self): """ Publish the log entry to the messaging system, broadcasting it to subscribers """ logger.log(self.level_integer, self.text) if self.level in PUBLISHED_LOG_LEVEL_SET: publish_data('log', { 'type': 'instance_log', 'instance_id': self.instance.pk, 'log_entry': str(self), })
def change_state(self, state, msg=""): self.state = state self.save() data_dict = {} if state == "lobby": msg = "waiting for more players. " + msg if state == "ready": msg = "publishing ready info. " + msg if state == "waiting": msg = "waiting for event. " + msg if state == "new_event": new_event = self.get_event_queue()[0] msg = "new event starting: " + new_event.e_type + ". " + msg data_dict["event"] = new_event.e_type if state == "voting": msg = "Waiting 10s to collect votes. " + msg cur_event = self.get_event_queue()[0] data_dict["subjects"] = [] for player in self.get_groups(cur_event.subjects): data_dict["subjects"].append(player.as_JSON()) data_dict["e_type"] = cur_event.e_type data_dict["channel"] = "event info" for p_id in cur_event.instigators: publish_data("player:"+p_id, data_dict) if state == "finished_voting": msg = "Votes collected, performing result" if state == "game_finished": msg = msg + "These guys won: " for group in self.get_winners(): msg = msg + group + ", " msg = "-------"+msg.upper()+"-------" log_type = "INFO" log_code = "Game" log_message = msg log_detail = 2 context_id = self.g_id log_handler.log(log_type=log_type, log_code=log_code, log_message=log_message, log_detail=log_detail, context_id=context_id)
def give_message(self, msg, sender, target, time): data_dict = {} channel = "player:"+self.p_id data_dict['message'] = msg data_dict['sender'] = sender data_dict['target'] = target data_dict['time'] = time data_dict['channel'] = channel data_dict['type'] = "message" publish_data(channel, data_dict) return data_dict
def create(self, **kwargs): initial = self.get_initial('create', **kwargs) self.serializer = self.serializer_class(data=kwargs, initial=initial) msg = UserMessage.objects.create( text=self.serializer.data['text'], user=self.connection.user, direction='from' ) publish_data('user-message-%s' % self.connection.user.pk, { 'text': msg.text, 'created_at': str(msg.created_at), 'direction': 'from' }) self.send('done')
def render_image(input_file, output_file, userid): """Renders the image with the given paths and calls callback on every update""" logger.info('Started task') proc = subprocess.Popen( [os.path.join(RENDERER_DIR, 'build/nori'), input_file, '0', '0', '1'], stdout=subprocess.PIPE) logger.info('Started render process') while True: # read output and send to websockets line = proc.stdout.readline() if line != b'': try: data = json.loads(line.decode('utf8')) return_object = { 'url': output_file, 'percentage': data['percentage'], 'x': data['x'], 'y': data['y'], 'width': data['width'], 'height': data['height'], 'data': data['data'], 'patchHeight': data['patchHeight'], 'patchWidth': data['patchWidth'], 'finished': False } publish_data(channel='update-msg'.format(userid), data=return_object) except json.JSONDecodeError as e: logger.debug('Error decoding json: {}\nInput: {}'. format(e, line)) else: break logger.info('Finished Task') return_object = { 'url': output_file, 'percentage': 100, 'finished': True } publish_data(channel='update-msg'.format(userid), data=return_object) os.remove(input_file)
def broadcast_sys_info(): global pcb if pcb is None: pcb = PeriodicCallback(broadcast_sys_info, 500) pcb.start() cpu = psutil.cpu_percent() net = psutil.net_io_counters() bytes_sent = '{0:.2f} kb'.format(net.bytes_recv / 1024) bytes_rcvd = '{0:.2f} kb'.format(net.bytes_sent / 1024) publish_data('sysinfo', { 'cpu': cpu, 'kb_received': bytes_sent, 'kb_sent': bytes_rcvd, })
def save(self): ww_redis_db.hset("g_list:"+self.g_id, "name", self.name) ww_redis_db.hset("g_list:"+self.g_id, "g_round", self.g_round) ww_redis_db.hset("g_list:"+self.g_id, "state", self.state) ww_redis_db.hset("g_list:"+self.g_id, "max_players", str(self.max_players)) ww_redis_db.hset("g_list:"+self.g_id, "witch_enabled", str(self.witch_enabled)) ww_redis_db.hset("g_list:"+self.g_id, "mystic_enabled", str(self.mystic_enabled)) players_string = cur_events_string = old_events_string = "" if self.players: players_string = "|".join(self.players) ww_redis_db.hset("g_list:"+self.g_id, "players", players_string) if self.event_queue: cur_events_string = "|".join(self.event_queue) ww_redis_db.hset("g_list:"+self.g_id, "event_queue", cur_events_string) if self.event_history: old_events_string = "|".join(self.event_history) ww_redis_db.hset("g_list:"+self.g_id, "event_history", old_events_string) if hasattr(self, 'redis_cleanup_callback_reference'): if self.redis_cleanup_callback_reference is not None: ww_redis_db.hset("g_list:"+self.g_id, "redis_cleanup_callback_reference", self.redis_cleanup_callback_reference) games_dict = {} data_dict = {} games_dict["json"] = self.as_JSON() data_dict["game"] = games_dict data_dict["channel"] = "game:"+self.g_id publish_data("game:"+self.g_id, data_dict) self.saved = True log_type = "INFO" log_code = "Memory" log_message = "Game has been saved." log_detail = 2 context_id = self.g_id log_handler.log(log_type=log_type, log_code=log_code, log_message=log_message, log_detail=log_detail, context_id=context_id)
def send_command(self, comment, command=None, player=None): # self.position[0] += 1 # self.position[1] += 1 print(self.position) self.comments.append(comment) self.last_comments.append(comment) print(self.last_command_timestamp[0]) now_timestamp = time.time() * 1000 if not self.last_command_timestamp[0]: self.last_command_timestamp[0] = now_timestamp print(now_timestamp, self.last_command_timestamp[0], (now_timestamp - self.last_command_timestamp[0])) if command and ((now_timestamp - self.last_command_timestamp[0]) > 1500): print("triggered!") self.last_command_timestamp[0] = now_timestamp self.move_player(command) direction = direction_map[command] publish_data("global", { 'type': "move", 'position': self.position, 'direction': direction }) self.send({ 'position': self.position, 'last_comment': comment, 'last_command': command }) publish_data("global", { "type": "comment", 'position': self.position, 'comment': comment, 'command': command, "player": player })
def push_message(self, **kwargs): data_dict = {} channel = "" if 'msg' not in kwargs or 'groups' not in kwargs: return if ('game' in kwargs['groups'] and 'g_id' in self.session and 'location' in self.session and self.session['location'] == "ingame"): channel = 'game:' + self.session['g_id'] elif 'player' in kwargs['groups'] and 'p_id' in kwargs: channel = 'player:' + kwargs['p_id'] data_dict['message'] = kwargs['msg'] data_dict['channel'] = channel publish_data(channel, data_dict) return data_dict
def save(self, *args, **kwargs): """ Save this OpenEdXAppServer """ # Always override configuration_settings - it's not meant to be manually set. We can't # assert that it isn't set because if a ValidationError occurred, this method could be # called multiple times before this AppServer is successfully created. if not self.pk: self.configuration_settings = self.create_configuration_settings() super().save(*args, **kwargs) # Notify anyone monitoring for changes via swampdragon/websockets: publish_data( 'notification', { 'type': 'openedx_appserver_update', 'appserver_id': self.pk, 'instance_id': self.owner.pk, # This is the ID of the InstanceReference })
def publish_search_status(search_result): status = {} searches = cache.keys('search.*') for key in searches: sid = int(key.split('.')[-1]) value = cache.hgetall(key) status[sid] = {} status[sid]['to_process'] = value.get('to_process', 0) status[sid]['processed'] = value.get('processed', 0) if (status[sid]['to_process'] == status[sid]['processed'] and status[sid]['to_process'] and status[sid]['processed']): s = Search.objects.get(pk=sid) s = Search.objects.get(pk=sid) s.status = 2 # mark status as done s.save() cache.delete(key) channel = 'project_%s_search' % search_result.search.project.id print channel, status publish_data(channel, status) return status
def push_message(self, **kwargs): data_dict = {} channel = "" if 'msg' not in kwargs or 'groups' not in kwargs: return if ( 'game' in kwargs['groups'] and 'g_id' in self.session and 'location' in self.session and self.session['location'] == "ingame" ): channel = 'game:'+self.session['g_id'] elif 'player' in kwargs['groups'] and 'p_id' in kwargs: channel = 'player:'+kwargs['p_id'] data_dict['message'] = kwargs['msg'] data_dict['channel'] = channel publish_data(channel, data_dict) return data_dict
def broadcast_sys_info(): global pcb if pcb is None: pcb = PeriodicCallback(broadcast_sys_info, 500) pcb.start() cpu = psutil.cpu_percent() net = psutil.net_io_counters() mem = psutil.virtual_memory() pct_mem = mem.percent bytes_sent = '{0:.2f} kb'.format(net.bytes_sent / 1024) bytes_rcvd = '{0:.2f} kb'.format(net.bytes_recv / 1024) publish_data('sysinfo', { 'cpu': cpu, 'mem': pct_mem, 'kb_rcvd': bytes_sent, 'kb_sent': bytes_rcvd, })
def do_geo_search(id, address): try: set_lock('geo_lock') query = GeocodingTest() if get_lock('geo_lock') == False: obj = GeoSearch.objects.get( pk=id ) # due to async, we want to get latest copy of geosearch object fresh to avoid conflict results = query.simple_geocode(address) if results: result = results[0]["geometry"]["location"] obj.lat = result.get('lat') obj.lng = result.get('lng') obj.status = 'good' else: obj.status = 'bad' obj.save() # swampdragon, tell browser one item finishes c = 'project_%d_geo' % obj.project.id publish_data(c, {"good": 1}) except Exception, exc: raise do_geo_search.retry(exc=exc)
def broadcast_sys_info(): global pcb if pcb is None: pcb = PeriodicCallback(broadcast_sys_info, 900) pcb.start() danger = sapnode.objects.filter(status='danger').order_by('sid').values().distinct() danger_count=len(danger) warning = sapnode.objects.filter(status='warning').order_by('sid').values().distinct() warning_count=len(warning) instancias = sapnode.objects.filter().order_by('sid').values().distinct() instancias_count=len(instancias) instancias_abap = sapnode.objects.filter(product='abap').order_by('sid').values().distinct() instancias_abap_count=len(instancias_abap) instancias_portal = sapnode.objects.filter(product='portal').order_by('sid').values().distinct() instancias_portal_count=len(instancias_portal) instancias_javaengine = sapnode.objects.filter(product='java_engine').order_by('sid').values().distinct() instancias_javaengine_count=len(instancias_javaengine) instancias_opentext = sapnode.objects.filter(product='opentext').order_by('sid').values().distinct() instancias_opentext_count=len(instancias_opentext) publish_data('sysinfo', { 'danger_count':danger_count, 'warning_count': warning_count, 'instancias_count': instancias_count, 'instancias_abap_count':instancias_abap_count, 'instancias_portal_count':instancias_portal_count, 'instancias_javaengine_count':instancias_javaengine_count, 'instancias_opentext_count':instancias_opentext_count, })
def emit(self, record): """ Handles an emitted log entry and stores it in the database, optionally linking it to the model object `obj` """ obj = record.__dict__.get('obj', None) if obj is None or not isinstance(obj, models.Model) or obj.pk is None: content_type, object_id = None, None else: content_type = apps.get_model( 'contenttypes', 'ContentType').objects.get_for_model(obj) object_id = obj.pk try: log_entry = apps.get_model('instance', 'LogEntry').objects.create( level=record.levelname, text=self.format(record), content_type=content_type, object_id=object_id) except ProgrammingError: # This can occur if django tries to log something before migrations have created the log table. # Make sure that is actually what happened: assert 'instance_logentry' not in connection.introspection.table_names( ) # Send notice of entries related to any resource. Skip generic log entries that occur # in debug mode, like "GET /static/img/favicon/favicon-96x96.png": if content_type: log_event = { 'type': 'object_log_line', 'log_entry': LogEntrySerializer(log_entry).data } if hasattr(obj, 'event_context'): log_event.update(obj.event_context) # TODO: Filter out log entries for which the user doesn't have view rights # TODO: More targetted events - only emit events for what the user is looking at publish_data('log', log_event)
def process_file(self, content): lines = content.split('\n') line_count = len(lines) for i, line in enumerate(lines): time.sleep(0.1) status_data = { 'current': i, 'total': line_count } if not self.request.called_directly: self.update_state( state='PROGRESS', meta=status_data ) # Swampdragon channel_data = status_data.copy() channel_data['status'] = 'PROGRESS' publish_data('upload_status', channel_data) return True
def emit(self, record): """ Handles an emitted log entry and stores it in the database, optionally linking it to the model object `obj` """ obj = record.__dict__.get('obj', None) if obj is None or not isinstance(obj, models.Model) or obj.pk is None: log_entry_set = apps.get_model('instance', 'GeneralLogEntry').objects else: log_entry_set = obj.log_entry_set log_entry = log_entry_set.create(level=record.levelname, text=self.format(record)) log_event = { 'type': 'instance_log', 'log_entry': LogEntrySerializer(log_entry).data } if hasattr(obj, 'event_context'): log_event.update(obj.event_context) # TODO: Filter out log entries for which the user doesn't have view rights publish_data('log', log_event)
def send_build_change(build): template = get_template("partials/build_list_row.html") row_html = template.render({'build': build}) publish_data('all-build-change', {'id': build.id, 'row_html': row_html}) publish_data('{}-build-change'.format(build.project.id), {'id': build.id, 'row_html': row_html}) template = get_template("partials/build_detail_header.html") details_html = template.render({'build': build}) publish_data('build-change-{}'.format(build.id), {'id': build.id, 'details_html': details_html})
def broadcast_sys_info(): global pcb if pcb is None: pcb = PeriodicCallback(broadcast_sys_info, 500) pcb.start() cpu = psutil.cpu_percent() net = psutil.net_io_counters() bytes_sent = '{0:.2f} kb'.format(net.bytes_recv / 1024) bytes_rcvd = '{0:.2f} kb'.format(net.bytes_sent / 1024) publish_data('sysinfo_sent', { 'kb_received': bytes_sent, }) publish_data('sysinfo_rec', { 'kb_sent': bytes_rcvd, }) publish_data('sysinfo_cpu', { 'cpu': cpu, })
def notify_user_of_a_call(user_id): channel = 'user_{}'.format(user_id) publish_data(channel=channel, {'message': 'Incoming call'})
def publish_online_users(): data = { 'users_online': user_count(), } publish_data(channel='sd_online_users', data=data)
def test_publish_string(self): publish_data('foo-chan', 'hello') self.assertEqual(self.connection.last_pub['data'], 'hello')
def test_publish_dict(self): publish_data('foo-chan', {'key': 'value'}) self.assertEqual(self.connection.last_pub['data']['key'], 'value')
def mytask(): print("123") f = open('/Users/johnnytsai/PythonProjects/Python-Django-AdminLTE2/SwampdragonTest/console.txt', 'a') f.write("123") data = {'name': 'name', 'message': 'message'} publish_data(channel='chatroom', data=data)
def publish_online_users(self): data = {'users_online': self.get_users()} publish_data(channel='online_users', data=data)
def notify_user_of_a_call(user_id): channel = 'user_{}'.format(user_id) publish_data(channel=channel, {'message': 'Incoming call'})