Beispiel #1
0
def notify(request):

    if request.method == 'POST':
        try:
            item = Item.objects.filter(pk=request.POST.get('item_id'))[0]
            sender = request.user
            receiver = item.found_by_user
            response_data = {}

            method = request.POST.get('method')
            message = request.POST.get('message')

            if (method == 'IBF'):
                notification = Notification()
                notification.sender = sender
                notification.receiver = receiver
                notification.message = message
                notification.topic = item
                notification.notification_type = 'CLAIM'
                notification.save()
                item.status = 'CLAIMED'
                item.lost_by_user = sender
                item.save()
                response_data['result'] = 'OK'

            elif (method == 'email'):
                email_subject = 'IBF: Claimed Item'
                email_body = "Hey %s, someone is claiming one of the items you found. Here's his email address so you can get in touchL %s" % (
                    receiver.username, sender.email)

                send_mail(email_subject,
                          email_body,
                          '*****@*****.**', [receiver.email],
                          fail_silently=False)
                item.status = 'CLAIMED'
                item.lost_by_user = sender
                item.save()
                response_data['result'] = 'OK'

            elif (method == 'phone'):
                item.status = 'CLAIMED'
                item.lost_by_user = sender
                item.save()
                response_data['result'] = 'OK'
            if (method == 'leave_message'):
                notification = Notification()
                notification.sender = sender
                notification.receiver = receiver
                notification.message = message
                notification.topic = item
                notification.notification_type = 'CLAIM'
                notification.save()
                response_data['result'] = 'OK'
        except Exception, e:
            traceback.print_exc()
            response_data['result'] = 'ERROR'
Beispiel #2
0
def reply_to_notification(request):

    if request.method == 'POST':
        try:
            old_notification = Notification.objects.filter(
                pk=request.POST.get('notification_pk'))[0]
            sender = request.user
            if old_notification.sender == sender:
                receiver = old_notification.receiver
            else:
                receiver = old_notification.sender
            response_data = {}

            message = request.POST.get('message')
            notification = Notification()
            notification.sender = sender
            notification.receiver = receiver
            notification.notification_type = "CLAIM"
            notification.message = message
            notification.topic = old_notification.topic
            notification.save()
            response_data['result'] = 'OK'
        except Exception, e:
            traceback.print_exc()
            response_data['result'] = 'ERROR'
Beispiel #3
0
def getDepositPaypalReceiptPdf(request, transaction_id):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        transaction = TransactionPaypal.objects.get(id=transaction_id, wallet__profile=profile)

        if transaction.currency == 'USD':
            purchasedCredits = transaction.amount - transaction.feeAmount
            feeAmount = transaction.feeAmount
        elif transaction.currency == 'EUR':
            purchasedCredits = (transaction.amount / transaction.freezedEur) - transaction.feeAmount
            feeAmount = transaction.feeAmount * transaction.freezedEur

        content = {
            'transaction': transaction,
            'purchasedCredits': purchasedCredits,
            'feeAmount': feeAmount,
            'paymentMethod': 'Credit Card',
            'baseUrl': Notification().getEmailBaseUrl()
        }
        pdf = render_to_pdf('deposit_paypal_invoice_template.html', content)
        if pdf:
            return HttpResponse(pdf, content_type='application/pdf')
        return Response({'success': False, 'error': "not.found"})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
