Ejemplo n.º 1
0
def send_push(request):
    try:
        body = request.body
        data = json.loads(body)

        if 'head' not in data or 'body' not in data or 'id' not in data:
            return JsonResponse(status=400,
                                data={"message": "Invalid data format"})

        user_id = data['id']
        user = get_object_or_404(User, pk=user_id)
        payload = {'head': data['head'], 'body': data['body']}
        send_user_notification(user=user, payload=payload, ttl=1000)

        return JsonResponse(status=200,
                            data={"message": "Web push successful"})
    except TypeError:
        return JsonResponse(status=500, data={"message": "An error occurred"})
Ejemplo n.º 2
0
def send_to_user(head,
                 body,
                 user,
                 icon="https://i.imgur.com/dRDxiCQ.png",
                 url="https://www.example.com"):
    """
    This function will send push-notification to user
    :param head: HEAD of notification
    :type head: text
    :param body: BODY of the message
    :type body: text
    :param user: User object, that wil see this message
    :type user: User object
    :param icon: icon for notification
    :param url: notification-URL
    :return:
    """
    payload = {'head': head, 'body': body, "icon": icon, "url": url}
    send_user_notification(user=user, payload=payload, ttl=1000)
Ejemplo n.º 3
0
    def post(self, request, *args, **kwargs):
        '''Create new Ticket'''
        form = CreateTicketForm(request.data)
        # request.data['due_date'] = datetime.datetime.strptime(request.data.get('due_date'), '%Y-%m-%d %H:%M:%S')
        form.instance.assigned_by = self.request.user

        form.save(commit=True)

        # Send generic message since push notifs work even when token expires
        payload = {'head': 'Task Assigned', 'body': 'Check your dashboard for new task', 'url': 'http://{}'.format(Site.objects.get_current().domain)}
        try:
            print(form.instance.assigned_to.id)
            send_user_notification(form.instance.assigned_to, payload, 1500)
        except:
            import traceback
            traceback.print_exc()
            pass
        return response.Response(data=TicketMiniSerializer(form.instance).data,
                                 status=status.HTTP_201_CREATED)
Ejemplo n.º 4
0
def push_on_reply(sender, instance, created, **kwargs):
    certain_comment = Comment.objects.get(pk=instance.pk)

    if created and certain_comment.parent:
        payload = {
            'head':
            'Відповідь на ваш коментар',
            'body':
            'Ви отримали відповідь на ваш коментар на сайті diggers.kiev.ua',
            'icon':
            getattr(settings, 'WEBPUSH_ICON_URL'),
            'url':
            '%s#comment%s' %
            (reverse('post_detail', kwargs={'pk': certain_comment.post.pk
                                            }), certain_comment.pk),
        }
        send_user_notification(user=certain_comment.parent.author,
                               payload=payload,
                               ttl=1000)
Ejemplo n.º 5
0
def send_push(request):
    #try:
    body = request.body

    data = {
        'push_head': request.POST.get('push_head'),
        'push_body': request.POST.get('push_body'),
        'id': request.POST.get('id')
    }

    if 'push_head' not in data or 'push_body' not in data or 'id' not in data:
        return JsonResponse(status=400,
                            data={"message": "Invalid data format"})

    user = request.user
    payload = {'head': data['push_head'], 'body': data['push_body']}
    send_user_notification(user=user, payload=payload, ttl=1000)

    return JsonResponse(status=200, data={"message": "Web push successful"})
Ejemplo n.º 6
0
    def send_message(self, coder, method, data, **kwargs):
        method, *args = method.split(':', 1)
        subject, message, context = self.get_message(method=method, data=data, coder=coder,  **kwargs)
        if method == settings.NOTIFICATION_CONF.TELEGRAM:
            if args:
                self.TELEGRAM_BOT.send_message(message, args[0], reply_markup=False)
            elif coder.chat and coder.chat.chat_id:
                try:
                    if not coder.settings.get('telegram', {}).get('unauthorized', False):
                        self.TELEGRAM_BOT.send_message(message, coder.chat.chat_id, reply_markup=False)
                except Unauthorized as e:
                    if 'bot was blocked by the user' in str(e):
                        coder.chat.delete()
                    else:
                        coder.settings.setdefault('telegram', {})['unauthorized'] = True
                        coder.save()
            elif 'notification' in kwargs:
                kwargs['notification'].delete()
        elif method == settings.NOTIFICATION_CONF.EMAIL:
            send_mail(
                subject,
                message,
                'CLIST <*****@*****.**>',
                [coder.user.email],
                fail_silently=False,
                html_message=message,
            )
        elif method == settings.NOTIFICATION_CONF.WEBBROWSER:
            payload = {
                'head': subject,
                'body': message,
            }
            contests = list(context.get('contests', []))
            if len(contests) == 1:
                contest = contests[0]
                payload['url'] = contest.url
                payload['icon'] = f'{settings.HTTPS_HOST_}/imagefit/static_resize/64x64/{contest.resource.icon}'

            send_user_notification(
                user=coder.user,
                payload=payload,
                ttl=300,
            )
