def publish_py(message, channel=None, event_class="default", data=None, site=SITE_NAME, target=None): cent_url = CENTRIFUGO_HOST + ":" + str(CENTRIFUGO_PORT) if CENTRIFUGO_PROXY is True: cent_url = CENTRIFUGO_HOST client = Client(cent_url, SECRET_KEY, timeout=1) channel = _get_channel(channel, target) if data is None: data = {} payload = { "message": message, "channel": channel, 'event_class': event_class, "data": data, "site": site } err = None try: client.publish(channel, payload) except CentException as e: err = str(e) if event_class.lower() == "debug": print("[DEBUG] ", str(json.dumps(payload))) return err
def __init__(self): self.url = 'http://localhost:8000' file = open('../centrifugo/config.json', 'r') config = json.load(file) self.api_key = config['api_key'] file.close() self.client = Client(self.url, api_key=self.api_key, timeout=1)
class CentClient(object): def __init__(self): print('Init connection') self.con = Client(CENT_URL, api_key=CENT_KEY, timeout=1) def send(self, token, message): self.con.publish(token, message)
def pay_notify(request): data = json.loads(request.body) cl = Client(settings.CENTRIFUGO_HOST, api_key=settings.CENTRIFUGO_API_KEY, timeout=1) status = data['event'] if status == 'refund.succeeded': return Response(status.HTTP_200_OK) order_id = int(data["object"]["description"].split("№")[1]) cl.publish(f'payment{order_id}', status) try: order = Order.objects.get(pk=order_id) except exceptions.ObjectDoesNotExist: return Response(status.HTTP_200_OK) if status == 'payment.succeeded': order.pay_notified = True order.paid = True send_template_email(subject=f'[HRSMNT] Заказ №{order_id}', template='emails/paid.html', context={'order_id': order_id}, to=[order.email]) elif status == 'payment.canceled': order.pay_notified = True order.save() response = HttpResponse() response.status_code = 200 return response
def post(self, request, channel_key): channels = Channel.objects.filter(key=channel_key, status=Channel.AVAILABLE) if not channels: return Response('Channel doesn\'t exist.', status=status.HTTP_404_NOT_FOUND) channel = channels[0] if channel.subscribers.filter(id=request.user.id): channel.subscribers.remove(request.user) response = { 'channel_key': channel.key, 'name': channel.name, 'is_active': False, } client = Client(settings.CENTRIFUGO_URL, api_key=settings.CENTRIFUGO_API_KEY, timeout=1) channel = f"subscriptions#{request.user.id}" client.publish(channel, response) return Response(response, status=status.HTTP_200_OK)
def handle(self, *args, **options): exit_msg = "\nPresence worker stopped" verbosity = options["verbosity"] if verbosity > 0: print("Starting presence worker: watching channels", ",".join(WATCH_CHANNELS)) print("Sending presence info every", FREQUENCY, "seconds") while True: try: cent_url = CENTRIFUGO_HOST + ":" + str(CENTRIFUGO_PORT) client = Client(cent_url, SECRET_KEY, timeout=1) for chan in WATCH_CHANNELS: data = client.presence(chan) datapack = package(data, chan) num_users = len(datapack["users"]) usr = "******" if num_users > 1: usr = "******" msg = "Channel " + chan + ": " + str(num_users) + \ " " + usr + " and " + str(datapack["anonymous"]) + " anonymous" + \ " online" now = datetime.now().strftime('%H:%M:%S') if verbosity > 0: print(now, msg) publish("", "__presence__", datapack, PUBLISH_CHANNEL) time.sleep(FREQUENCY) except KeyboardInterrupt: if verbosity > 0: print(exit_msg) return except: if verbosity > 0: print(exit_msg) return
def delete_comment(request): comment_id = request.GET.get('comment_id') comment = request.user.comment_set.filter(pk=comment_id) if comment: comment.delete() data = {'type': 'del-comment', 'id': comment_id} client = Client(url, secret_key, timeout=1) client.publish('comment', data) status = 'ok' else: status = 'error' return JsonResponse({'status': status})
def question_page(request, pk): try: question = Question.objects.get(id=pk) except ObjectDoesNotExist: # question doesn't exist, should show 404 return render(request, '404_not_found.html') answers = question.answers.best_answers() answers = [add_vote_to_object(answer, request.user) for answer in answers] page = paginate(answers, request, 20) if not request.user.is_authenticated: # showing page without answer form return render( request, 'question_page.html', { 'question': add_vote_to_object(question, request.user), 'page_obj': page }) # формируем token для фронтенда channel_id = str(question.id) token = jwt.encode({"sub": channel_id}, app_settings.CENTRIFUGO_SECRET_KEY) if request.method == 'GET': form = AnswerForm() else: form = AnswerForm(data=request.POST) if form.is_valid(): answer = form.save(commit=False) answer.author = request.user.profile answer.related_question = question answer.save() response = redirect( reverse('question_page', kwargs={'pk': question.id})) response['Location'] += f'#ans{answer.id}' client = Client('http://127.0.0.1:8000', api_key=app_settings.CENTRIFUGO_API_KEY, timeout=1) client.publish('new_answer', {}) return response return render( request, 'question_page.html', { 'question': add_vote_to_object(question, request.user), 'page_obj': page, 'form': form, 'jwt_token': token })
def send_centrifuge(point): client = Client( getattr(settings, 'CENTRIFUGE_URL'), api_key=getattr(settings, 'CENTRIFUGE_APIKEY'), timeout=getattr(settings, 'CENTRIFUGE_TIMEOUT'), ) dict_point = ObjectSerializer(point).data if point.author is not None: dict_point['author'] = point.author.username try: client.publish('latest_points', dict_point) except CentException: return False return True
def post(self, request, video_key): if 'value' not in request.data or request.data['value'] not in [ -1, 0, 1 ]: return Response('Invalid request (or rating value).', status=status.HTTP_400_BAD_REQUEST) new_value = request.data['value'] ratings = Rating.objects.filter(video__key=video_key, video__status=Video.PUBLIC) if not ratings: return Response('Video doesn\'t exist.', status=status.HTTP_404_NOT_FOUND) rating = ratings[0] records = rating.records.filter(author=request.user) if not records: rating.counter += new_value record = RatingRecord(author=request.user, rating=rating, value=new_value) else: record = records[0] if record.value != new_value: if new_value == 0: rating.counter -= record.value elif record.value == 0: rating.counter += new_value else: rating.counter += 2 * new_value record.value = new_value record.save() rating.save() response = { 'counter': rating.counter, } client = Client(settings.CENTRIFUGO_URL, api_key=settings.CENTRIFUGO_API_KEY, timeout=1) channel = f"video/{video_key}/rating" client.publish(channel, response) return Response(response, status=status.HTTP_200_OK)
def check_favorites(request): dish_pk = request.GET['dish_pk'] dish = get_object_or_404(Dish, pk=dish_pk) favorite = dish.favorite_set.filter(author=request.user) if not favorite: dish.favorite_set.create(author=request.user) is_favorited = True type = 'favorite' else: dish.favorite_set.get(author=request.user).delete() is_favorited = False type = 'unfavorite' client = Client(url, secret_key, timeout=1) data = {"type": type, 'id': dish_pk} client.publish('home', data) return JsonResponse({'is_favorited': is_favorited})
def post(self, request, channel_key, video_key): channels = Channel.objects.filter(key=channel_key, status=Channel.AVAILABLE) if not channels: return Response("Wrong channel key.", status=status.HTTP_400_BAD_REQUEST) channel = channels[0] video = Video.objects.filter(key=video_key, status=Video.PUBLIC, owner=channel.owner) if not video: return Response("Wrong video key.", status=status.HTTP_400_BAD_REQUEST) video = video[0] serializer = CommentSerializer(data=request.data) if serializer.is_valid(): print(request.data) if 'parent_id' not in request.data or not request.data['parent_id']: parent = None else: parents = video.comments.filter(id=request.data['parent_id']) if not parents: return Response("Wrong comments id.", status=status.HTTP_400_BAD_REQUEST) parent = parents[0] comment = serializer.create() comment.video = video comment.author = request.user comment.parent = parent comment.save() client = Client(settings.CENTRIFUGO_URL, api_key=settings.CENTRIFUGO_API_KEY, timeout=1) channel = f"video/{video_key}/comments" data = { 'id': comment.id, 'author': comment.author.username, 'text': comment.text, 'created': str(comment.created), 'hide_children': False, 'children': [], 'parent_id': parent.id if parent else None, } client.publish(channel, data) return Response({ 'key': comment.id }, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def __new__(cls, *args, **kw): if not cls.client: cls.client = Client( settings.CENTRIFUGE_ADDRESS, settings.CENTRIFUGE_SECRET, timeout=settings.CENTRIFUGE_TIMEOUT, ) return cls.client
class Centrifugo: def __init__(self): self.url = 'http://localhost:8000' file = open('../centrifugo/config.json', 'r') config = json.load(file) self.api_key = config['api_key'] file.close() self.client = Client(self.url, api_key=self.api_key, timeout=1) def run(self): channel = 'public:chat' data = {'input': 'test'} self.client.publish(channel, data) def send(self, chat_id, user_id, msg): channel = 'public:chat' data = {'chat_id': chat_id, 'user_id': user_id, 'msg': msg} self.client.publish(channel, data)
class CentrifugoClient: client: Client = None def init_app(self, url, api_key): self.client = Client(url, api_key=api_key, timeout=1, verify=False) @do_not_execute(return_value=None, raised_exception=False) def send_problem_run_updates(self, problem_id: int, run: Run): current_app.logger.debug( f'CentrifugoClient: send update for problem {problem_id}') channel = f'problem.{problem_id}' try: self.client.publish(channel, {'run': run.serialize()}) except AttributeError: current_app.logger.exception( f'CentrifugoClient: client is not initialized') except CentException: current_app.logger.exception( f'CentrifugoClient: can\'t send message to centrifugo')
def publish_py(message, channel=None, event_class="default", data=None, site=SITE_NAME, target=None): cent_url = CENTRIFUGO_HOST + ":" + str(CENTRIFUGO_PORT) if CENTRIFUGO_PROXY is True: cent_url = CENTRIFUGO_HOST client = Client(cent_url, SECRET_KEY, timeout=1) channel = _get_channel(channel, target) if data is None: data = {} payload = {"message": message, "channel": channel, 'event_class': event_class, "data": data, "site": site} err = None try: client.publish(channel, payload) except CentException as e: err = str(e) if event_class.lower() == "debug": print("[DEBUG] ", str(json.dumps(payload))) return err
def get_centrifugo_client(): # pylint: disable=invalid-name,protected-access if not settings.CENTRIFUGO_CLIENT_KWARGS: return None centrifugo_client_kwargs = {**settings.CENTRIFUGO_CLIENT_KWARGS} centrifugo_client_kwargs.pop('token_hmac_secret_key', None) logger.debug(f"Getting Centrifugo client with kwargs: {centrifugo_client_kwargs}") client = CentrifugoClient(**centrifugo_client_kwargs) User = get_user_model() @receiver(signals.post_save) @receiver(signals.post_delete) def centrifugo_signal_for_notificate_users_about_updates(instance, *args, **kwargs): if isinstance(instance, (BaseModel, User)) and getattr(instance, '_notify_update', True): notify_clients(instance.__class__, instance.pk) client._signal = centrifugo_signal_for_notificate_users_about_updates return client
def add_comment(request): if request.method == 'POST': dish_pk = request.POST.get('dish_id') form = CommentForm(request.POST) if form.is_valid(): comment = Comment() comment.text = bleach.clean(request.POST.get('text')) comment.author = request.user comment.dish_id = dish_pk comment.save() data = { 'type': 'new-comment', 'comment_pk': comment.pk, 'text': comment.text, 'author': request.user.username, 'avatar': request.user.profile.avatar.url, 'created_at': str(comment.created_at) } client = Client(url, secret_key, timeout=1) client.publish('comment', data) return JsonResponse({'status': 'ok'})
def post(self, request, video_key): video = Video.objects.filter(key=video_key, status=Video.PUBLIC) if not video: return Response('Video doesn\'t exist.', status=status.HTTP_404_NOT_FOUND) views = video[0].views views.counter += 1 views.save() response = { 'counter': views.counter, } client = Client(CENTRIFUGO_URL, api_key=CENTRIFUGO_API_KEY, timeout=1) channel = f"video/{video_key}/views" client.publish(channel, response) return Response(response, status=status.HTTP_200_OK)
def create_vote_for_object(obj_type, user_id, obj_id, mark): # TODO: make global client = Client('http://127.0.0.1:8000', api_key=app_settings.CENTRIFUGO_API_KEY, timeout=1) if obj_type == 'question': # TODO: current rating instead of mark! client.publish('question_vote', { 'user_id': user_id, 'question_id': obj_id, 'mark': mark }) return QuestionVote.objects.create(user_id=user_id, related_object_id=obj_id, mark=mark) else: # TODO: ограничить канал client.publish('answers_vote', { 'user_id': user_id, 'answer_id': obj_id, 'mark': mark }) return AnswerVote.objects.create(user_id=user_id, related_object_id=obj_id, mark=mark)
def main(): result = dict( changed=False, message=[] ) module = AnsibleModule( argument_spec=dict( url=dict(required=True), secret=dict(required=True), data=dict(required=True), channel=dict(required=True) ) ) if module.check_mode: return result url = module.params.get('url') secret = module.params.get('secret') data = module.params.get('data') data = json.loads(data.replace("'", '"')) channel = module.params.get('channel') client = Client(url, secret, timeout=1) try: response = client.publish(channel, data) result['message'].append(response) module.exit_json(**result) return True except Exception as e: module.fail_json(msg=str(e)) return False
class CentrifugeClient(): url = 'http://localhost:8001' api_key = '19cfcd36-a643-4989-a288-0a2e0f662d86' channel = 'centrifuge' client = Client(url, api_key, timeout=1) @classmethod def publish(cls, message): data = { 'status': 'ok', 'message': { 'id': message.id, 'user': message.user_id, 'content': message.content, } } cls.client.publish(cls.channel, data)
class CentrifugeClient: url = 'http://centrifugo:8000' api_key = 'f420f296-4c19-4b42-891c-9f861685b754' channel = "chats:centrifuge" client = Client(url, api_key, timeout=1) @classmethod def publish(cls, message): user = User.objects.get(id=message.user_id) data = { "status": "ok", "message": { 'id': message.id, 'user_id': message.user_id, 'username': user.username, 'content': message.content, } } cls.client.publish(cls.channel, data)
def check_likes(request): obj_pk = request.GET['obj_pk'] obj_type = request.GET['obj_type'] if obj_type == 'comment': obj = get_object_or_404(Comment, pk=obj_pk) elif obj_type == 'dish': obj = get_object_or_404(Dish, pk=obj_pk) like = obj.likes.filter(author=request.user) if not like: obj.likes.create(author=request.user) is_liked = True type = 'like' else: obj.likes.get(author=request.user).delete() is_liked = False type = 'unlike' client = Client(url, secret_key, timeout=1) data = {"type": type, 'id': obj_pk} if obj_type == 'dish': client.publish('home', data) elif obj_type == 'comment': client.publish('comment', data) return JsonResponse({'is_liked': is_liked})
def __init__(self): print('Init connection') self.con = Client(CENT_URL, api_key=CENT_KEY, timeout=1)
from cent import Client from django.conf import settings from django.db.models import F from django.http import JsonResponse, HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST, require_GET from rest_framework import viewsets from rest_framework.decorators import action from chats.tasks import send_email from chats.forms import * from users.serializers import UserSerializer client = Client(settings.CENTRIFUGE_ADDRESS, settings.CENTRIFUGE_API, timeout=1) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer @staticmethod @action(methods=['get'], detail=False) def members(request, *args, **kwargs): result = [] members = Member.objects.filter(chat__id=request.GET.get('chat_id')). \ values_list('user__id', flat=True).order_by('id') for i in list(members): result.append(User.objects.get(id=i))
from django.shortcuts import render, redirect, reverse from questions.models import * from django.core.paginator import Paginator from questions.forms import * from django.http import JsonResponse from django.template.loader import render_to_string from django.contrib.auth import authenticate, logout as d_logout, login as d_login from django.contrib.auth.decorators import login_required from urllib import parse from cent import Client, CentException from django.conf import settings import jwt cl = Client(settings.CENTRIFUGE_ADDRESS, api_key=settings.CENTRIFUGE_API_KEY, timeout=settings.CENTRIFUGE_TIMEOUT) def get_token(request): token = jwt.encode({ "sub": request.user.pk }, settings.CENTRIFUGE_SECRET).decode() if token: return status_response(True, token) else: return status_response(False, 'Can\'t get token from server centrifugo') # cl.publish('news', {'message': 'question has been added'}) def publish(request):
if __name__ == '__main__': parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-c', default="./config.json", help='path to centrifugo config') parser.add_argument('-p', default="8000", help='centrifugo port') args = parser.parse_args() print(args) # centrifugo url = "http://localhost:" + args.__dict__['p'] json_data = open(args.__dict__['c']).read() data = json.loads(json_data) api_key = data['api_key'] client = Client(url, api_key=api_key, timeout=5) inject.configure(base_config) inspector = BlockInspector() while True: block = inspector.get_next_block() txs = import_block(block) for txsData in txs: print(txs) for key in txsData.totals: u_channel = "totals#" + key c_clients = client.presence(u_channel)
import os from cent import Client url = os.environ['CENTRIFUGO_URL'] secret_key = os.environ['CENTRIFUGO_SECRET'] # initialize client instance. client = Client(url, secret_key, timeout=1) # publish data into channel channel = "all" data = {"input": "test"} client.publish(channel, data)
def onChannel(self, dcn): global dc global state state = 1 dc = dcn print("\n=======Got DC=======\n") print("\nPress enter to get the prompt.") def onClose(self): print("DC Closed") os._exit(0) url = "http://" + signalling_server global cent_client cent_client = Client(url, secret_key, timeout=1) # Cent async def run(evt_loop, user): global peer global dc dc = None peer = None timestamp = str(int(time.time())) info = json.dumps({"client_version": "0.1"}) token = generate_token(secret_key, user, timestamp, info=info) async def input_validation(uinput): uinput = uinput[:-1] # Remove '\n' global state global peer
from rest_framework.response import Response from rest_framework import authentication from rest_framework.pagination import CursorPagination from rest_framework.authentication import SessionAuthentication from django.contrib.auth.models import User from cent import Client import json, os, jwt from ..settings import BASE_DIR from .serializers import MessageSerializer, ChatSerializer, UserSerializer from .models import Message, Chat cf_file = open(os.path.join(BASE_DIR, 'config/centrifugo.json')) cf = json.load(cf_file) centrifuge = Client("http://centrifugo:8000", api_key=cf['api_key']) cf_file.close() def check_user_access(request, chatId): if request.user.is_staff: return True chat = Chat.objects.get(id=chatId) return chat.users.filter(id=request.user.id).exists() class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return
def presence_stats(client: Client, channel: str): client.add("presence_stats", {"channel": channel}) result = client.send() return result[0]