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})
def notify_followers_new_content(course): followers = UserProfile.query(UserProfile.followed_courses == course) for follower in followers: notify = Notification(text='Novo conteúdo adicionado %s' %(course.get().title), profile=follower.key, ntype='icon-warning-sign' ) notify.put()
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)
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)
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'
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})
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)
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})
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)
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})
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()
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()
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)
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_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 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()
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})
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()
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 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 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'})
def createIssue(request): try: order = Order.objects.get(id=request.data.get('order')) if checkExistingIssue(order): raise ValueError("Issue Already exists") user = request.user profile = Profile.objects.get(user=user) chat = createChat(order) issueSerializer = IssueProtectedSerializer(data=request.data) if issueSerializer.is_valid(): request.data['profile'] = profile request.data['order'] = order request.data['chat'] = chat issue = issueSerializer.create(request.data) issue.save() issueNotification = Notification() issueNotification.alert = True if profile == order.profile: issueNotification.user = issue.order.service.profile.user alertText = "User %s opened an issue" % issue.order.profile.user.username else: issueNotification.user = issue.order.profile.user alertText = "User %s opened an issue" % issue.order.service.profile.user.username issueLink = "%sissue/%d" % ( issueNotification.getEmailLinkBaseUrl(), issue.id ) issueNotification.alertData = "%s|%s|%d" % (alertText, "/issue", issue.id) issueNotification.save() return Response({'success': True, 'issueId': issue.id}, status=status.HTTP_201_CREATED) else: return Response({'success': False, 'errors': issueSerializer.errors}) except Profile.DoesNotExist: return Response({'success': False, 'error': 'profile.notfound'}) except Exception as e: return Response({'success': False, 'errors': e.message})
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()
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)
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 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})
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})
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)
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})
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})
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'
def save(self, *args, **kwargs): if not self.date: self.date = timezone.now() self.full_clean() if not self.is_validated: self.customer.amount += self.amount self.customer.save() self.is_validated = True if self.customer.user.preferences.notify_on_refill: Notification( user=self.customer.user, url=reverse( "core:user_account_detail", kwargs={ "user_id": self.customer.user.id, "year": self.date.year, "month": self.date.month, }, ), param=str(self.amount), type="REFILLING", ).save() super(Refilling, self).save(*args, **kwargs)
def sendPasswordResetEmail(profile): protocol = 'http' profile.setKeyExpires() profile.save() if settings.FRONTEND_SSL: protocol = 'https' confirmationLink = "%s://%s:%s/password-recovery/reset/%s" % ( protocol, settings.FRONTEND_HOST, settings.FRONTEND_PORT, str(profile.activationKey)) emailId = str(uuid.uuid4()) now = datetime.now() headers = { "Date": "%s, %s %s %s %s:%s:%s -0000" % (datetime.strftime(now, "%a"), datetime.strftime(now, "%d"), datetime.strftime(now, "%b"), datetime.strftime(now, "%Y"), datetime.strftime(now, "%H"), datetime.strftime( now, "%M"), datetime.strftime(now, "%S")), "Message-ID": emailId } mailBody = render_to_string( 'password_reset_mail.html', { 'confirmation_link': confirmationLink, 'user': profile.user, 'validityHours': settings.PROFILE_ACTIVATION_KEY_EXPIRE_TIMEOUT, 'baseUrl': Notification().getEmailBaseUrl() }) emailMessage = EmailMessage(subject='Reset your LWF password', headers=headers, body=mailBody, from_email=settings.EMAIL_DEFAULT_FROM, to=[profile.user.email]) emailMessage.content_subtype = "html" # Main content is now text/html emailMessage.send()
def addNewsLetterEmail(request): email = request.data.get("email") if email: email = email.lower() try: NewsLetterEmailAddress.objects.get(email__iexact=email) except NewsLetterEmailAddress.DoesNotExist: newEmail = NewsLetterEmailAddress() newEmail.email = email newEmail.save() adminNotification = Notification() adminNotification.email = True adminNotification.user = User.objects.get(username="******") adminNotification.setEmailData( "New user signed for newsletter", "notifications/email/newsletter_email_registered.html", { 'email': email, }) Thread(target=adminNotification.process, args=(), kwargs={}).start() return Response({ 'success': True, })
def get_notifications(self): notifications = Notification.query(Notification.profile==self.logged.key).order(-Notification.created_at).fetch(5) return self.render_json({'notifications': [n.to_dict() for n in notifications]})
def notify_follow(course, user): notify = Notification(text='%s começou a seguir o curso %s' %(user.full_name, course.title), profile=course.owner, ntype='icon-warning-sign' ) notify.put()
def respond_to_repatriation(request): response_data = {} if request.method=='POST': try: notification = Notification.objects.filter(pk=request.POST.get('notification_id'))[0] response = request.POST.get('response') notification = Notification.objects.filter(pk=request.POST.get('notification_id'))[0] item = Item.objects.filter(pk=notification.topic.pk)[0] notification.notification_type = "CLAIM" new_notification = Notification() new_notification.sender = request.user new_notification.receiver = notification.sender if response == 'true': new_notification.message = "Congratulations!! "+notification.topic.title + " has been repatriated." new_notification.notification_type = 'CLAIM' item.status = "REPATRIATED" item.save() else: new_notification.message = request.user.username + " and you have to agree how the repatriation will occur. Once this is done, you can request a 'Repatriated' status change on "+notification.topic.title new_notification.notification_type = 'CLAIM' item.status = "CLAIMED" item.save() new_notification.topic = item new_notification.notification_type = 'CLAIM' new_notification.save() response_data['message'] = new_notification.message notification.save() response_data['result'] = 'OK' except Exception, e: traceback.print_exc() response_data['result'] = 'ERROR'
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'
def add_notification(self): notify = Notification(text=self.request.get('text'), profile=self.logged.key, ntype='icon-comment') notify.put() return self.render_json({'success': True})