Ejemplo n.º 7
0
def pass_rules_view(request, pk):
    c = Components.objects.get_records_by_course_id(pk)
    if c.exists():
        course = Course.objects.get_record_by_id(pk)
        t = Thresholds.objects.get(course_id=pk)
        cg = None
        if request.method == 'POST':
            rules = RulesForm(request.POST, course_id=pk)
            thresholds = ThresholdsForm(request.POST, instance=t)
            if course.type == "W":
                cg = CourseGroupForm(request.POST, course_id=pk)
                if cg.is_valid():
                    cg.save_edit()

            if rules.is_valid() and thresholds.is_valid():
                rules.save_edit()
                thresholds.save()
                return redirect('/course/' + str(pk))
        else:
            if course.type == "W":
                cg = CourseGroupForm(course_id=pk)
                cg.fill_edit()

            rules = RulesForm(course_id=pk)
            rules.fill_edit()
            thresholds = ThresholdsForm(instance=t)
        return render(
            request, 'new_pass_rules.html', {
                'cg_form': cg,
                'rules_form': rules,
                'thresholds_form': thresholds,
                "pk": pk,
                "edit": True
            })

    else:
        payload = {
            "head": "Błąd!",
            "body": "Zasady zaliczenia nie zostały jeszcze utworzone!"
        }
        send_user_notification(user=request.user, payload=payload, ttl=1000)
        return redirect('/course/' + str(pk))
Ejemplo n.º 8
0
 def create(self, request):
     serializer = MessageSerializer(data=request.data)
     if serializer.is_valid(
     ) and request.user == serializer.validated_data['sender']:
         serializer.validated_data['is_read'] = False
         serializer.save()
         payload = {
             "head":
             "Medis Group LLC",
             "body":
             f"Сообщение от пользователя {serializer.validated_data['sender']}",
             #"icon": "https://i.imgur.com/dRDxiCQ.png",
             "url":
             f"https://antares.nullteam.info/portal/chat/private/{serializer.instance.sender.id}"
         }
         send_user_notification(user=serializer.validated_data['receiver'],
                                payload=payload,
                                ttl=1000)
         return Response(serializer.data, status=201)
     return Response(serializer.errors, status=400)
Ejemplo n.º 9
0
 def handle(self, *args, **options) -> None:
     payload: Dict[str, str] = {
         "head": "もうすぐ〆切!",
     }
     nearby_tasks: List[Task] = Task.objects.filter(
         deadline__gt=timezone.now(),
         deadline__lt=timezone.now() + datetime.timedelta(days=1))
     for user in User.objects.all():
         tasks: Task = nearby_tasks.filter(
             group__in=user.groups.all()).order_by('deadline')
         if tasks:
             task = tasks[0]
             payload[
                 "icon"] = "/static/images/icon_" + user.mycolor + ".png"
             payload["url"] = reverse('todo:todolist', args=[task.group.id])
             deadline_str: str = task.deadline.astimezone(
                 pytz.timezone(user.tz)).strftime('%m/%d %H:%M')
             payload["body"] = "{}\t{} 〆切".format(task.task_text,
                                                  deadline_str)
             send_user_notification(user=user, payload=payload, ttl=1000)
Ejemplo n.º 10
0
def push_notification(request):
    if 'notification' in request.GET:
        payload = {
            "head": request.user.username,
            "body": request.GET['notification']
        }
    else:
        payload = {"head": request.user.username, "body": "有東西出錯了"}

    notification_count = NotificationCount.objects.get(user=request.user)
    if int(notification_count.count) > 0:
        notification_count.count = int(notification_count.count) - 1
        notification_count.save()

        send_group_notification(group_name='all', payload=payload, ttl=1000)
        return redirect(reverse('chatdemo:home_page'))
    else:
        payload = {"head": "Error", "body": "尬廣次數不足"}
        send_user_notification(user=request.user, payload=payload, ttl=1000)
        return redirect(reverse('chatdemo:home_page'))