Beispiel #4
0
def addOrderForwarderFeedbackToBuyer(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        order = Order.objects.get(id=int(request.data.get('orderId')), service__profile=profile)
        orderFeedback = getOrderFeedback(order, profile)
        orderFeedback.score = request.data.get('score')
        orderFeedback.text = request.data.get('text')
        orderFeedback.save()
        buyerProfile = order.profile
        buyerProfile.feedback = FeedbackManager.updateBuyerProfileFeedback(buyerProfile)
        buyerProfile.save()

        feedbackNotification = Notification()
        feedbackNotification.alert = True
        feedbackNotification.user = buyerProfile.user
        orderLink = "%sbuyer" % (
            feedbackNotification.getEmailLinkBaseUrl()
        )
        alertText = "User %s left a feedback %.2f/5" % (profile.user.username, orderFeedback.score)
        feedbackNotification.alertData = "%s|%s" % (alertText, "/buyer")
        feedbackNotification.save()

        orderSerializer = OrderWithAddressesSerializer(order, context={'request': request})
        return Response({'success': True, 'order': orderSerializer.data})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
Beispiel #5
0
 def post(self, request, *args, **kwargs):
     self.object = self.get_object()
     self.form = self.get_form()
     if request.user.is_authenticated and request.user.was_subscribed:
         if self.form.is_valid():
             for uid in self.form.cleaned_data["users"]:
                 u = User.objects.filter(id=uid).first()
                 if not u:  # Don't use a non existing user
                     continue
                 if PeoplePictureRelation.objects.filter(
                         user=u,
                         picture=self.form.cleaned_data["picture"]).exists(
                         ):  # Avoid existing relation
                     continue
                 PeoplePictureRelation(
                     user=u,
                     picture=self.form.cleaned_data["picture"]).save()
                 if not u.notifications.filter(type="NEW_PICTURES",
                                               viewed=False).exists():
                     Notification(
                         user=u,
                         url=reverse("core:user_pictures",
                                     kwargs={"user_id": u.id}),
                         type="NEW_PICTURES",
                     ).save()
             return super(PictureView, self).form_valid(self.form)
     else:
         self.form.add_error(None,
                             _("You do not have the permission to do that"))
     return self.form_invalid(self.form)
Beispiel #6
0
def send2FASMS(request):
    email = request.data.get('email')
    if email:
        email = email.lower()
    success = False
    try:
        user = get_object_or_404(User, email__iexact=email)
        profile = get_object_or_404(Profile, user=user)
        wallet = Wallet.objects.get(profile=profile)
        TransactionManager.createVerify2FASMSTransaction(
            settings.TWO_FACTOR_SMS_COST, wallet.id)
        profile.setVerificationCode()
        profile.save()
        messageSend = sendVerificationCodeSMS(request,
                                              profile.verificationCode,
                                              profile.mobile)
        success = messageSend
    except ValueError:
        profile.enable2FASMS = False
        notification = Notification()
        notification.alert = True
        notification.user = profile.user
        alertText = "Two factor authentication has been disabled due to low credit"
        notification.alertData = alertText
        notification.save()
        profile.save()
    except Exception as e:
        return Response({
            'success': False,
            'error': {
                'code': 'no.sms.sent',
                'msg': e.message
            }
        })
    return Response({'success': success})
Beispiel #7
0
def cancel(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        order = Order.objects.get(id=request.data.get('orderId'), profile=profile)
        order.state = ORDER_STATUS['cancelled']
        order.save()
        orderSerializer = OrderProtectedSerializer(order, context={'request': request})

        # Notification to forwarder
        orderNotification = Notification()
        orderNotification.email = True
        orderNotification.alert = True
        orderNotification.user = order.service.profile.user
        orderLink = "%sorders/forwarder/%s" % (
            orderNotification.getEmailLinkBaseUrl(),
            order.id
        )
        orderNotification.setEmailData(
            "LWF Order %s" % (order.state),
            "notifications/email/forwarder_order_change_status.html",
            {
                'order': order,
                'orderLink': orderLink
            }
        )
        alertText = "Order #%d changed status to %s" % (order.id, order.state)
        orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/forwarder/", order.id)
        orderNotification.save()

        return Response({'success': True, 'order': orderSerializer.data})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
Beispiel #8
0
def apply_common(request, app):
    if request.method == "POST":
        count = 1
        answers = []
        for q in appmodule.questions:
            answer = Answer(app=app,
                            question=q["text"],
                            text=request.POST.get("q" + unicode(count)))
            answers.append(answer)
            count += 1
        app.status = 1
        app.timezone = request.POST.get('tz')
        app.applicantProfile = request.user.userprofile
        app.applicationDate = datetime.utcnow()
        app.save()
        recruiter = Group.objects.filter(name="Recruiter").first()
        note = Notification(cssClass="success")
        note.content = "New Application from <a href='" + reverse(
            'applications:viewapp', kwargs={
                "app": app.token
            }) + "'>" + unicode(request.user.userprofile) + "</a>."
        note.save()
        note.targetGroup.add(recruiter)

        Answer.objects.bulk_create(answers)

        return redirect("applications:mystatus")

    else:
        return render(request, "apply.html",
                      {"questions": appmodule.questions})
Beispiel #9
0
def postNotification(target, text, cssClass="info"):
    n = Notification(content=text, cssClass=cssClass)
    n.save()

    if type(target) is User:
        n.targetUsers.add(target)
    elif type(target) is Group:
        n.targetGroup.add(target)
Beispiel #10
0
def uploadSelfIDoc(request):
    success = False
    user = request.user
    profile = Profile.objects.get(user=user)
    file = request.data.get('SelfIDocImage')
    if file:
        if type(file) is dict:
            file = file['changingThisBreaksApplicationSecurity']
        if file.find("http://") > -1 or file.find("https://") > -1:
            imgstr = base64.b64encode(requests.get(file).content)
            ext = file.split('/')[-1].split(".")[-1]
            SelfIDocImageName = "%d.%s" % (user.id, ext)
            data = ContentFile(base64.b64decode(imgstr),
                               name=SelfIDocImageName)
            if data.size > settings.MAX_IMAGE_SIZE_UPLOAD:
                return Response({
                    'success': False,
                    'error': 'file.toobig'
                }, 500)
            if profile.SelfIDocImage:
                profile.SelfIDocImage.delete(save=True)
            profile.SelfIDocImage = data
            profile.save()
            success = True
        else:
            datapost = request.data.get('SelfIDocImage')
            if type(datapost) is dict:
                datapost = datapost['changingThisBreaksApplicationSecurity']
            format, imgstr = datapost.split(';base64,')
            ext = format.split('/')[-1]
            SelfIDocImageName = "%d.%s" % (user.id, ext)
            data = ContentFile(base64.b64decode(imgstr),
                               name=SelfIDocImageName)
            if data.size > settings.MAX_IMAGE_SIZE_UPLOAD:
                return Response({
                    'success': False,
                    'error': 'file.toobig'
                }, 500)
            if profile.SelfIDocImage:
                profile.SelfIDocImage.delete(save=True)
            profile.SelfIDocImage = data
            profile.save()
            success = True

    if success:
        # Admin Notification
        adminNotification = Notification()
        adminNotification.email = True
        adminNotification.user = User.objects.get(username="******")
        adminNotification.setEmailData(
            "User uploaded documents",
            "notifications/email/admin_email_user_uploaded_docs.html", {
                'user': user,
                'documentType': 'Selfie Id'
            })

    return Response({'success': False})
Beispiel #11
0
 def patch(self, request, pk, format=None):
     user = self.get_object(pk)
     user.profile.hearts += 1
     user.save()
     notification = Notification(sender=Token.objects.get(
         key=self.request.META['HTTP_AUTHORIZATION'].split(' ', 1)[1]).user,
                                 receiver=user)
     notification.save()
     return Response(status=status.HTTP_200_OK)
Beispiel #12
0
def updateForwarderTrackingInfo(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        order = Order.objects.get(id=request.data.get('orderId'), service__profile=profile)
        try:
            orderTrackingInfo = OrderTrackingInfo.objects.get(
                order=order,
                profile=profile,
                fromForwarder=True,
                trackingStatus=settings.ORDER_TRACKING_INFO_STATUS_CHOICES[1][0]
            )
            orderTrackingInfo.courier = request.data.get('courier')
            orderTrackingInfo.courierOther = request.data.get('courierOther')
            orderTrackingInfo.trn = request.data.get('trn')
            orderTrackingInfo.link = request.data.get('link')
        except OrderTrackingInfo.DoesNotExist:
            orderTrackingInfo = OrderTrackingInfo(
                order=order,
                profile=profile,
                fromForwarder=True,
                courier=request.data.get('courier'),
                courierOther=request.data.get('courierOther'),
                trn=request.data.get('trn'),
                link=request.data.get('link'),
                trackingStatus=settings.ORDER_TRACKING_INFO_STATUS_CHOICES[1][0]
            )
        orderTrackingInfo.save()
        order.save()
        orderSerializer = OrderWithAddressesSerializer(order, context={'request': request})

        # Notification to buyer
        orderNotification = Notification()
        orderNotification.email = True
        orderNotification.alert = True
        orderNotification.user = order.profile.user
        orderLink = "%sorders/buyer/%s" % (
            orderNotification.getEmailLinkBaseUrl(),
            order.id
        )
        orderNotification.setEmailData(
            "LWF Order Tracking Info Updated",
            "notifications/email/buyer_order_tracking_changed.html",
            {
                'order': order,
                'orderTrackingInfo': orderTrackingInfo,
                'orderLink': orderLink
            }
        )
        alertText = "Order #%d tracking info updated" % (order.id)
        orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/buyer/", order.id)
        orderNotification.save()

        return Response({'success': True, 'order': orderSerializer.data})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
Beispiel #13
0
def withdraw(request):
    """
    Request Withdraw from wallet.
    """
    try:
        user = request.user
        currency = request.data.get('currency')
        amount = float(request.data.get('amount'))
        ccAddress = request.data.get('address')
        freezedCurrency = Currency().getCurrency(currency)
        if not freezedCurrency:
            return Response({'success': False, 'error': 'currency.notvalid'})
        cryptoAmount = amount / freezedCurrency.usd

        #create withdrawrequest
        withdrawRequest = WithdrawRequest()
        withdrawRequest.user = user
        withdrawRequest.requestedCurrency = currency
        withdrawRequest.requestedAmount = amount
        withdrawRequest.requestedCcAddress = ccAddress
        withdrawRequest.freezedUsd = freezedCurrency.usd
        withdrawRequest.freezedEur = freezedCurrency.eur
        withdrawRequest.save()

        #create notification
        protocol = 'http'
        if settings.FRONTEND_SSL:
            protocol = 'https'
        confirmationLink = "%s://%s:%s/withdrawConfirm/%s" % (
            protocol, settings.FRONTEND_HOST, settings.FRONTEND_PORT,
            str(withdrawRequest.hash))
        notification = Notification()
        notification.email = True
        notification.user = user
        notification.setEmailData(
            "Withdraw request comfirm",
            "notifications/email/withdraw_request_confirm_email.html", {
                'user': user,
                'confirmation_link': confirmationLink,
                'currency': currency,
                'amount': amount,
                'cryptoAmount': cryptoAmount,
                'freezedUsd': freezedCurrency.usd,
                'freezedEur': freezedCurrency.eur
            })

        withdrawRequest.notification = notification
        withdrawRequest.save()

        return Response({'success': True})
    except Profile.DoesNotExist:
        return Response({'success': False, 'error': 'profile.notfound'})
    except Wallet.DoesNotExist:
        return Response({'success': False, 'error': 'wallet.notfound'})
Beispiel #14
0
 def save(self):
     if not self.is_moderated:
         for user in (RealGroup.objects.filter(
                 id=settings.SITH_GROUP_COM_ADMIN_ID).first().users.all()):
             if not user.notifications.filter(type="MAILING_MODERATION",
                                              viewed=False).exists():
                 Notification(
                     user=user,
                     url=reverse("com:mailing_admin"),
                     type="MAILING_MODERATION",
                 ).save()
     super(Mailing, self).save()
Beispiel #15
0
def adminAjaxPostChatMessage(request):
    r = {'success': False, 'chat': None}
    adminUser = User.objects.get(username="******")  #EMULATE ADMIN USER
    try:
        chatId = int(request.POST['chatId'])
        chat = Chat.objects.get(id=chatId)
        message = request.POST['message']
        chatMessage = ChatMessage(sender=adminUser, text=message, chat=chat)
        chatMessage.save()

        issue = Issue.objects.get(chat=chat)

        issueNotificationBuyer = Notification()
        issueNotificationBuyer.alert = True
        issueNotificationBuyer.user = issue.order.profile.user
        alertText = "Admin sent a new message"
        issueLink = "%sissue/%d" % (
            issueNotificationBuyer.getEmailLinkBaseUrl(), issue.id)
        issueNotificationBuyer.alertData = "%s|%s" % (alertText, issueLink)
        issueNotificationBuyer.save()

        issueNotificationForwarder = Notification()
        issueNotificationForwarder.alert = True
        issueNotificationForwarder.user = issue.order.service.profile.user
        alertText = "Admin sent a new message"
        issueLink = "%sissue/%d" % (
            issueNotificationForwarder.getEmailLinkBaseUrl(), issue.id)
        issueNotificationForwarder.alertData = "%s|%s" % (alertText, issueLink)
        issueNotificationForwarder.save()

        chatSerializer = ChatSerializer(chat, context={'request': request})
        chatMessageSerializer = ChatMessageSerializer(
            chatMessage, context={'request': request})
        r['chat'] = chatSerializer.data
        r['message'] = chatMessageSerializer.data
        r['success'] = True
    except Exception, ex:
        r['error'] = "%s" % (traceback.format_exc())
Beispiel #16
0
def signup(request):
    name = request.data.get("name")
    surname = request.data.get("surname")
    email = request.data.get("email")
    if email:
        email = email.lower()
    username = request.data.get("username")
    if username:
        username = username.lower()
    error = checkUserAlreadyRegistered(email, username)
    if error:
        return Response({'success': False, 'error': error})
    user = User.objects.create_user(username,
                                    email,
                                    email,
                                    last_login=timezone.now())
    user.first_name = name
    user.last_name = surname
    user.is_active = False
    user.save()
    profile = Profile()
    profile.user = user
    profile.setActivationKey()
    profile.setKeyExpires()
    profile.save()
    createDefaultWallets(profile)

    #set default avatar
    try:
        imageData = getDefaultAvatarImageData()
        ext = settings.DEFAULT_AVATAR_IMAGE_PATH.split('/')[-1].split(".")[-1]
        avatarImageName = "%d.%s" % (profile.user.id, ext)
        data = ContentFile(imageData, name=avatarImageName)
        profile.avatarImage = data
        profile.save()
    except:
        pass

    # Admin Notification
    adminNotification = Notification()
    adminNotification.email = True
    adminNotification.user = User.objects.get(username="******")
    adminNotification.setEmailData(
        "New LWF user registered",
        "notifications/email/admin_email_user_registered.html", {
            'user': user,
        })
    Thread(target=adminNotification.process, args=(), kwargs={}).start()
    sendRegistrationEmail(profile)
    return Response({'success': True})
Beispiel #17
0
 def process(self, parent, owner, files):
     notif = False
     try:
         if self.cleaned_data["folder_name"] != "":
             folder = SithFile(parent=parent,
                               name=self.cleaned_data["folder_name"],
                               owner=owner)
             folder.clean()
             folder.save()
             notif = True
     except Exception as e:
         self.add_error(
             None,
             _("Error creating folder %(folder_name)s: %(msg)s") % {
                 "folder_name": self.cleaned_data["folder_name"],
                 "msg": repr(e)
             },
         )
     for f in files:
         new_file = SithFile(
             parent=parent,
             name=f.name,
             file=f,
             owner=owner,
             is_folder=False,
             mime_type=f.content_type,
             size=f.size,
         )
         try:
             new_file.clean()
             new_file.save()
             notif = True
         except Exception as e:
             self.add_error(
                 None,
                 _("Error uploading file %(file_name)s: %(msg)s") % {
                     "file_name": f,
                     "msg": repr(e)
                 },
             )
     if notif:
         for u in (RealGroup.objects.filter(
                 id=settings.SITH_GROUP_COM_ADMIN_ID).first().users.all()):
             if not u.notifications.filter(type="FILE_MODERATION",
                                           viewed=False).exists():
                 Notification(
                     user=u,
                     url=reverse("core:file_moderation"),
                     type="FILE_MODERATION",
                 ).save()
Beispiel #18
0
    def form_valid(self, form):
        resp = super(UVCommentReportCreateView, self).form_valid(form)

        # Send a message to moderation admins
        for user in (RealGroup.objects.filter(
                id=settings.SITH_GROUP_PEDAGOGY_ADMIN_ID).first().users.all()):
            if not user.notifications.filter(type="PEDAGOGY_MODERATION",
                                             viewed=False).exists():
                Notification(
                    user=user,
                    url=reverse("pedagogy:moderation"),
                    type="PEDAGOGY_MODERATION",
                ).save()

        return resp
    def emit(self, record):
        try:
            Notification = core.models.notification.Notification
        except core.models.notification.Notification.DoesNotExist:
            from core.models import Notification

        Notification(message=record.msg,
                     request=record.request_body,
                     method=record.method,
                     url=record.url,
                     module=record.module,
                     function=record.funcName,
                     level=record.levelname,
                     status_code=record.status_code,
                     additional_data=record.extra).create()
Beispiel #20
0
def submit(request):
    if not isDropbears(request.user):
        return render(request, 'error.html', {
            'title': '403 - Forbidden',
            'description': 'You are not a member.'
        })
    c = {}
    if request.method == "POST":
        error = False
        new = SRPRequest()
        new.owner = request.user.userprofile

        link = request.POST.get('link', False)
        if link:
            new.killID = link.split("/")[-2]
            if SRPRequest.objects.filter(killID=new.killID).exists():
                error = True
                return render(request, "submit.html", c)
            shipID, shipName, pilot, corp, value = getKillInformation(
                new.killID)
        if not link or not shipID:
            error = True
        else:
            new.value = int(float(value))
            new.shipID = shipID
            new.fc = request.POST.get('fc', '')
            new.aar = request.POST.get('aar', '')
            new.learned = request.POST.get('learned', '')
            new.suggestions = request.POST.get('suggestions', '')
            new.pilot = pilot
            new.corp = corp
            new.ship = shipName
            new.save()
            c["message"] = "Successfully added kill #" + new.killID
            finance = Group.objects.filter(name="Finance").first()
            note = Notification(cssClass="info")
            note.content = "New <a href='" + reverse(
                'srp:viewsrp', kwargs={"killID": new.killID}
            ) + "'>SRP request for a " + shipName + "</a> added by <a href='" + reverse(
                'core:playerProfile',
                kwargs={"profileName": slugify(request.user.userprofile)
                        }) + "'>" + unicode(request.user.userprofile) + "</a>."
            note.save()
            note.targetGroup.add(finance)

        c["error"] = error

    return render(request, "submit.html", c)
Beispiel #21
0
def ticketSubmit(request):
    if not isDropbears(request.user):
        return render(request, 'error.html', {
            'title': '403 - Forbidden',
            'description': 'You are not a member.'
        })
    c = {}
    if request.method == "POST":
        error = False
        new = Ticket()
        anonymous = request.POST.get("anonymous") == "on"
        new.author = None if anonymous else request.user.userprofile

        new.title = request.POST.get('title', '')
        new.text = request.POST.get('text', '')
        new.category = int(request.POST.get('category', 0))
        sample = string.lowercase + string.digits
        new.token = ''.join(random.sample(sample, 8))
        new.save()
        c["message"] = "Successfully added <a href='" + reverse(
            'helpdesk:viewticket', kwargs={"token": new.token}
        ) + "'>Ticket #" + str(
            new.id
        ) + " \"" + new.title + "\"</a>. If you chose to submit anonymously, save this link as it's your only way to access it."

        director = Group.objects.filter(name="Director").first()
        note = Notification(cssClass="info")
        if anonymous:
            note.content = "Someone added a new Ticket: <a href='" + reverse(
                'helpdesk:viewticket',
                kwargs={"token": new.token}) + "'>\"" + new.title + "\"</a>"
        else:
            note.content = "<a href='" + reverse(
                'core:playerProfile',
                kwargs={"profileName": slugify(request.user.userprofile)}
            ) + "'>" + unicode(
                new.author) + "</a> added a new Ticket: <a href='" + reverse(
                    'helpdesk:viewticket', kwargs={
                        "token": new.token
                    }) + "'>\"" + new.title + "\"</a>"
        note.save()
        note.targetGroup.add(director)

        c["error"] = error

    c["users"] = Group.objects.filter(name="Director").first().user_set.all()

    return render(request, "ticketsubmit.html", c)
Beispiel #22
0
def notifications_job(request):
    data = None
    log = ''
    try:
        match_search = ItemsMatchView()
        pre_reg_items = PreRegisteredItem.objects.filter(lost=True)

        log += "<p>=========================</p>"
        log += "<p>======= START JOB =======</p>"

        for item in pre_reg_items:
            log += "<p>== Searching matches for item:</p>"
            log += "<p>______Title: " + item.title + "</p>"
            log += "<p>______Category: " + item.category + "</p>"
            log += "<p>______Created on: " + str(item.created_at) + "</p>"
            t = request.GET.copy()
            t.update({'q': string.replace(item.tags, ' ', '+')})
            t.update({'category': item.category})
            t.update({'unique_id': item.unique_id})
            t.update({'start_date': str(item.created_at).split(' ')[0]})
            request.GET = t
            match_results = match_search.get(request)
            for match in match_results:
                if not Notification.objects.filter(notification_type="MATCH",
                                                   match=item,
                                                   topic=match.object):
                    log += "<p>== Creating notification for match:</p>"
                    log += "<p>______Title: " + match.object.title + "</p>"
                    log += "<p>______Category: " + match.object.category + "</p>"
                    log += "<p>______Created on: " + str(
                        match.object.date_field) + "</p>"

                    notification = Notification()
                    notification.receiver = item.owner
                    notification.notification_type = "MATCH"
                    notification.message = "This item matched your lost "
                    notification.topic = match.object
                    notification.match = item
                    notification.save()

                    log += "<p>== Notification Created</p>"
                    log += "<p>=======================</p>"
        log += "<p><p>========= END JOB =======</p>"
        log += "<p>=========================</p>"

    except Exception, e:
        traceback.print_exc()
Beispiel #23
0
 def form_valid(self, form):
     self.object = form.save()
     if form.cleaned_data[
             "automoderation"] and self.request.user.is_in_group(
                 settings.SITH_GROUP_COM_ADMIN_ID):
         self.object.moderator = self.request.user
         self.object.is_moderated = True
         self.object.save()
     else:
         for u in (RealGroup.objects.filter(
                 id=settings.SITH_GROUP_COM_ADMIN_ID).first().users.all()):
             if not u.notifications.filter(type="NEWS_MODERATION",
                                           viewed=False).exists():
                 Notification(
                     user=u,
                     url=reverse("com:news_admin_list"),
                     type="NEWS_MODERATION",
                 ).save()
     return super(NewsCreateView, self).form_valid(form)
Beispiel #24
0
def follow_user(request, username):
    logged_user = Account.objects.get(id=request.session.get('user_id'))
    try:
        to_follow = Account.objects.get(username=username)
    except Exception:
        return Http404()

    following_rel = FollowersModel.objects.filter(
        user=logged_user, following=to_follow)
    is_following = True if following_rel else False

    if is_following:
        FollowersModel.unfollow(logged_user, to_follow)
        is_following = False
    else:
        FollowersModel.follow(logged_user, to_follow)
        is_following = True
        Notification(
            notification_type=3, to_user=to_follow, from_user=logged_user).save()

    return JsonResponse({'is_following': is_following})
Beispiel #25
0
def getBuyerOrderPaymentReportPdf(request, order_id):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        order = Order.objects.get(
            id=order_id,
            profile=profile
        )
        transaction = PaymentTransaction.objects.get(order=order, inWallet__profile=profile)
        content = {
            'transaction': transaction,
            'totalPaid': transaction.amount + transaction.feeAmount,
            'paymentMethod': 'Bundle Credits',
            'baseUrl': Notification().getEmailBaseUrl()
        }
        pdf = render_to_pdf('order_buyer_report_template.html', content)
        if pdf:
            return HttpResponse(pdf, content_type='application/pdf')
        return Response({'success': False, 'error': "not.found"})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
Beispiel #26
0
def repatriate_item(request):
    response_data = {}
    if request.method == 'POST':
        try:
            item_id = request.POST.get('item_id')
            item = Item.objects.filter(pk=item_id)[0]
            item.status = "PREREPATRIATED"
            item.save()

            notification = Notification()
            notification.sender = item.found_by_user
            notification.receiver = item.lost_by_user
            notification.message = item.found_by_user.username + ' wants to mark this item (subject of this conversation) as "Repatriated". If you agreed with the finder on a metting, then please accept his request.'

            notification.topic = item
            notification.notification_type = 'ACCEPT'
            notification.save()
            response_data['result'] = 'OK'
        except Exception, e:
            traceback.print_exc()
            response_data['result'] = 'ERROR'
    def test_for_notification_get_when_no_unread_notification_for_that_user(
            self):
        """
        Unit test for notification get api for no unread notification
        """

        # Setup
        notification = Notification(user=self.user,
                                    event=self.event,
                                    message="test message",
                                    has_read=True)
        notification.save()

        # Run
        response = self.client.get("/core/notification/",
                                   content_type="application/json",
                                   HTTP_AUTHORIZATION="Bearer {}".format(
                                       self.token))

        # Assert
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['data'], [])
    def test_notification_api_patch_for_valid_data(self):
        """
        Unit test for notification patch api with valid data
        """

        # Setup
        json_content = {"notification_ids": [1]}
        notification = Notification(user=self.user,
                                    event=self.event,
                                    message="test message",
                                    has_read=False)
        notification.save()

        # Run
        response = self.client.patch("/core/notification/",
                                     data=json_content,
                                     content_type="application/json",
                                     HTTP_AUTHORIZATION="Bearer {}".format(
                                         self.token))

        # Assert
        self.assertEqual(response.status_code, 200)
    def test_for_notification_get_data_when_unread_notification(self):
        """
        Unit test for notification get api for unread notification
        """

        # Setup
        notification = Notification(user=self.user,
                                    event=self.event,
                                    message="test message",
                                    has_read=False)
        notification.save()

        # Run
        response = self.client.get("/core/notification/",
                                   content_type="application/json",
                                   HTTP_AUTHORIZATION="Bearer {}".format(
                                       self.token))

        # Assert
        self.assertEqual(response.data['data'][0]['message'],
                         notification.message)
        self.assertEqual(response.data['data'][0]['id'], notification.id)
Beispiel #30
0
def getWithdrawReceiptPdf(request, transaction_id):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        transaction = WithdrawTransaction.objects.get(id=transaction_id, user=user)
        withdrawRequest = WithdrawRequest.objects.get(transaction=transaction, user=user)
        bcToCrypto = 1 / withdrawRequest.freezedUsd
        cryptoAmount = transaction.amount / withdrawRequest.freezedUsd

        content = {
            'transaction': transaction,
            'withdrawRequest': withdrawRequest,
            'bcToCrypto': bcToCrypto,
            'cryptoAmount': cryptoAmount,
            'baseUrl': Notification().getEmailBaseUrl()
        }
        pdf = render_to_pdf('withdraw_crypto_invoice_template.html', content)
        if pdf:
            return HttpResponse(pdf, content_type='application/pdf')
        return Response({'success': False, 'error': "not.found"})
    except Exception as e:
        return Response({'success': False, 'error': e.message})