def old_listen_and_replay_to_redis(): TCP_IP = '127.0.0.1' TCP_PORT = 5555 BUFFER_SIZE = 1024 redis_publisher = RedisPublisher(facility='foobar', broadcast=True) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((TCP_IP, TCP_PORT)) s.listen(1) while True: conn, addr = s.accept() print 'Connection address:', addr data = conn.recv(BUFFER_SIZE) if not data: continue try: redis_publisher.publish_message(RedisMessage(data)) except Exception as e: print "could not publish in redis because %s" % e conn.send("Thank you for your message. Bye.\n") conn.close()
def heartbeat(self,websocketmsg): try: zom = Zombie.objects.get(host=websocketmsg.ip) redis_publisher = RedisPublisher(facility='attacker',sessions=[atkr.sesskey for atkr in Attacker.objects.all()]) redis_publisher.publish_message(RedisMessage(simplejson.dumps({'new':'new','newzombieId':zom.pk,'newzombieHost':zom.host}))) except Exception: pass
def display(msg, task_id, color=None, stderr=False, screen_only=False, log_only=False, runner=None): # prevent a very rare case of interlaced multiprocess I/O log_flock(runner) while msg.startswith("\n"): msg = msg.replace("\n", "") msg2 = msg + '\n' if color: msg2 = stringc(msg, color) + '\n' logger.debug('TASK_ID: {task_id} | MSG: {message}'.format(task_id=task_id, message=msg2)) # Pusblish the message on websocket redis_publisher = RedisPublisher(facility=task_id, broadcast=True) redis_message = RedisMessage(msg2) redis_publisher.publish_message(message=redis_message) # Store the message into a redis list to let the user get all # history of the logs redis_connection.rpush('tasks:' + task_id, msg2) # reset the expire of the list if settings.WS4REDIS_EXPIRE: if settings.WS4REDIS_EXPIRE > 0: redis_connection.expire('tasks:' + task_id, settings.WS4REDIS_EXPIRE) log_unflock(runner)
def stk_push(phone_number, price, first_name, last_name, user_name): push_url = 'http://pay.brandfi.co.ke:8301/api/stkpush' push_params = { "clientId": "2", "transactionType": "CustomerPayBillOnline", "phoneNumber": phone_number, "amount": "1", "callbackUrl": "http://pay.brandfi.co.ke/payfi-success", "accountReference": "demo", "transactionDesc": "Test" } headers = {'Content-type': 'application/json'} r = requests.post(push_url, json=push_params, headers=headers) parsed_json = json.loads(r.text) checkoutRequestId = parsed_json['CheckoutRequestID'] mobile_number = phone_number.replace("254", "0") stk_push_query = STKPushQuery( checkoutRequestId, mobile_number, first_name, last_name, user_name) """Example of how to send server generated events to clients.""" while not stk_push_query.is_result: stk_push_query.push_query() redis_publisher = RedisPublisher(facility='foobar', broadcast=True) message = RedisMessage(stk_push_query.result) redis_publisher.publish_message(message) if(stk_push_query.is_result): break
def test_defining_multiple_publishers(self): pub1 = RedisPublisher(facility=self.facility, broadcast=True) self.assertEqual(pub1._publishers, set([self.prefix + ':broadcast:' + self.facility])) pub2 = RedisPublisher(facility=self.facility, users=['john']) self.assertEqual(pub2._publishers, set([self.prefix + ':user:john:' + self.facility]))
def send_message(self, game, message): facility = 'notify-%s' % game.slug self.stdout.write(' Sending %s [facility=%s]' % (message, facility)) redis_publisher = RedisPublisher(facility=facility, broadcast=True) redis_publisher.publish_message(RedisMessage(message))
def dumpTargetData(self, request, pk=None): connectionCheck() ids = json.loads(request.data['ids']) data = '' count = 1 for pk in ids: try: target = Target.objects.get(pk=pk) target.wasSent() data += str(count) + '\t' + str(target.ptype) + '\t' + str( target.latitude ) + '\t' + str( target.longitude ) + '\t' + target.orientation + '\t' + target.shape + '\t' + target.background_color + '\t' + target.alphanumeric + '\t' + target.alphanumeric_color + '\t' + target.picture.url + '\n' count += 1 except Target.DoesNotExist: continue # websocket response for "sent" redis_publisher = RedisPublisher(facility='viewer', sessions=gcsSessions()) redis_publisher.publish_message( RedisMessage(json.dumps({ 'target': 'sent', 'ids': ids }))) return Response({'data': data})
def catch(self, request, format='xml'): ''' Deals with the incoming payload, Creates a new message object connected to the Contact ''' message = str(request.data['Body']) to_number = request.data['From'] contact = Contact.objects.filter(phone_number=to_number).first() if not contact: print "Unknown contact messaging you" contact = Contact.objects.create( first_name='Unknown', last_name='', phone_number=to_number ) new_message = Message.objects.create( text=message, contact=contact, ) message_serialized = serialize(MessageSerializer(new_message)) redis_publisher = RedisPublisher(facility='akalite', broadcast=True) web_message = RedisMessage(message_serialized) redis_publisher.publish_message(web_message) print('Message successfuly caught.') resp = twilio.twiml.Response() resp.message("Caught") return Response(None)
def listen_and_replay_to_redis(self): logger = logging.getLogger("django") tid = random.randint(1, 1000) logger.debug(" >> [%s] websocket starting thread" % tid) try: redis_publisher = RedisPublisher(facility='foobar', broadcast=True) while True: data = str(uuid.uuid4()) #self.counter += 1 #data = "%s - %s" % (data, self.counter) redis_publisher.publish_message(RedisMessage(data)) ttw = random.uniform(3, 10) logger.debug(" >> [%s] websocket thread %s: %s waiting %s seconds" % (tid, datetime.now().strftime("%H:%M:%S"), data, ttw)) time.sleep(ttw) except Exception as e: logger.debug(" >> [%s] websocket thread error: %s" % (tid,e)) logger.debug(" >> [%s] websocket thread dying" % tid)
def connectionCheck(): if cache.has_key("checkallowed"): if not cache.has_key("android"): redis_publisher = RedisPublisher(facility='viewer',sessions=gcsSessions()) redis_publisher.publish_message(RedisMessage(json.dumps({'disconnected':'disconnected'}))) cache.delete("checkallowed")
def redisPublishMessage(msj): redis_publisher = RedisPublisher(facility='foobar', broadcast=True) message = RedisMessage(msj) redis_publisher.publish_message(message)
def handle(self, *args, **options): welcome = RedisMessage('Hello everybody') print "begin update unit pos" redis_publisher=RedisPublisher(facility='units_updated', users=[x for x in User.objects.all()]) while True: sleep(1) start=clock() #self.stdout.write( "ruslix " ) try: cursor = connection.cursor() cursor.execute('begin') cursor.execute('LOCK TABLE game_unit') #cursor.fetchone() d=datetime.now() t=unit.objects.filter(in_move__lte=d) for i in t: i.in_move=None i.save() found_combat(i) """for ii in neighbor: print ii.user.user," lalala3 ",i.user.user """ redis_publisher=RedisPublisher(facility='units_updated', users=[i.user.user,]) welcome = RedisMessage("unit moved "+str(i.pk)) redis_publisher.publish_message(welcome) print i.pk,i.in_move,i.user finally: cursor.execute('commit')
def lanzafinllamada(request, base, agente): if Agente.objects.filter(anexo=int(agente)).count() > 1: a = simplejson.dumps('Existe muchos agentes agente con el anexo ' + agente) return HttpResponse(a, content_type="application/json") if Agente.objects.filter(anexo=int(agente)).count() == 0: a = simplejson.dumps('No existe el agente con anexo ' + agente) return HttpResponse(a, content_type="application/json") _agente = Agente.objects.get(anexo=int(agente)) _agente.estado_id = 3 _agente.id_estado = 4 _agente.save() redis_publisher = RedisPublisher( facility='foobar', users=[_agente.user.username, 'edeamat', 'scondezo']) message = RedisMessage('llamada-' + str(base)) redis_publisher.publish_message(message) a = simplejson.dumps('Se lanzo FIN llamada al agente con el anexo ' + agente) return HttpResponse(a, content_type="application/json")
def gdelete(request): groupname = request.POST.get('name', 0) rd = StrictRedis() pref = settings.MY_PREFIX prefg = pref + ":" + groupname user = str(request.user) print "received request for deleting", groupname, "from", user ismember = rd.sismember(pref + ":groups", groupname) if not ismember: return JsonResponse({ 'done': False, 'reason': 'No such group name' }) # now check whether the requesting user is the one who created the group d = rd.hgetall(prefg + ":hash") if d['owner'] != user: return JsonResponse({ 'done': False, 'reason': 'Only group owner can delete the group' }) rd.srem(pref + ":groups", groupname) rd.delete(prefg + ":hash", pref + ":" + groupname) rd.delete(pref + ":" + groupname) redis_publisher = RedisPublisher(facility=pref, broadcast=True) redis_publisher.publish_message( RedisMessage(json.dumps({ "type": "group_delete", "name": groupname }))) return JsonResponse({'done': True})
def interop_error_handler(error): code,reason,text = error.errorData() #response to client accordingly #but keep going...if something fails, respond and ignore it #alert mission planner about the error though if code == 400: return Response({'time':time()-startTime,'error':"WARNING: Invalid telemetry data. Skipping"}) elif code == 404: return Response({'time':time()-startTime,'error':"WARNING: Server might be down"}) elif code == 405 or code == 500: return Response({'time':time()-startTime,'error':"WARNING: Interop Internal Server Error"}) #EXCEPT FOR THIS elif code == 403: creds = cache.get("Creds") times = 5 for i in xrange(0,times): try: interop_login(username=creds['username'],password=creds['password'],server=creds['server'],tout=5) return Response({'time':time()-startTime,'error':"Had to relogin in. Succeeded"}) except Exception as e: sleep(2) continue code,_,__ = e.errorData() #Everyone should be alerted of this resp = {'time':time()-startTime,'error':"CRITICAL: Re-login has Failed. We will login again when allowed\nLast Error was %d" % code} redis_publisher = RedisPublisher(facility='viewer',sessions=gcsSessions()) redis_publisher.publish_message(RedisMessage(json.dumps({'warning':resp}))) return Response(resp)
def get(self, request, *args, **kwargs): game_name = self.kwargs.get('game_name') context = RequestContext(request) moves = cache.get("game."+game_name) variables = {'moves': moves} game = (TicTacGameSession.objects.filter(name=game_name) or [None])[0] if game is None or (game.user != request.user and game.user2 is not None and game.user2 != request.user) or game.state == "over": return HttpResponseRedirect('/room_list/') if game.user != request.user and game.user2 is None: game.user2 = request.user game.state = "playing" game.save() redis_publisher = RedisPublisher(facility='foobar', users=[game.user]) message = RedisMessage("start") redis_publisher.publish_message(message) redis_publisher.publish_message(RedisMessage("")) variables['my_turn'] = False variables['joined'] = True # kela elif game.user2 is None: variables['my_turn'] = True variables['joined'] = False else: variables['my_turn'] = False variables['joined'] = True variables['first_player'] = game.user == request.user variables['game_name'] = game_name # variables['second_player'] print variables return render_to_response('tictac.html', variables, context_instance=context)
def ws_call(signal_name, request, sharing, kwargs): """ Call a JS signal from the Python side. :param signal_name: name of signal :type signal_name: :param request: a SignalRequest with session_key and username :type request: :class:`djangofloor.decorators.SignalRequest` :param sharing: the required sharing. Can be SESSION, USER or BROADCAST or any dict which is valid for django-websockets-redis. :type sharing: :param kwargs: options to pass to the JS signal :type kwargs: :return: `None` """ if isinstance(sharing, binary_type): sharing = force_text(sharing) if sharing == SESSION: sharing = {SESSION: [request.session_key, ]} elif sharing == USER: sharing = {USER: [request.username, ]} elif sharing == BROADCAST: sharing = {BROADCAST: True} if BROADCAST in sharing: sharing[BROADCAST] = True redis_publisher = RedisPublisher(facility=settings.FLOOR_WS_FACILITY, **sharing) msg = json.dumps({'signal': signal_name, 'options': kwargs}, cls=get_signal_encoder()) redis_publisher.publish_message(RedisMessage(msg.encode('utf-8')))
def targetCreate(self,request,pk=None): #pdb.set_trace() connectionCheck() if not "scaleWidth" in request.data or int(request.data['scaleWidth'])==0 : return HttpResponseForbidden("No crop given!") if not "width" in request.data or int(request.data['width']) == 0: return HttpResponseForbidden("No crop given!") if not "height" in request.data or int(request.data['height']) ==0: return HttpResponseForbidden("No crop given!") try: picture = Picture.objects.get(pk=request.data['pk']) except Picture.DoesNotExist: return HttpResponseForbidden() target = TargetSerializer(data={key : (request.data[key] if key in request.data else None) for key in ('background_color','alphanumeric_color','orientation','shape','alphanumeric','ptype','description')}) if not target.is_valid(): return HttpResponseForbidden() sizeData = request.data target = target.deserialize() if target.background_color == "grey": target.background_color = "gray" if target.alphanumeric_color =="grey": target.alphanumeric_color = "gray" target.crop(size_data=sizeData,parent_pic=picture) target.save() redis_publisher = RedisPublisher(facility='viewer',sessions=gcsSessions()) redis_publisher.publish_message(RedisMessage(json.dumps({'target':'create','pk':target.pk,'image':TARGET+"/Target"+str(target.pk).zfill(4)+'.jpeg'}))) return Response("success")
def group_post(request): redis_publisher = RedisPublisher(facility='myg', groups=request.POST.get('group')) msg = request.POST.get('message') message = RedisMessage(request.POST.get('user') + ": " + msg) redis_publisher.publish_message(message) return HttpResponse('OK')
def select(request): track_ids = request.POST.getlist('track_ids') if track_ids: new_track = False for id in track_ids: selected = Track.objects.get(id=id) print 'selected:', selected try: position = PlaylistItem.objects.latest().position + 1 except PlaylistItem.DoesNotExist: position = 0 new_track = True print 'position:', position PlaylistItem(track=selected, position=position).save() else: print 'playlist:', [str(i.track) for i in PlaylistItem.objects.all()] publisher = RedisPublisher(facility='main', broadcast=True) message = json.dumps({'notification': 'playlist_updated'}) publisher.publish_message(RedisMessage(message)) if new_track: track = get_current_track() if track: if not track.file: request_track_file(track, request) else: notify_track_available(track) return HttpResponseRedirect(reverse('playlist')) return render(request, 'playlistq/album.html', { 'error_message': "You didn't select a track.", })
def notify_user(user_names: List[str], content: dict): try: redis_publisher = RedisPublisher(facility=settings.FACILITY_WS4REDIS, broadcast=False, users=user_names) message = RedisMessage(json.dumps(content)) redis_publisher.publish_message(message) except: logging.exception('Error while sending notification to users "%s"', user_names)
def detalle_venta(request, id_produccion): if request.method == 'POST': instance = Produccion() telefono = request.POST['telefono_1'] instance = Produccion.objects.get(id=id_produccion) form = ProduccionForm(request.POST or None, instance=instance) if form.is_valid(): form.save() redis_publisher = RedisPublisher(facility='foobar', users=[request.user.username]) message = RedisMessage('llamada-' + str(telefono)) redis_publisher.publish_message(message) return render(request, 'colasIN/exito.html', {}) if request.method == 'GET': incidencia = Produccion.objects.get(id=id_produccion) incidenciaform = ProduccionForm(instance=incidencia) return render(request, 'colasIN/detalle_venta.html', { 'incidenciaform': incidenciaform, 'incidencia': incidencia })
def library(request): if request.method == 'POST': library = json.loads(request.body.decode(encoding='utf-8')) print library for artist_title, artist_attrs in library.items(): print('Adding artist:', artist_title) artist, created = Artist.objects.get_or_create(title=artist_title) for album_title, album_attrs in artist_attrs.items(): print('Adding album:', album_title) album, created = Album.objects.get_or_create(title=album_title, artist=artist) for track_title, track_attrs in album_attrs.items(): print('Adding track:', track_title) track, created = Track.objects.get_or_create( title=track_title, artist=artist, album=album, defaults={'session': request.session.session_key}) print() publisher = RedisPublisher(facility='main', broadcast=True) message = json.dumps({'notification': 'library_updated'}) publisher.publish_message(RedisMessage(message)) return HttpResponse('OK') else: artists = Artist.objects.all() context = {'artists': artists} context.update(csrf(request)) return render(request, 'playlistq/library.html', context)
class MessageService(object): """Service to handle messages, including local logging and publishing using Redis. """ def __init__(self): self._redis_publisher = RedisPublisher( facility=settings.REDIS_PUBLISHER_FACILITY_LABEL, broadcast=True) self._log_lines = [] def publish_message(self, line, **kwargs): """Publishes a messages using Redis. This line is sent to the web. The line could be an empty string """ # Line could be an empty string: in case we need to inform # some situation to the web tier, we send a dict with flags, # but we don't want to send a log line. if line: self._log_lines.append(line) message_dict = {'line': line} message_dict.update(kwargs) self._redis_publisher.publish_message( RedisMessage(json.dumps(message_dict))) def log_and_publish(self, message, *args, **kwargs): """Log a line using and publish it to the web tier. The *args are passed to logger.info() The **kwargs are passed to '_send_line()' """ logger.info(message, *args) record = LogRecord('name', logging.INFO, "(unknown file)", 0, message, args, exc_info=None, func=None) full_message = record.getMessage() self.publish_message(line=full_message, **kwargs) # self._log_lines.append(message) def log_and_publish_error(self, message, *args, **kwargs): """Log a line using and send it to the web tier. The *args are passed to logger.info() The **kwargs are passed to '_send_line()' """ logger.error(message, *args) record = LogRecord('name', logging.ERROR, "(unknown file)", 0, message, args, exc_info=None, func=None) full_message = record.getMessage() updated_kwargs = dict(kwargs) updated_kwargs['errorLine'] = True self.publish_message(line=full_message, **updated_kwargs) # self._log_lines.append(message) def get_log(self): """Returns the saved log lines as a single string""" return "\n".join(self._log_lines)
def post(self, request, *args, **kwargs): print request.POST redis_publisher = RedisPublisher(facility='foobar', users=[request.POST.get('user')]) print redis_publisher message = RedisMessage(request.POST.get('message')) print message redis_publisher.publish_message(message) return HttpResponse('OK')
def broadcast_post(request): redis_publisher = RedisPublisher(facility='foobar', broadcast=True) msg = request.POST.get('message') rip = request.META['REMOTE_ADDR'] message = RedisMessage(rip + ': ' + msg) print msg, ' from ', rip redis_publisher.publish_message(message) return HttpResponse('OK')
def send_capture(player1, player2, pos): redis_publisher = RedisPublisher(facility='game_move', users=[player1.user.username, player2.user.username]) message = {} message['capture'] = True message['pos'] = pos message = RedisMessage(json.dumps(message)) redis_publisher.publish_message(message)
def send_move_update(player, move): redis_publisher = RedisPublisher(facility='game_move', users=[player.user.username]) message = {} message['move'] = move message['capture'] = False message = RedisMessage(json.dumps(message)) redis_publisher.publish_message(message)
def broadcast_post(request): redis_publisher = RedisPublisher(facility='foobar', broadcast = True) msg = request.POST.get('message') rip = request.META['REMOTE_ADDR'] message = RedisMessage(rip+': '+msg) print msg,' from ',rip redis_publisher.publish_message(message) return HttpResponse('OK')
def publish(serializer, category, request): message = {} redis_publisher = RedisPublisher(facility="pushes", broadcast=True) existing_message = redis_publisher.fetch_message(request, "pushes") if existing_message: message = json.loads(existing_message) message[category] = serializer.data redis_publisher.publish_message(RedisMessage(json.dumps(message)))
def notify_file_ready(args): sess, msg = args # simulate hard work time.sleep(1) redis_publisher = RedisPublisher(facility='comm', sessions=[sess]) message = RedisMessage(msg) redis_publisher.publish_message(message) return msg
def sync(self, request): # Sample code for reading incidents message queue redis_publisher = RedisPublisher(facility='pushes', broadcast=True) message = redis_publisher.fetch_message(request, facility='pushes') # if the message is empty, replace it with a empty json/dict and convert to a string if not message: message = json.dumps({}) return Response(json.loads(message))
def create_notification(assignee, task_title): task = Task.objects.get(title=task_title) user = User.objects.get(pk=assignee) if task: notify = Notification.objects.create(assigned_to=user, notify=task) redis_publisher = RedisPublisher(facility="foobar", broadcast=True) message = RedisMessage("new") redis_publisher.publish_message(message) return True
def send_message(player1, player2, msg): redis_publisher = RedisPublisher(facility='chat', users=[player1.user.username, player2.user.username]) message = {} message['name'] = msg.user.username message['text'] = msg.text message['time'] = str(msg.time) message = RedisMessage(json.dumps(message)) redis_publisher.publish_message(message)
def publishMessage(topic, message="update", groups=[]): if not groups: redis_publisher = RedisPublisher(facility=topic, broadcast=True) else: redis_publisher = RedisPublisher(facility=topic, groups=groups) message = RedisMessage(message) redis_publisher.publish_message(message)
def connectionCheck(): if cache.has_key("checkallowed"): if not cache.has_key("android"): redis_publisher = RedisPublisher(facility='viewer', sessions=gcsSessions()) redis_publisher.publish_message( RedisMessage(json.dumps({'disconnected': 'disconnected'}))) cache.delete("checkallowed")
def notify_track_available(track): print 'Notify availability:', track message = {'notification': 'track_available', 'artist': str(track.artist), 'album': str(track.album), 'track': str(track), 'url': track.url} publisher = RedisPublisher(facility='main', broadcast=True) publisher.publish_message(RedisMessage(json.dumps(message)))
def __init__(self): self.delta = 0 self.laps = {"hour": 24, "minute": 60, "second": 60} self.sch = BackgroundScheduler(timezone=utc) self.sch.start() now = datetime.datetime.now() then = now + datetime.timedelta(seconds=(70 - now.second)) self.sch.add_job(self.new_minute, 'date', run_date=then) self.redis_publisher = RedisPublisher(facility="pclock", broadcast=True)
def speak_message(self, text): """Places a speech in the redis pub-sub message queue identified by this Nabaztag's identifier. :param text: The text to send to the text-to-speech service. """ connection = RedisPublisher(facility=self.id, broadcast=True) message = {'speak': 1, 'text': text} connection.publish_message(json.dumps(message))
def notify_refresh_user(id, name): redis_publisher = RedisPublisher(facility='talk', broadcast=True) message = RedisMessage( json.dumps({ 'op': 'notify_refresh_user', 'id': id, 'name': name })) redis_publisher.publish_message(message) return {'status': 'success'}
def on_userlist_change(sender, **kwargs): from .rest import UserViewSet redis_publisher = RedisPublisher(facility='foobar', broadcast=True) # a bit of a kludge, but doing so we easily send the list in the exact same format for convenience user_view_set = UserViewSet() user_list = user_view_set.serializer_class(User.objects.all(), many=True).data json = encoders.JSONEncoder().encode(user_list) redis_publisher.publish_message(RedisMessage(json))
def UpdateDoc(self, row_data, user): err = {"error": "Input Validation Failed"} if not ValidateUserInput(row_data['comment']).ValidateInputMixed(): return err query = { "doc": { "Record": { "Comment": { "Date": str(datetime.datetime.utcnow()), "Analyst": str(user), "Comment": row_data['comment'] }, "Tag": update_control.TagIntToStr(row_data['tag']) } } } try: r = requests.post(self.es_host + ":" + self.es_port + self.index + self.type_audit_type + '/{0}/_update?parent={1}'.format( row_data['rowId'], row_data['parent']), data=json.dumps(query), auth=(self.elastic_user, self.elastic_pass), verify=False) except ConnectionError as e: ret = {"connection_error": e.args[0]} return ret try: q = requests.get(self.es_host + ":" + self.es_port + self.index + self.type_audit_type + "/{0}?parent={1}".format( row_data['rowId'], row_data['parent']), auth=(self.elastic_user, self.elastic_pass), verify=False) case = q.json()['_source']['CaseInfo']['case_name'] except ConnectionError as e: _ret = {"connection_error": e.args[0]} return _ret redis_publisher = RedisPublisher(facility='comments', broadcast=True) broadcast_comment = { "comment": row_data['comment'], "endpoint": row_data['parent'], "case": case, "analyst": str(user) } redis_publisher.publish_message( RedisMessage(json.dumps(broadcast_comment))) return r.json()
def interop_error_handler(error, startTime): code, reason, text = error.errorData() #response to client accordingly #but keep going...if something fails, respond and ignore it #alert mission planner about the error though if code == 400: return Response({ 'time': time() - startTime, 'error': "WARNING: Invalid telemetry data. Skipping" }) elif code == 404: return Response({ 'time': time() - startTime, 'error': "WARNING: Server might be down" }) elif code == 405 or code == 500: return Response({ 'time': time() - startTime, 'error': "WARNING: Interop Internal Server Error" }) #EXCEPT FOR THIS elif code == 403: creds = cache.get("Creds") times = 5 for i in xrange(0, times): try: interop_login(username=creds['username'], password=creds['password'], server=creds['server'], tout=5) return Response({ 'time': time() - startTime, 'error': "Had to relogin in. Succeeded" }) except Exception as e: sleep(2) continue code, _, __ = e.errorData() #Everyone should be alerted of this resp = { 'time': time() - startTime, 'error': "CRITICAL: Re-login has Failed. We will login again when allowed\nLast Error was %d" % code } redis_publisher = RedisPublisher(facility='viewer', sessions=gcsSessions()) redis_publisher.publish_message( RedisMessage(json.dumps({'warning': resp}))) return Response(resp)
def register(self,websocketmsg): try: zom = Zombie.objects.get(host=websocketmsg.ip) if(zom.facility != websocketmsg.message['facility']): zom.facility = websocketmsg.message['facility'] zom.save() except Zombie.DoesNotExist: newZombie = Zombie.objects.create(host=websocketmsg.ip,facility=websocketmsg.get()['facility']) #tell attacker new zombie added redis_publisher = RedisPublisher(facility='attacker',sessions=[ atkr.sesskey for atkr in Attacker.objects.all()]) redis_publisher.publish_message(RedisMessage(simplejson.dumps({'new':'new','newzombieId':newZombie.pk,'newzombieHost':newZombie.host})))
def test_subscribe_broadcast(self): audience = {'broadcast': True} publisher = RedisPublisher(facility=self.facility, **audience) publisher.publish_message(self.message, 10) websocket_url = self.websocket_base_url + u'?subscribe-broadcast' ws = create_connection(websocket_url) self.assertTrue(ws.connected) result = ws.recv() self.assertEqual(result, self.message) ws.close() self.assertFalse(ws.connected)
def request_track_file(track, request): print 'Request file:', track print 'Session:', track.session message = {'notification': 'file_requested', 'artist': str(track.artist), 'album': str(track.album), 'track': str(track), 'id': track.id} publisher = RedisPublisher(facility='main', sessions=[track.session]) publisher.publish_message(RedisMessage(json.dumps(message)))
def change_led(self, led, color): """Places an LED message in the redis pub-sub message queue identified by this Nabaztag's identifier. :param led: The led to change. :param color: A tuple containing RGB values for the colour to set, e.g. (255, 255, 255) """ connection = RedisPublisher(facility=self.id, broadcast=True) message = {'led': led, 'red': color[0], 'green': color[1], 'blue': color[2]} connection.publish_message(json.dumps(message))
def move_ear(self, ear, position): """Places an ear message in the redis pub-sub message queue identified by this Nabaztag's identifier. :param ear: The ear to move. :param position: The position to move it to. """ connection = RedisPublisher(facility=self.id, broadcast=True) message = {"ear": ear, "pos": position} connection.publish_message(json.dumps(message))
def update_stock(sender, instance, **kwargs): singals = type(instance).objects.filter(status='active') if instance.status != 'active': instance = False row = render_to_string('dashbord/includes/signal_dashbord.html', { 'active_singal': instance, 'signals': singals }) redis_publisher = RedisPublisher(facility='active_signal', broadcast=True) message = RedisMessage(row) redis_publisher.publish_message(message)
def send_chat_message(message): redis_publisher = RedisPublisher(facility='chat_message', users=[settings.ADMIN_ACCT, message.team.login_info.username]) packet = dict() packet['team_pk'] = message.team.pk packet['team_name'] = message.team.team_name packet['text'] = message.text packet['is_response'] = message.is_response df = DateFormat(message.time.astimezone(time_zone)) packet['time'] = df.format("h:i a") packet = RedisMessage(json.dumps(packet)) redis_publisher.publish_message(packet)
def process_workbook(self, filepaths): redis_publisher = RedisPublisher(facility='processing', **{'broadcast': True}) counter = 1 redis_data = { "total_rows": 0, "rows_processed": 0, "rows_ignored": 0, "jd_created": 0, "error": False, "error_message": "" } for filepath in filepaths: try: data = self.readxlsx(filepath) redis_data["total_rows"] += len(data) message = RedisMessage(json.dumps(redis_data)) redis_publisher.publish_message(message) from core.models import WorkBook for row in data: redis_data["rows_processed"] += 1 workbook, created = WorkBook.objects.get_or_create( id=row['ID']) if not created: redis_data["rows_ignored"] += 1 else: redis_data['jd_created'] += 1 workbook.role = row['Role'] workbook.level = row['Level'] workbook.primary_skill = row['Primary Skill'] workbook.secondary_skill = row['Secondary Skill'] workbook.description = row['Description'] workbook.save() message = RedisMessage(json.dumps(redis_data)) redis_publisher.publish_message(message) counter += 1 except KeyError: redis_data['error'] = True redis_data[ 'error_message'] = "Some fields are missing in file %s<br>" % filepath.replace( 'media/', '') # noqa message = RedisMessage(json.dumps(redis_data)) redis_publisher.publish_message(message) continue except xlrd.XLRDError: redis_data['error'] = True redis_data[ 'error_message'] += "Invalid File Provided %s<br>" % filepath.replace( 'media/', '') # noqa message = RedisMessage(json.dumps(redis_data)) redis_publisher.publish_message(message) continue
def test_publish_broadcast(self): websocket_url = self.websocket_base_url + u'?publish-broadcast' ws = create_connection(websocket_url) self.assertTrue(ws.connected) ws.send(self.message) ws.close() self.assertFalse(ws.connected) publisher = RedisPublisher() request = self.factory.get('/chat/') result = publisher.fetch_message(request, self.facility, 'broadcast') self.assertEqual(result, self.message) # now access Redis store directly self.assertEqual(publisher._connection.get(self.prefix + ':broadcast:' + self.facility), self.message)
def web_sockets_broadcast(request, message): if not settings.USE_WEBSOCKETS: return HttpResponse('Websockets not enabled in bootstrap.py') try: from ws4redis.publisher import RedisPublisher from ws4redis.redis_store import RedisMessage except ImportError: return HttpResponse('Websockets package ws4redis not installed') redis_publisher = RedisPublisher(facility='visual-translations-map', broadcast=True) message = RedisMessage(message) redis_publisher.publish_message(message) return HttpResponse("Broadcast: {}".format(message))
def create(self, request, *args, **kwargs): serializer = RedisMessageSerializer(data=request.data) provider = RedisProvider() conversation_key = provider.build_key('conversation', request.data['conversation']) conversation_raw = provider.get_list(conversation_key) if len(conversation_raw): recipients = ast.literal_eval(conversation_raw[0]) if request.user.username not in recipients or request.data[ 'recipient'] not in recipients: raise serializers.ValidationError( detail=daemo_error("Invalid recipient for this thread")) else: raise serializers.ValidationError( detail=daemo_error("Invalid conversation")) if serializer.is_valid(): redis_publisher = RedisPublisher(facility='notifications', users=[request.data['recipient']]) message = RedisMessage( json.dumps({ "body": request.data['message'], "time_relative": get_relative_time(timezone.now()), "conversation": request.data['conversation'], "sender": request.user.username })) redis_publisher.publish_message(message) message_data = { "conversation": request.data['conversation'], "body": request.data['message'] } serializer = MessageSerializer(data=message_data, context={'request': request}) if serializer.is_valid(): obj = serializer.create(sender=request.user) response_data = MessageSerializer(instance=obj, context={ "request": request }).data return Response(data=response_data, status=status.HTTP_201_CREATED) raise serializers.ValidationError(detail=serializer.errors) else: raise serializers.ValidationError(detail=serializer.errors)
def allowed_channels(request, channels): log.error('called allowed_channels') try: # Get channel from request uuid = request.path_info uuid = uuid.split('/')[2] # Only authenticated users if request.user.is_authenticated(): # Get character character = get_user_character_active(request) # Get channel user_channels = [] channel = Channel.objects.get(uuid=uuid) if channel.name == 'sync': user_channels.append('subscribe-broadcast') elif ChannelRight.objects.get(character=character, channel=channel): user_channels.append('subscribe-broadcast') p, created = UserList.objects.get_or_create(channel=channel, character=character) p.save() current_time = datetime.utcnow() current_time = current_time.replace(tzinfo=utc) publisher = RedisPublisher(facility=uuid, broadcast=True) # Prepare data values_sending = {'ERROR': -1, 'CODE': utils.result_codes['CHANNEL_JOIN_SUCCESSFULLY'], 'DATA': {'USER': character.nickname, 'TIMESTAMP': "%02d:%02d:%02d" % (current_time.hour, current_time.minute, current_time.second)}, 'ACTION': utils.actions['CHANNEL_JOIN'], 'CALLER': utils.callers['CHANNEL']} if channel.name != 'sync': publisher.publish_message(RedisMessage(json.dumps(values_sending))) return user_channels else: raise PermissionDenied('Not allowed to subscribe nor to publish on the Websocket!') except (ObjectDoesNotExist, MultipleObjectsReturned) as e: return '' # Empy list, no access
def salir(request): redis_publisher = RedisPublisher(facility='foobar', users=['edeamat', 'scondezo']) message = RedisMessage('llamada-' + str(0)) redis_publisher.publish_message(message) age = Agente.objects.get(user_id=request.user.id) age.estado_id = 5 age.id_estado = 0 age.save() logout(request) return HttpResponseRedirect('/comunica7/ingresar')
def create_new_thread_with_topic(title, session_id, course_id, topic, is_instructor): newThread = Thread(title=escape(title), original_poster=session_id, course_id=course_id, topic=topic, pinned=is_instructor) newThread.save() unique_key = 'threads' + course_id + topic redis_publisher = RedisPublisher(facility=unique_key, broadcast=True) message = RedisMessage( json.dumps({ 'type': 'thread_created', 'thread_id': newThread.pk, 'thread_title': newThread.title, 'replyNum': newThread.getNumberOfReplies(), 'pinned': newThread.pinned, })) redis_publisher.publish_message(message) redis_publisher = RedisPublisher(facility=session_id, broadcast=True) message = RedisMessage( json.dumps({ 'type': 'created-thread', 'thread_id': newThread.pk })) redis_publisher.publish_message(message) return newThread
def get(self, request): from ws4redis.publisher import RedisPublisher from ws4redis.redis_store import RedisMessage redis_publisher = RedisPublisher( facility='notify', users=('*****@*****.**', ), ) message = RedisMessage('Hello World') redis_publisher.publish_message(message) return JsonResponse({ 'status': 'ok', })