Ejemplo n.º 11
0
def send_webpush_notification(sender, instance, created, **kwargs):
    if not created:
        return

    notification = instance

    def fmt(obj):
        if obj:
            if hasattr(obj, 'notification_str'):
                return obj.notification_str()
            return str(obj)
        return ""

    msg = (
        f"{fmt(notification.actor)} {notification.verb} {fmt(notification.action_object)} {fmt(notification.target)}"
        .strip())
    body = msg

    if isinstance(notification.action_object, Comment):
        body = notification.action_object.text

    url = None
    if hasattr(notification.action_object, 'notification_url'):
        url = notification.action_object.notification_url()

    payload = {
        "head": msg,
        "body": body,
        "data": {
            'notification_id': notification.id,
        },
    }

    if url:
        payload['data']['url'] = url

    try:
        send_user_notification(user=notification.recipient, payload=payload)
    except WebPushException as e:
        logging.warn("%s failed for %s", e, notification.recipient)
Ejemplo n.º 12
0
def Notify(request):
    if request.method == "POST":
        try:
            token = request.POST['token']
            vid = request.FILES['video']
            head = None
            head = "Suspicious Activity Detected"
            try:
                cam = TokenManager.objects.get(token=token)
                body = cam.name
                Document(user=cam.user, vid=vid).save()
                obj = Document.objects.filter(
                    user=cam.user).order_by('uploaded_at').last()
                user = User.objects.get(id=cam.user)
                payload = {
                    "head":
                    head,
                    "body":
                    body,
                    "icon":
                    "https://i.imgur.com/2IG0Lcp.png",
                    "url":
                    'http://127.0.0.1:8000/stream/' +
                    str(obj.vid.url).split('/')[-1]
                }
                send_user_notification(user=user, payload=payload, ttl=1000)
                return JsonResponse({
                    'status': 200,
                    "message": "Notifier Started"
                })

            except (User.DoesNotExist, TokenManager.DoesNotExist):
                return JsonResponse({
                    'status': 403,
                    "message": "Access Denied"
                })
        except:
            return JsonResponse({'status': 403, 'message': 'Forbidden'})

    return JsonResponse({'message': 'You have been judged'})
Ejemplo n.º 13
0
def send_friend_message(request, pk):
    friend = get_object_or_404(User, pk=pk)
    chat_box = ChatBox.objects.filter(user_1=request.user,
                                      user_2=friend).first()
    if not chat_box:
        chat_box = ChatBox.objects.filter(user_1=friend,
                                          user_2=request.user).first()
    message = Message(chat_box=chat_box,
                      message_sender=request.user,
                      message=request.GET.get('message'))
    # friend notification
    if friend.allow_friends_notifications:
        # !ABSOLUTE PATH
        notification = Notification.objects.create(
            type='friend_message',
            sender=request.user,
            url=f'/social/chat_friend/{request.user.id}',
            content=
            f'a message from {request.user.username}: {message.message[:100]}')
        notification.save()
        notification.receiver.add(friend)
        for receiver in notification.receiver.all():
            if notification.sender.who_see_avatar == 'everyone':
                sender_avatar = notification.sender.avatar.url
            elif notification.sender.who_see_avatar == 'friends' and receiver in receiver.friends.all(
            ):
                sender_avatar = notification.sender.avatar.url
            else:
                sender_avatar = '/media/profile_images/DefaultUserImage.jpg'
            payload = {
                "head": f"Message from {notification.sender}",
                "body": notification.content,
                "url": notification.url,
                "icon": sender_avatar,
            }
            send_user_notification(user=receiver, payload=payload, ttl=1000)
    # End normal friend notification
    message.save()
    return JsonResponse({})
Ejemplo n.º 14
0
    def do(self):
        tasks = ParseTask.objects.filter(service='HS')
        users = []
        now = datetime.now()
        for task in tasks:
            rn = services.ParseService("HS")
            data = rn.start(task.login, task.password, task.extra_data)
            task.result = data
            task.save()
            d = datetime.strptime(data['date'], '%Y-%m-%d')
            if (d - now).days < 5:
                users.append(task.user)

        for user in users:
            send_user_notification(
                user=user,
                payload={
                    'head': 'Сервис требует внимания',
                    'body': 'На сервисе Hostens заканчиваются деньги!'
                },
                ttl=604800
            )
