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 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)
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 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 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 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 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 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 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 postHeartbeat(self, request, pk=None): global EXPIRATION #check for seperate cache entry """ if (cache.get('heartbeat') != None): #trigger would be 'heartbeat' for status of heartbeats #SEND TRIGGER IN THIS CASE TO START """ if not cache.has_key('heartbeat'): #if doesn't have key heartbeat set its cache entry cache.set('heartbeat','connected',EXPIRATION) else: #else delete the old one cache.delete('heartbeat') #create a new one cache.set('heartbeat','connected',EXPIRATION) #ONCE STARTS RECEIVING HEARTBEATS #cache.set('heartbeat', 'triggering', EXPIRATION) #ONCE STOPS RECEIVING HEARTBEATS #cache.set('heartbeat','stopped', EXPIRATION) if cache.get('trigger') == 1: redis_publisher = RedisPublisher(facility="viewer",sessions=gcsSessions()) redis_publisher.publish_message(RedisMessage(json.dumps({'triggering':'true','time':cache.get("time")}))) elif cache.get('trigger')== 0: redis_publisher = RedisPublisher(facility="viewer",sessions=gcsSessions()) redis_publisher.publish_message(RedisMessage(json.dumps({'triggering':'false'}))) if (cache.has_key('trigger')): return Response({'heartbeat':cache.get('trigger')}) else: return Response({})
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 redisPublishMessage(msj): redis_publisher = RedisPublisher(facility='foobar', broadcast=True) message = RedisMessage(msj) redis_publisher.publish_message(message)
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)
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 new_group(request): groupname = request.POST.get("groupname") totwords = request.POST.get("totwords") totmembers = request.POST.get('totmembers') pref = settings.MY_PREFIX prefg = pref+":"+groupname user = str(request.user) rd = StrictRedis() # the above statements are self explanatory exists = rd.exists(pref+":"+groupname) if exists: # return error, can't create the group with that name # don't do that, just add this user to the already existing group # if group size < totmembers d = rd.hgetall(prefg+":hash") response = {'facility':""} if int(d['totmembers'])>int(d['curmembers']): rd.hincrby(prefg+":hash", 'curmembers') #d = rd.hgetall(prefg+":hash") response['facility'] = groupname response['new_group_created'] = False rd.sadd(prefg, user) #now notify the others that this user joined the group! redis_publisher = RedisPublisher(facility = pref, broadcast = True) mydict = {"type":"new_join", 'who':user, 'name':groupname} msgstring = json.dumps(mydict) print "broadcast message:"+msgstring message = RedisMessage(msgstring) redis_publisher.publish_message(message) # now check if the competition is ready to start if int(d['totmembers'])-1 == int(d['curmembers']): start_competition(request,groupname) return JsonResponse(response) # so the group doesn't exist rd.sadd(prefg, user) # add this user to the set of all the users that are part of this group hashdict = {'totwords':totwords, 'totmembers':totmembers, "owner":user, "name":groupname, 'curmembers':1} # adding group name is redundant but it simplifies things a lot rd.hmset(prefg+":hash", hashdict) # using hash greatly simplifies the things(dict interconversion hgetall()), though i feel that the # naming convention used is horrible redis_publisher = RedisPublisher(facility = pref, broadcast = True) mydict = {"type":"new_group"} mydict.update(hashdict) msgstring = json.dumps(mydict) print msgstring message = RedisMessage(msgstring) redis_publisher.publish_message(message) # notify the others about this new group that was created rd.sadd(pref+":groups", groupname) return JsonResponse({'facility':groupname, 'new_group_created':True})
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 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 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 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 test_publish(request): pref = settings.MY_PREFIX redis_publisher = RedisPublisher(facility = pref, broadcast = True) message = RedisMessage(json.dumps({'type':'test', 'message':'this is a test message from server to everyone!'})) redis_publisher.publish_message(message) if request.GET.get('facility', None): redis_publisher = RedisPublisher(facility = request.GET['facility'], broadcast = True) redis_publisher.publish_message(RedisMessage('this is a test message from server to group!')) return HttpResponse('OK')
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 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 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 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 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 wizz(cls, user, cid, chash, content, keep): cmptr = Comptoir.objects.get(id=cid) if (cmptr.key_hash != chash): # We reject the message publisher = RedisPublisher(facility="fsp", users=user) publisher.publish_message(RedisMessage(hash_error)) else: audience = cls.get_audience([cid]) publisher = RedisPublisher(facility="fsp", users=audience[cid]) wizz_msg = Wizz(user, cmptr, content, keep) publisher.publish_message(wizz_msg.redis())
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 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 mpc_idle(self): """Idle until event received from MPD. Note: this is blocking. To break this loop, toggle some switch on MPD. """ self.ensure_connected() res = [''] if self.connected: res = self.client.idle() self.check_party_mode(res) if 'update' in res and 'updating_db' not in self.client.status(): # let ratings scanner do rescan if database updated self.main.rescan_ratings = True # clear yellow LED write_gpio_pipe('1 0') elif 'update' in res: # raise yellow LED write_gpio_pipe('1 1') if 'playlist' in res: # Tell playlist view to update its status. redis_publisher = RedisPublisher(facility='piremote', broadcast=True) redis_publisher.publish_message(RedisMessage('playlist')) if 'player' not in res: return # Publish current player state via websocket via redis broadcast. state = self.client.status() cur = self.client.currentsong() state_data = dict(event=res) msg = json.dumps(state_data) redis_publisher = RedisPublisher(facility='piremote', broadcast=True) redis_publisher.publish_message(RedisMessage(msg)) # Check if playing and file changed --> insert into history if so. if 'state' in state and state['state'] == 'play': file = cur['file'] if file != self.last_file: self.last_file = file if 'artist' in cur and 'title' in cur: title = '%s - %s' % (cur['artist'], cur['title']) elif 'title' in cur: title = cur['title'] else: no_ext = os.path.splitext(file)[0] title = os.path.basename(no_ext).replace('_', ' ') self.insert_into_history(file, title)
def check_update(self): try: user = User.objects.using('req').get(id=3) except: return False redis_publisher = RedisPublisher(facility='ws_user', users=[user.username]) count_in_progress = Request.objects.using('req').filter(user=user, method__in=['GetFullULResponse', 'GetShortULResponse'], code__in=['52']).order_by( 'root_id').distinct('root_id').count() count_in_resolved = Request.objects.using('req').filter(code__in=['01', '53', '82', '83', '97', '98', '99']).order_by('root_id').distinct( 'root_id').count() log.info('Send on ws update progress - %s, resolved - %s' % (count_in_progress, count_in_resolved)) dict = {'in_progress': count_in_progress, 'new_result': count_in_resolved} message = RedisMessage(json.dumps(dict)) redis_publisher.publish_message(message)
def test_publish(request): pref = settings.MY_PREFIX redis_publisher = RedisPublisher(facility=pref, broadcast=True) message = RedisMessage( json.dumps({ 'type': 'test', 'message': 'this is a test message from server to everyone!' })) redis_publisher.publish_message(message) if request.GET.get('facility', None): redis_publisher = RedisPublisher(facility=request.GET['facility'], broadcast=True) redis_publisher.publish_message( RedisMessage('this is a test message from server to group!')) return HttpResponse('OK')
def send_broadcast_ws(sender, instance, created, **kwargs): if not created: return try: event_type, user, body = decompose_message(instance) rp = RedisPublisher(facility=WEBSOCKETS_FACILITY, broadcast=True) instance_dict = json.dumps(instance.to_dict()) msg = RedisMessage(instance_dict) rp.publish_message(msg) logger.debug('WS socket msg sent: {}'.format(instance_dict)) except Exception as e: logger.debug('Exception sending websocket message', exc_info=True, extra=instance.to_dict()) return
def auto_approve_tasks(): now = timezone.now() # if now.weekday() in [5, 6]: # return 'WEEKEND' # if now.weekday() == 0 and now.hour < 15: # return 'MONDAY' cursor = connection.cursor() # noinspection SqlResolve query = ''' WITH taskworkers AS ( SELECT tw.id, p.id project_id, p.group_id project_gid, tw.task_id, u.id user_id, u.username, u_worker.username worker_username FROM crowdsourcing_taskworker tw INNER JOIN crowdsourcing_task t ON tw.task_id = t.id INNER JOIN crowdsourcing_project p ON t.project_id = p.id INNER JOIN auth_user u ON p.owner_id = u.id INNER JOIN auth_user u_worker ON tw.worker_id = u_worker.id WHERE tw.submitted_at + INTERVAL %(auto_approve_freq)s < NOW() AND tw.status=%(submitted)s) UPDATE crowdsourcing_taskworker tw_up SET status=%(accepted)s, approved_at = %(approved_at)s, auto_approved=TRUE FROM taskworkers WHERE taskworkers.id=tw_up.id RETURNING tw_up.id, tw_up.worker_id, taskworkers.task_id, taskworkers.user_id, taskworkers.username, taskworkers.project_gid, taskworkers.worker_username ''' cursor.execute(query, {'submitted': models.TaskWorker.STATUS_SUBMITTED, 'accepted': models.TaskWorker.STATUS_ACCEPTED, 'approved_at': now, 'auto_approve_freq': '{} hour'.format(settings.AUTO_APPROVE_FREQ)}) task_workers = cursor.fetchall() for w in task_workers: task_workers.append({'id': w[0]}) post_approve.delay(w[2], 1) redis_publisher = RedisPublisher(facility='notifications', users=[w[4], w[6]]) message = RedisMessage( json.dumps({"event": 'TASK_APPROVED', "project_gid": w[5], "project_key": to_hash(w[5])})) redis_publisher.publish_message(message) cursor.close() return 'SUCCESS'
def lanzagestion(request, base, agente): _agente = Agente.objects.get(id=agente) _agente.estado_id = 3 _agente.save() redis_publisher = RedisPublisher(facility='foobar', users=[_agente.user.username]) message = RedisMessage('llamada-' + str(base)) redis_publisher.publish_message(message) _data = Agente.objects.filter(id=agente) serializer = AgentesSerializer(_data, many=True) return JsonResponse(serializer.data, safe=False)
def publish(user, item=None, additional_data=None): if additional_data is None: additional_data = {} redis_publisher = RedisPublisher(facility='all', users=[user.email]) r = JSONRenderer() if item is None: data = {} else: data = item.as_dict() data.update(additional_data) data = r.render(data) message = RedisMessage(data) if getattr(settings, 'TESTING', False): # Do not send in tests return redis_publisher.publish_message(message)
def test_subscribe_user(self): logged_in = self.client.login(username='******', password='******') self.assertTrue(logged_in, 'John is not logged in') request = self.factory.get('/chat/') request.user = User.objects.get(username='******') audience = {'users': ['john', 'mary']} publisher = RedisPublisher(request=request, facility=self.facility, **audience) publisher.publish_message(self.message, 10) websocket_url = self.websocket_base_url + u'?subscribe-user' header = ['Cookie: sessionid={0}'.format(self.client.cookies['sessionid'].coded_value)] ws = create_connection(websocket_url, header=header) self.assertTrue(ws.connected) result = ws.recv() self.assertEqual(result, self.message.decode()) ws.close() self.assertFalse(ws.connected)
def postHeartbeat(self, request, pk=None): global EXPIRATION #check for seperate cache entry """ if (cache.get('heartbeat') != None): #trigger would be 'heartbeat' for status of heartbeats #SEND TRIGGER IN THIS CASE TO START """ if not cache.has_key('heartbeat'): #if doesn't have key heartbeat set its cache entry cache.set('heartbeat', 'connected', EXPIRATION) else: #else delete the old one cache.delete('heartbeat') #create a new one cache.set('heartbeat', 'connected', EXPIRATION) #ONCE STARTS RECEIVING HEARTBEATS #cache.set('heartbeat', 'triggering', EXPIRATION) #ONCE STOPS RECEIVING HEARTBEATS #cache.set('heartbeat','stopped', EXPIRATION) if cache.get('trigger') == 1: redis_publisher = RedisPublisher(facility="viewer", sessions=gcsSessions()) redis_publisher.publish_message( RedisMessage( json.dumps({ 'triggering': 'true', 'time': cache.get("time") }))) elif cache.get('trigger') == 0: redis_publisher = RedisPublisher(facility="viewer", sessions=gcsSessions()) redis_publisher.publish_message( RedisMessage(json.dumps({'triggering': 'false'}))) if (cache.has_key('trigger')): return Response({ 'heartbeat': cache.get('trigger'), 'loop': cache.get('loop'), 'delay': cache.get('delay') }) else: return Response({})
def post(self, request): data = {} django_messages = [] try: order_id = request.POST['order_id'] purchase_order_obj = PurchaseOrder.objects.get(id=order_id) purchase_order_obj.order_status = 'CLOSED' purchase_order_obj.save() #====== Close Conversation ===== customer = purchase_order_obj.customer conversation = Conversation.objects.get(customer=customer, closed=False) conversation.closed = True conversation.save() #=========== Grid Updation ============ grid_detail_data = GridDetails.objects.filter(order=purchase_order_obj, is_active=True) for grid_detail in grid_detail_data: grid_detail.is_active = False grid_detail.order = None grid_detail.save() ################################################################### dealer = purchase_order_obj.dealer employee_data = DealerEmployeMapping.objects.filter(dealer=dealer) employee_name_list = [each_employee.employe.username for each_employee in employee_data] employee_name_list.append(dealer.username) from ws4redis.publisher import RedisPublisher from ws4redis.redis_store import RedisMessage from ws4redis.redis_store import SELF for username in employee_name_list: redis_publisher = RedisPublisher(facility='barhop', users=[username]) message = RedisMessage(".close_"+str(order_id)) redis_publisher.publish_message(message) ################################################################### data['error_msg'] = "" data['success'] = "True" return HttpResponse(json.dumps(data), content_type='application/json') except: data['error_msg'] = "something went WRONG" return HttpResponse(json.dumps(data), content_type='application/json') return HttpResponse(json.dumps(data), content_type='application/json')
def pausar(request, id_agente): redis_publisher = RedisPublisher(facility='foobar', users=['edeamat', 'scondezo']) message = RedisMessage('llamada-' + str(0)) redis_publisher.publish_message(message) ag = Agente.objects.get(id=id_agente) ag.estado_id = 4 ag.id_estado = 1 ag.t_estado = datetime.today() ag.save() LogEstadoAgente(fecha=datetime.today(), estado_id=4).save() return HttpResponseRedirect('/colasIN/monitor_agente/333/0/')
class StatsBroadcaster(StatsConsumer): def __init__(self): StatsConsumer.__init__(self) self.redis_publisher = RedisPublisher(facility='platform', broadcast=True) def BroadCast(self, cpu_stats, mem_stats, disk_stats, processes, es_stats): os_stats = { "cpu": cpu_stats, "mem": mem_stats, "disk": disk_stats, "processes": processes, "es_stats": es_stats } self.redis_publisher.publish_message(RedisMessage( json.dumps(os_stats)))
def lanzaestado(request): # _agente = Agente.objects.get(id=agente) _agentes = Agente.objects.all() _agentes = AgentesSerializer(_agentes,many=True) redis_publisher = RedisPublisher(facility='foobar', users=['root']) message = RedisMessage(_agentes) redis_publisher.publish_message(message) data = simplejson.dumps('body') return HttpResponse(data, content_type="application/json")
def post(self, request, *args, **kwargs): identifier = request.query_params.get('daemo_id', False) if not identifier: return Response("Missing identifier", status=status.HTTP_400_BAD_REQUEST) try: from django.conf import settings from hashids import Hashids identifier_hash = Hashids(salt=settings.SECRET_KEY, min_length=settings.ID_HASH_MIN_LENGTH) if len(identifier_hash.decode(identifier)) == 0: return Response("Invalid identifier", status=status.HTTP_400_BAD_REQUEST) task_worker_id, task_id, template_item_id = identifier_hash.decode(identifier) template_item = models.TemplateItem.objects.get(id=template_item_id) task = models.Task.objects.get(id=task_id) source_url = None if template_item.aux_attributes['src']: source_url = urlsplit(template_item.aux_attributes['src']) else: source_url = urlsplit(task.data[template_item.aux_attributes['data_source']]) if 'HTTP_REFERER' not in request.META.keys(): return Response(data={"message": "Missing referer"}, status=status.HTTP_403_FORBIDDEN) referer_url = urlsplit(request.META['HTTP_REFERER']) if referer_url.netloc != source_url.netloc or referer_url.scheme != source_url.scheme: return Response(data={"message": "Referer does not match source"}, status=status.HTTP_403_FORBIDDEN) redis_publisher = RedisPublisher(facility='external', broadcast=True) task_hash = Hashids(salt=settings.SECRET_KEY, min_length=settings.ID_HASH_MIN_LENGTH) message = RedisMessage(json.dumps({"task_id": task_hash.encode(task_id), "template_item": template_item_id })) redis_publisher.publish_message(message) with transaction.atomic(): task_worker = TaskWorker.objects.get(id=task_worker_id, task_id=task_id) task_worker_result, created = TaskWorkerResult.objects.get_or_create(task_worker_id=task_worker.id, template_item_id=template_item_id) # only accept in progress, submitted, or returned tasks if task_worker.task_status in [1, 2, 5]: task_worker_result.status = 1 task_worker_result.result = request.data task_worker_result.save() return Response(request.data, status=status.HTTP_200_OK) else: return Response("Task cannot be modified now", status=status.HTTP_400_BAD_REQUEST) except ValueError: return Response("Invalid identifier", status=status.HTTP_400_BAD_REQUEST) except Exception: return Response("Fail", status=status.HTTP_400_BAD_REQUEST)
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 lanzadisponible(request, agente): _agente = Agente.objects.get(id=agente) _agente.estado_id = 1 _agente.id_estado = 2 _agente.save() redis_publisher = RedisPublisher( facility='foobar', users=[_agente.user.username, 'edeamat', 'scondezo']) message = RedisMessage('llamada-' + str(0)) redis_publisher.publish_message(message) a = simplejson.dumps('Se lanzo disponible') return HttpResponse(a, content_type="application/json")
def test_subscribe_session(self): logged_in = self.client.login(username='******', password='******') self.assertTrue(logged_in, 'John is not logged in') self.assertIsInstance(self.client.session, (dict, type(self.session)), 'Did not receive a session key') session_key = self.client.session.session_key self.assertGreater(len(session_key), 30, 'Session key is too short') request = self.factory.get('/chat/') request.session = self.client.session audience = {'sessions': [SELF]} publisher = RedisPublisher(request=request, facility=self.facility, **audience) publisher.publish_message(self.message, 10) websocket_url = self.websocket_base_url + u'?subscribe-session' header = ['Cookie: sessionid={0}'.format(session_key)] ws = create_connection(websocket_url, header=header) self.assertTrue(ws.connected) result = ws.recv() self.assertEqual(result, self.message.decode()) ws.close() self.assertFalse(ws.connected)
def lanzallamada(request, base, agente_id): print 'request', request.GET audio = '' if Agente.objects.filter(anexo=int(agente_id)).count() == 0: a = simplejson.dumps('No existe el agente con el anexo ' + agente_id) return HttpResponse(a, content_type="application/json") for r in request.GET: if r == 'audio': audio = request.GET['audio'] #ProduccionAudio(audio=audio,telefono=base,agente_id=Agente.objects.get(anexo=int(agente_id)).id).save() if Agente.objects.filter(anexo=int(agente_id)).count() > 1: a = simplejson.dumps('Existe muchos agentes agente con el anexo ' + agente_id) return HttpResponse(a, content_type="application/json") _agente = Agente.objects.get(anexo=int(agente_id)) _agente.estado_id = 2 _agente.id_estado = 3 _agente.save() print 'lanzallamada', _agente.user.username redis_publisher = RedisPublisher( facility='foobar', users=[_agente.user.username, 'edeamat', 'scondezo']) message = RedisMessage('llamada-' + str(base) + '-' + str(audio)) redis_publisher.publish_message(message) a = simplejson.dumps('Se lanzo la llamada al agente con anexo ' + agente_id) return HttpResponse(a, content_type="application/json")
def send_notification_ws(sender, instance, created, **kwargs): #Only send WS message if it's a new notification not if we're updating. logger.debug('receiver received something.') if not created: return try: rp = RedisPublisher(facility=WEBSOCKETS_FACILITY, users=[instance.user]) # logger.debug(instance.to_dict()) instance_dict = json.dumps(instance.to_dict()) msg = RedisMessage(instance_dict) rp.publish_message(msg) # logger.debug('WS socket msg sent: {}'.format(instance_dict)) except Exception as e: # logger.debug('Exception sending websocket message', # exc_info=True, # extra = instance.to_dict()) logger.debug('Exception sending websocket message', exc_info=True) return
def supervisor(request): agentes = Agente.objects.all() print 'traes la daata?', agentes colas = ColasinAcd.objects.all() redis_publisher = RedisPublisher(facility='foobar', users=['edeamat', 'scondezo']) message = RedisMessage('hola') redis_publisher.publish_message(message) return render(request, 'colasIN/supervisor.html', { 'agentes': agentes, 'colas': colas })
class Clock(object): def __str__(self): return "O'clock: {0} | P'clock: {1}".format(self.oclock(), self.pclock()) 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 pclock(self): return datetime.datetime.now() + datetime.timedelta(seconds=self.delta) def oclock(self): return datetime.datetime.now() def new_minute(self): print "WOW" self.printc() last = random.randint(-20, 20) self.laps["second"] = 60 + last print "New minute elapsed. Next minute will last {0} seconds.".format( self.laps["second"]) msg = RedisMessage( json.dumps({ "type": "second", "laps": self.laps["second"] })) self.redis_publisher.publish_message(msg) self.delta += last self.sch.add_job(self.new_minute, 'date', run_date=datetime.datetime.now() + datetime.timedelta(seconds=self.laps["second"] + 10)) def printc(self): print self.__str__()
def deleteTarget(self, request, pk=None): connectionCheck() try: #get target photo path and delete it target = Target.objects.get(pk=request.data['pk']) os.remove(target.picture.path) target.delete() redis_publisher = RedisPublisher(facility='viewer', sessions=gcsSessions()) redis_publisher.publish_message( RedisMessage( json.dumps({ 'target': 'delete', 'pk': request.data['pk'] }))) return HttpResponse('Success') except Target.DoesNotExist: pass return HttpResponseForbidden("Target does not exist")
def _interactive_job_callback(sender, **kwargs): event_type = kwargs.get('event_type') if event_type == 'VNC': event_data = kwargs.get('event_data') job_owner = event_data.get('job_owner') WEBSOCKETS_FACILITY = 'websockets' users = [event_data.get('job_owner')] logger.info('Event received from %s', sender) logger.info('Sending %s', event_data) notification = Notification( event_type=event_type, user=job_owner, body=json.dumps(event_data)) notification.save() rp = RedisPublisher(facility = WEBSOCKETS_FACILITY, users=users) msg = RedisMessage(json.dumps(event_data)) rp.publish_message(msg)
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 ds_event_callback(sender, **kwargs): WEBSOCKETS_FACILITY = 'websockets' event_type = kwargs.get('event_type', '') users = kwargs.get('users', []) data = copy.copy(kwargs) data.pop('signal') logger.info('Event received from {0}'.format(sender)) logger.info('Event Type: {0}'.format(event_type)) logger.info('Event kwargs: {0}'.format(kwargs)) if users: rp = RedisPublisher(facility=WEBSOCKETS_FACILITY, users=users) else: rp = RedisPublisher(facility=WEBSOCKETS_FACILITY, broadcast=True) msg = RedisMessage(json.dumps(data)) rp.publish_message(msg)
def create(self, validated_data): schedule_obj = Schedules.objects.create(**validated_data) redis_publisher = RedisPublisher(facility='alerts', broadcast=True) schedule_obj.uber_arrival_time = get_uber_time_estimate( schedule_obj.source_latitude, schedule_obj.source_longitude, schedule_obj.product_id) message = RedisMessage('{} Requested uber api for {}'.format( datetime.datetime.now().strftime('%H:%M:%S'), schedule_obj.email)) redis_publisher.publish_message(message) schedule_obj.travel_time = get_travel_estimate( schedule_obj.source_latitude, schedule_obj.source_longitude, schedule_obj.destination_latitude, schedule_obj.destination_longitude) message = RedisMessage('{} Requested map api for {}'.format( datetime.datetime.now().strftime('%H:%M:%S'), schedule_obj.email)) redis_publisher.publish_message(message) current_time = int(datetime.datetime.now().strftime('%s')) total_travel_time = schedule_obj.uber_arrival_time + schedule_obj.travel_time remaining_time = (schedule_obj.schedule_time - (current_time + total_travel_time)) if remaining_time <= BOOKING_CONSTANT: schedule_obj.is_booked = True msg = """Hi, You booked a cab with us for {}. Please leave now to reach earliest by {}""".format( time.strftime('%H:%M:%S', time.localtime(schedule_obj.schedule_time)), time.strftime( '%H:%M:%S', time.localtime((total_travel_time + current_time)))) send_mail('Book your uber', msg, '*****@*****.**', [schedule_obj.email], fail_silently=False) else: check_and_book.apply_async(args=(schedule_obj.id, ), countdown=remaining_time / CONSTANT_FACTOR) schedule_obj.save() return schedule_obj
def pushmessage(request): redis_publisher = RedisPublisher(facility='subscribe', users=[request.GET.get('user')]) #redis_publisher = RedisPublisher(facility='subscribe', broadcast=True) data = {} data['message'] = "You got it" data['audio'] = "" messagebody = """ { "alert": "Updates Available", "badge": 1, "data": "{'version':'1.13','size':'14MB'}", "priority": "high", "sound": "DefaultNotificationSound", "gcmNotification": { "title": "The Title For The App", "icon": "TheIcon", "body": "The Notification Body", "sound": "OverrideSound", "color": "Blue", "tag": "TheTag", "collapseKey": "TheCollapseKey", "delayWhileIdle": true, "timeToLive": 10, "restrictedPackageName": "com.sap.test", "clickAction": "TheClickAction", "bodyLocKey": "message", "bodyLocArgs": "[\"msg1\",\"msg2\"]", "titleLocKey": "titleMessage", "titleLocArgs": "[\"tmsg1\",\"tmsg2\"]" }, "customParameters": { "gcm.badge": 2 } } """ message = RedisMessage(messagebody) # and somewhere else redis_publisher.publish_message(message) return JsonResponse(data)
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: return Response(data={"message": "Invalid recipient for this thread"}, status=status.HTTP_400_BAD_REQUEST) else: return Response(data={"message": "Invalid conversation"}, status=status.HTTP_400_BAD_REQUEST) if serializer.is_valid(): redis_publisher = RedisPublisher(facility='inbox', 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) return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def update_room_listeners(self, request): facility = request.path_info.replace(settings.WEBSOCKET_URL, '', 1) if facility not in [room.token for room in Room.objects.all()]: raise Exception("Unknow room") prefix = self.get_prefix() key = prefix + 'broadcast:' + facility query = self._connection.execute_command('PUBSUB', 'NUMSUB', key) room_to_update = Room.objects.get(token=facility) room_to_update.listeners = int(query[1]) if len(query) > 1 else 0 room_to_update.save() redis_publisher = RedisPublisher(facility=room_to_update.token, broadcast=True) message = { 'action': 'listeners_updated', 'listeners': room_to_update.listeners } listenersMessage = RedisMessage(json.dumps(message)) redis_publisher.publish_message(listenersMessage)
def post(self, request, pk, format=None): message = request.POST.get('message', '') if Room.objects.get(pk=pk) and message: data = { 'room': pk, 'message': message, 'success': "true", } redis_publisher = RedisPublisher( facility='room-%d' % pk, users=[Room.objects.get(pk=pk).members], broadcast=True) redis_publisher.publish_message(message) else: data = { 'error_message': "Error sending message=%s to room=%d" % (message, int(pk)), 'success': "false" } return Response(data, status.HTTP_200_OK)