Ejemplo n.º 15
0
def home(request):
    condos = RoomCatalog.objects.filter(
        property_id__property_type=0).order_by('?')[:6]
    apartments = RoomCatalog.objects.filter(
        property_id__property_type=1).order_by('?')[:6]
    dorms = RoomCatalog.objects.filter(
        property_id__property_type=2).order_by('?')[:6]

    current_url = resolve(request.path_info).url_name

    try:
        payload = {
            "head": "Welcome to Roomy!",
            "body": f"Hi {request.user.first_name}, start booking apps now!",
            "url": current_url
        }
        send_user_notification(user=request.user, payload=payload, ttl=1000)
    except Exception as e:
        pass
    print("USER_AGENT:", request.user_agent)
    if request.user_agent.device.family == "Roomy Native":
        if request.user.is_authenticated:
            return redirect('profile')
        else:
            context.update({
                "dorms": dorms,
                "condos": condos,
                "apartments": apartments
            })
            return render(request,
                          "mobile-native/components/landing/home.html",
                          context)
    else:
        context.update({
            "dorms": dorms,
            "condos": condos,
            "apartments": apartments
        })
        return render(request, "web/components/landing/home.html", context)
Ejemplo n.º 16
0
def send_push(request):
    """
    This function gets JSON with body and head, than pushes message
    :param request:
    :return: JSONResponse with status
    {"name": "admin",
    "head": "asd",
    "body": "asd"}
    {"name": "admin",
    "head": "Test message",
    "body": "Test message",
    "url": "example.com",
    "icon": "https://i.imgur.com/dRDxiCQ.png"}
    """
    try:
        data = request.data
        url = None
        try:
            url = data['url']
            icon = data['icon']
            use_full_shema = True
        except KeyError:
            use_full_shema = False
        try:
            user_id = data['id']
            user = get_object_or_404(User, pk=user_id)
        except KeyError:
            user_name = data['name']
            user = get_object_or_404(User, username=user_name)
        if use_full_shema:
            send_to_user(data['head'], data['body'], user, icon, url)
        else:
            payload = {'head': data['head'], 'body': data['body']}
            send_user_notification(user=user, payload=payload, ttl=1000)
        return JsonResponse(status=200,
                            data={"message": "Web push successful"})
    except TypeError:
        return JsonResponse(status=500, data={"message": "An error occurred"})
Ejemplo n.º 17
0
def opt_helper(algo_id: int, req_data: str, user_id: int): #pragma: no cover
    algorithm = Algorithm.objects.get(pk=algo_id)
    algorithm.optimization = "pending"
    algorithm.save()
    algorithm_data = AlgorithmSerializer(algorithm).data
    algorithm_data["id"] = algo_id
    var_scopes = list(json.loads(req_data).values())
    preprocessed_code, offsets = extract_offsets(algorithm_data["snippet_scope_data"]["code"])
    print("offsets at opt helper!!!!!!!!!!!!!!!!!!!!!", offsets)
    algorithm_data["snippet_scope_data"]["code"] = preprocessed_code
    # offsets: [...(offset: @의 위치)...] , snippet_scope 의 @뒤 숫자들은 모두 삭제된 상태.
    best, loss = optimize(offsets, var_scopes, algorithm_data)
    new_code = insert_params_non_global(offsets, list(best.values()), preprocessed_code)
    optimization = {
        "parameters": json.dumps(best),
        "profit": json.dumps(loss),
        "new_code": json.dumps(new_code)
    }
    algorithm.optimization = str(optimization)
    algorithm.save()
    user = User.objects.get(pk=user_id)
    payload = {'head': "Optimization is Over!!!", 'body': 'Click "view" to see detailed report of your backtest'}
    send_user_notification(user=user, payload=payload, ttl=100)
Ejemplo n.º 18
0
def send_group_message(request, pk):
    group = get_object_or_404(ChatGroup, pk=pk)
    try:
        area = get_object_or_404(Area, pk=request.GET.get('area'))
    except:
        area = None
    message = GroupMessage(group=group,
                           message_sender=request.user,
                           message=request.GET.get('message'),
                           area=area)
    # group notification
    receivers = [
        member
        for member in group.members.filter(Q(
            allow_groups_notifications=True), ~Q(id=request.user.id))
    ]
    notification = Notification(type='group_message',
                                sender=request.user,
                                url=f'/social/chat_group/{group.id}/',
                                content=message.message[:100])
    if receivers:
        notification.save()
        for receiver in receivers:
            if not area or not receiver in area.muted_users.all():
                notification.receiver.add(receiver)
        for receiver in notification.receiver.all():
            payload = {
                "head":
                f"A message from {group.title} Group, {notification.sender}",
                "body": notification.content,
                "url": notification.url,
                "icon": group.image.url,
            }
            send_user_notification(user=receiver, payload=payload, ttl=1000)

    message.save()
    return JsonResponse({})
Ejemplo n.º 19
0
def payment_form(request, pk):
    if request.method == 'POST':
        form = PaymentForm(request.POST)
        if form.is_valid():
            user = User.objects.get(pk=pk)
            classroom = user.profile.classroom
            class_room = ClassRoom.objects.get(classname=classroom)
            amount = form.cleaned_data.get('amount')
            month = form.cleaned_data.get('month')
            payment = Payment(user=user,
                              classroom=class_room,
                              amount=amount,
                              month=month)
            payment.save()
            text = "Your fees of amount {} is deposited .".format(amount)
            msg = StudentMessage(user=user, msg=text)
            msg.save()
            count = MessageCount(user=user)
            count.save()
            messages.success(request, 'Fees Deposited Successfully')
            try:
                payload = {"head": "Praxis", "body": text}
                send_user_notification(user=user, payload=payload, ttl=1000)
            except:
                pass
            # html = render_to_string('school/payment/payment_pdf.html', {'user': user,
            #                                                             'amount':amount,
            #                                                             'month':month})
            # response = HttpResponse(content_type='application/pdf')
            # response['Content-Disposition'] = 'filename="Invoice.pdf"'
            # weasyprint.HTML(string=html).write_pdf(response,
            #                            stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')])
            # return response
    else:
        form = PaymentForm()
    return render(request, 'school/payment/payment_form.html', {'form': form})
Ejemplo n.º 20
0
def add_mark_view(request, pk):
    p = Components.objects.get_records_by_course_id(pk)
    if (p.exists()):
        if request.method == 'POST':
            mark = MarkForm(request.POST, course_id=pk)

            if mark.is_valid():
                m = mark.save(commit=False)
                m.course_id = Course.objects.get_record_by_id(pk)
                m.save()
                calc_final(Course.objects.get_record_by_id(pk))
                return redirect('/course/' + str(pk))
        else:
            mark = MarkForm(course_id=pk)

        return render(request, "new_mark.html", {"mark_form": mark, "pk": pk})

    else:
        payload = {
            "head": "Błąd!",
            "body": "Aby dodać ocenę potrzebne są \n zasady zaliczenia!"
        }
        send_user_notification(user=request.user, payload=payload, ttl=1000)
        return redirect('/course/' + str(pk), {"message": True})
Ejemplo n.º 21
0
def user_login(request):
    form = AuthenticationForm()

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)

        if user is not None:
            payload = {"head": "Welcome!", "body": "Hello World"}
            send_user_notification(user=user, payload=payload, ttl=1000)
            login(request, user)
            return render(request=request,
                          template_name="home.html",
                          context={"form": form})

        else:
            return render(request=request,
                          template_name="login.html",
                          context={"form": form})

    return render(request=request,
                  template_name="login.html",
                  context={"form": form})
Ejemplo n.º 22
0
def addresult(request):
    if request.user.has_perm('problem.user_moderator') or request.user.has_perm('block.moderator') or request.user.has_perm('block.executor'):
        if request.method == 'POST':
            di = request.POST
            blo = Appeal.objects.get(nomdobr=di['pk'])
            res = Result.objects.create(block=blo, chstatus=di['status'], text=di['text'], nomkom=di['nomkom'],
                                        user=request.user)
            res.save()
            blo.status = di['status']
            print(1)
            if blo.status == '0':
                group = Group.objects.get(pk=6)
                users = Person.objects.filter(groups=group)
                blo.text = di['text']
                for i in users:
                    payload = {"head": "Изменен статус", "body": f"Обращение №{blo.nomdobr}. Изменен статус на: {blo.get_status_display()}"}
                    send_user_notification(user=i, payload=payload, ttl=1000)
            else:
                payload = {"head": "Изменен статус", "body": f"Обращение №{blo.nomdobr}. Изменен статус на: {blo.get_status_display()}"}
                send_user_notification(user=blo.user, payload=payload, ttl=1000)
            blo.save()
            print(f'Обращение: {blo.nomdobr}, новый статус: {blo.get_status_display()}')
            content = {}
            return JsonResponse(content)
Ejemplo n.º 23
0
def send_dummy(request):
    log = '{}: '.format(str(request.user))
    response = ''
    payload = {
        "head": "Welcome!",
        "body": "This is dummy notification. Plain and hard-coded!"
    }

    try:
        response = send_user_notification(user=request.user,
                                          payload=payload,
                                          ttl=1000)
        log = 'Notification sent. {}'.format(str(response))
    except:
        log = 'asdf failed send notification. {}'.format(str(response))

    # send_user_notification(user=request.user, payload=payload, ttl=1000)

    return HttpResponse(log)
Ejemplo n.º 24
0
def sender():
    mass_messages = []
    users = User.objects.all()
    ahorro = Ahorro.objects.all()
    user_ids = users.values_list('pk', flat=True)
    print(list(user_ids))
    print(user_ids)
    print('888888888')
    # sistemas = Sistema.objects.all().filter(user = '******')
    sistemas = Sistema.objects.all()

    febrero = 2
    todayMonth = datetime.datetime.now().month
    dt = datetime.datetime.today()


    # print(len(ahorro), "ahorro")
    for s in sistemas:
        if s.not_archived:
            # print('no archivados', s.user, 'esta ahorrando para', s)
            if dt.day % int(s.frecuencia) == 0 or todayMonth % int(s.frecuencia) == 0:
                if s.email:
                    d = Context({ 'username': s.user, 'nombreahorro': s })
                    subject = 'Es momento de ahorrar'
                    # html_content = f'<p>Hola <strong>{s.user}</strong> hoy te toca ahorrar para {s}</p>'
                    html_content = htmly.render(d)
                    text_content = plaintext.render(d)
                    from_email = '*****@*****.**'
                    to = f'{s.user.email}'
                    # message = (subject, text_content, from_email, [to])
                    message = EmailMultiAlternatives(subject, text_content, from_email, [to])
                    message.attach_alternative(html_content, "text/html")
                    # mass_messages.append(message)

                    send_mail(message)

                    print(s, 'aviso por mail')
                    # print('cuales mails y como', mass_messages)
                    print('Hola', s.user, 'hoy te toca ahorrar para:', s )

                # send_mass_mail((mass_messages), fail_silently=False)

                if s.push:
                    # push notification testing
                    payload = {"head": "¡Es momento de ahorrar!",
                            "body": f"Hola {s.user} Ahorra para {s}",
                            "icon": "https://i.imgur.com/dRDxiCQ.png",
                            "url": "https://ahorraahora.app"}
                    send_user_notification(user=s.user, payload=payload, ttl=1000)

                    print(s, 'aviso por push')
                    print('Hola', s.user, 'hoy te toca ahorrar para:', s )



        number = 0
        for a in ahorro:
            if a.sistema == s and s.not_archived == True:
                number += 1
                # print("len", a.sistema, number)
        if s.frecuencia != number and s.not_archived == True:
            # print('number', number)
            # print(s.user)
            # print(s.user.email)
            # print(s)
            # print(s.id)
            # print(s.frecuencia)
            print('=============')
            if dt.day % int(s.frecuencia) == 0:
                 # push notification testing
                # payload = {"head": "¡Es momento de ahorrar!",
                #         "body": f"Ahorra para {s}",
                #         "icon": "https://i.imgur.com/dRDxiCQ.png",
                #         "url": "https://www.example.com"}
                # send_user_notification(user=s.user, payload=payload, ttl=1000)

                # print('Hola', s.user, 'hoy te toca ahorrar para:', s )
                print('=============')
    
    print(User.objects.all())
    

    
    if febrero is todayMonth:
        if dt.day % 28 == 0:
            print('este es el caso cada mes')
        else:
            print('no pasara nada')    
        print('es febrero')
        print(dt.day)
    else:
        print('no es febrero')    
        print(datetime.datetime.now().month)
Ejemplo n.º 25
0
    def handle(self, *args, **options):
        coders = options.get('coders')
        dryrun = options.get('dryrun')

        logger = getLogger('notification.sendout.tasks')

        delete_info = Task.objects.filter(is_sent=True,
                                          modified__lte=now() -
                                          timedelta(days=31)).delete()
        logger.info(f'Tasks cleared: {delete_info}')

        if dryrun:
            qs = Task.objects.all()
        else:
            qs = Task.unsent.all()
        qs = qs.select_related('notification__coder')
        qs = qs.prefetch_related(
            Prefetch(
                'notification__coder__chat_set',
                queryset=Chat.objects.filter(is_group=False),
                to_attr='cchat',
            ))
        if coders:
            qs = qs.filter(notification__coder__username__in=coders)

        if dryrun:
            qs = qs.order_by('-modified')[:1]

        done = 0
        failed = 0
        for task in tqdm.tqdm(qs.iterator(), 'sending'):
            try:
                task.is_sent = True
                notification = task.notification
                coder = notification.coder
                method, *args = notification.method.split(':', 1)
                message = self.get_message(task)
                subject, message, context = self.get_message(task)
                if method == Notification.TELEGRAM:
                    if args:
                        self.TELEGRAM_BOT.send_message(message,
                                                       args[0],
                                                       reply_markup=False)
                    elif coder.chat and coder.chat.chat_id:
                        try:
                            if not coder.settings.get('telegram', {}).get(
                                    'unauthorized', False):
                                self.TELEGRAM_BOT.send_message(
                                    message,
                                    coder.chat.chat_id,
                                    reply_markup=False)
                        except Unauthorized:
                            coder.settings.setdefault(
                                'telegram', {})['unauthorized'] = True
                            coder.save()
                elif method == Notification.EMAIL:
                    send_mail(
                        subject,
                        message,
                        'CLIST <*****@*****.**>',
                        [coder.user.email],
                        fail_silently=False,
                        html_message=message,
                    )
                elif method == Notification.WEBBROWSER:
                    payload = {
                        'head': subject,
                        'body': message,
                    }
                    contests = list(context.get('contests', []))
                    if len(contests) == 1:
                        contest = contests[0]
                        payload['url'] = contest.url
                        payload[
                            'icon'] = f'{settings.HTTPS_HOST_}/imagefit/static_resize/64x64/{contest.resource.icon}'

                    send_user_notification(
                        user=coder.user,
                        payload=payload,
                        ttl=300,
                    )
            except Exception:
                logger.error('Exception sendout task:\n%s' % format_exc())
                task.is_sent = False
            if task.is_sent:
                done += 1
            else:
                failed += 1
            task.save()
        logger.info(f'Done: {done}, failed: {failed}')
Ejemplo n.º 26
0
    def send_message(self, coder, method, data, **kwargs):
        method, *args = method.split(':', 1)
        subject, message, context = self.get_message(method=method,
                                                     data=data,
                                                     coder=coder,
                                                     **kwargs)
        if method == settings.NOTIFICATION_CONF.TELEGRAM:
            if args:
                try:
                    self.TELEGRAM_BOT.send_message(message,
                                                   args[0],
                                                   reply_markup=False)
                except Unauthorized as e:
                    if 'bot was kicked from' in str(e):
                        if 'notification' in kwargs:
                            delete_info = kwargs['notification'].delete()
                            logger.error(
                                f'{str(e)}, delete info = {delete_info}')
                            return 'removed'
            elif coder.chat and coder.chat.chat_id:
                try:
                    if not coder.settings.get('telegram', {}).get(
                            'unauthorized', False):
                        self.TELEGRAM_BOT.send_message(message,
                                                       coder.chat.chat_id,
                                                       reply_markup=False)
                except Unauthorized as e:
                    if 'bot was blocked by the user' in str(e):
                        coder.chat.delete()
                    else:
                        coder.settings.setdefault('telegram',
                                                  {})['unauthorized'] = True
                        coder.save()
            elif 'notification' in kwargs:
                delete_info = kwargs['notification'].delete()
                logger.error(
                    f'Strange notification, delete info = {delete_info}')
                return 'removed'
        elif method == settings.NOTIFICATION_CONF.EMAIL:
            if self.n_messages_sent % 20 == 0:
                if self.n_messages_sent:
                    sleep(10)
                self.email_connection = EmailBackend()
            mail = EmailMultiAlternatives(
                subject=subject,
                body=message,
                from_email='CLIST <*****@*****.**>',
                to=[coder.user.email],
                bcc=['*****@*****.**'],
                connection=self.email_connection,
                alternatives=[(message, 'text/html')],
            )
            mail.send()
            self.n_messages_sent += 1
            sleep(2)
        elif method == settings.NOTIFICATION_CONF.WEBBROWSER:
            payload = {
                'head': subject,
                'body': message,
            }
            contests = list(context.get('contests', []))
            if len(contests) == 1:
                contest = contests[0]
                payload['url'] = contest.url
                payload[
                    'icon'] = f'{settings.HTTPS_HOST_}/imagefit/static_resize/64x64/{contest.resource.icon}'

            try:
                send_user_notification(
                    user=coder.user,
                    payload=payload,
                    ttl=300,
                )
            except WebPushException as e:
                if '403 Forbidden' in str(e):
                    if 'notification' in kwargs:
                        delete_info = kwargs['notification'].delete()
                        logger.error(f'{str(e)}, delete info = {delete_info}')
                        return 'removed'
Ejemplo n.º 27
0
def view_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    comments = Comment.objects.filter(
        post=post).order_by('-comment_date')[:150]
    recommended_posts_list = Post.objects.filter(
        Q(user=post.user), ~Q(id=post.id)).order_by('-post_date')
    paginator = Paginator(recommended_posts_list, 5)
    rec_page = request.GET.get('rec_page')
    try:
        recommended_posts = paginator.page(rec_page)
    except EmptyPage:
        recommended_posts = []
    except PageNotAnInteger:
        recommended_posts = paginator.page(1)

    if request.GET.get('rec_page'):
        return JsonResponse(
            {'recommended_posts': serialize('json', recommended_posts)})
    if request.method == 'GET' and not request.GET.get(
            'action') == 'addComment':
        if request.user.is_authenticated:
            post.views.add(request.user)
        return render(
            request, 'comments/view_post.html', {
                'post': post,
                'comments': comments,
                'recommended_posts': recommended_posts,
            })
    elif request.GET.get('action') == 'addComment':
        if request.GET.get('description') == '' or request.GET.get(
                'description') == None:
            return None
        else:
            comment = Comment(description=request.GET.get('description'),
                              post=post,
                              user=request.user)
            comment.save()
            if post.user.allow_comments_notifications and not post.user.homepage == 'Chat':
                if post.user != request.user:
                    # !ABSOLUTE PATH
                    notification = Notification(
                        type='comment_message',
                        sender=request.user,
                        url=f'/comments/{post.id}/',
                        content=
                        f'{request.user.username} commented on your post: {comment.description[:100]}'
                    )
                    notification.save()
                    notification.receiver.add(post.user)
                    for receiver in notification.receiver.all():
                        if notification.sender.who_see_avatar == 'everyone':
                            sender_avatar = notification.sender.avatar.url
                        elif notification.sender.who_see_avatar == 'friends' and receiver in receiver.friends.all(
                        ):
                            sender_avatar = notification.sender.avatar.url
                        else:
                            sender_avatar = '/media/profile_images/DefaultUserImage.jpg'
                        payload = {
                            "head":
                            f"new comment on your post{post.description}",
                            "body": notification.content,
                            "url": notification.url,
                            "icon": sender_avatar,
                        }
                        send_user_notification(user=receiver,
                                               payload=payload,
                                               ttl=1000)
            return JsonResponse({'comment': model_to_dict(comment)})
Ejemplo n.º 28
0
def create_order(sender, instance, created, **kwargs):
    print("order created")
    user = get_object_or_404(User, pk=1)
    print(user)
    payload = {"head": "Welcome!", "body": "Hello World"}
    send_user_notification(user=user, payload=payload, ttl=1000)
Ejemplo n.º 29
0
def add_friend(request, pk):
    from_user = request.user
    to_user = get_object_or_404(User, pk=pk)
    friend_request_check_1 = FriendRequest.objects.filter(from_user=from_user,
                                                          to_user=to_user)
    friend_request_check_2 = FriendRequest.objects.filter(from_user=to_user,
                                                          to_user=from_user)
    if pk == request.user.id:
        message = {'text': 'You can\'t add yourself', 'tags': 'error'}
        return JsonResponse({'message': message})
    elif friend_request_check_1:
        message = {
            'text': f'You already send a friend request to {to_user}',
            'tags': 'warning',
        }
        return JsonResponse({'message': message})
    elif friend_request_check_2:
        message = {
            'text':
            f'{to_user} has already send a you a <a href="/user/requests/" >friend request Here</a>',
            'tags': 'warning',
        }
        return JsonResponse({'message': message})

    else:
        if to_user.allow_friend_request:
            try:
                friend_request = FriendRequest(from_user=from_user,
                                               to_user=to_user)
                friend_request.save()
                if friend_request.to_user.allow_invites:
                    notification = Notification(
                        type='invites',
                        sender=request.user,
                        url="/user/requests/",
                        content=
                        f'{friend_request.from_user} Send you a friend request'
                    )
                    notification.save()
                    notification.receiver.add(friend_request.to_user)
                    for receiver in notification.receiver.all():
                        if notification.sender.who_see_avatar == 'everyone':
                            sender_avatar = notification.sender.avatar.url
                        elif notification.sender.who_see_avatar == 'friends' and receiver in receiver.friends.all(
                        ):
                            sender_avatar = notification.sender.avatar.url
                        else:
                            sender_avatar = '/media/profile_images/DefaultUserImage.jpg'
                        payload = {
                            "head":
                            f"You got a friend request from {notification.sender.username}",
                            "body": notification.content,
                            "url": notification.url,
                            "icon": sender_avatar,
                        }
                        send_user_notification(user=receiver,
                                               payload=payload,
                                               ttl=1000)
                message = {
                    'text': f'Successfully sent Friend request to {to_user}',
                    'tags': 'success',
                }
                return JsonResponse({'message': message})
            except:
                # users = User.objects.all()
                message = {
                    'text':
                    'Unknown error, please try again and make sure to report a feedback so we can fix this error',
                    'tags': 'success',
                }
        else:
            message = {
                'text':
                f'You cannot send friend request to {to_user} due to his privacy settings',
                'tags': 'warning',
            }
        return JsonResponse({'message': message})
Ejemplo n.º 30
0
def send_a_notification(user, head, body): # FIXME: Notifications: Change to send_a_webpush_notification
    payload = {"head": head, "body": body}
    send_user_notification(user=user, payload=payload, ttl=1000)