Exemplo n.º 1
0
    def save(self, *args, **kwargs):
        """ Due to cross import, can't directly import Utilisateur """
        # 
        if self.send_to_all or self.send_to_inactive:  # or self.send_to_active
            authusers = User.objects.filter(is_superuser=False).only('email')
            users = []
            if self.send_to_inactive:
                for u in authusers:
                    try:
                        if u.profile.get_picture_count() == 0:
                            users.append(u)
                    except ObjectDoesNotExist:
                        pass

            else:
                users = authusers

            from notification import Notification

            notif = Notification(debug=settings.IS_LOCAL)
            notif.set_content(self.subject, self.content)
            for u in users:
                notif.push(u.email)
            notif.send(debug=settings.IS_LOCAL)
        super(MailingList, self).save(*args, **kwargs)
def main():
	# Where is our base folder (the one containing the auto_form.py file)?
	global base_dir 
	base_dir = os.path.normpath(os.path.dirname(os.path.realpath(sys.argv[0])))
	# Parsing arguments
	if len(sys.argv) > 2:
		print "Too many arguments"
		return
	elif len(sys.argv) == 2:
		if sys.argv[1] == "--setup-cron":
			setup_cron()
			return
		elif sys.arg[1] != "--run":
			print "invalid option: %s" % sys.argv[0]
			return
	# We are good to go!
	entities = import_entities()
	#entities = {"285000001": "Gobernacion"}
	current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
	if len(entities) == 0:
		print "%s:: No entities found. Are you sure the file is there?" % current_time
	elif len(entities) < 10:
		print "%s:: Will run against those entities %s" % (current_time,entities)
	else:
		print "%s:: Will run against %d entities" % (current_time,len(entities))
	total = 0;
	report = Report(os.path.join(base_dir,REPORTS_FOLDER))
	for entity_id, entity_name in entities.iteritems():
		print "\n***** Entity %s (%s) *****" % (entity_name, entity_id)
		new_processes = do_one(entity_id)
		if len(new_processes) > 0:
			report.append(entity_id, entity_name, new_processes)
			total += len(new_processes)

	# Notify the result
	notif = None
	if report.created:
		text_body = "Hay %d nuevos contratos disponibles.\nAdjunto el reporte." % total
		notif = Notification(text_body, report.file_path);
	else:
		notif = Notification("No hay nada nuevo hoy.", None);
	notif.send()
	# Display summary
	print "\n"
	print "#############################################################"
	print "# Summary"
	print "# We found %d new processes" % total
	print "# Report avail. at %s" % report.file_path
	print "#############################################################"
Exemplo n.º 3
0
def push_notification():
    """ Send a notification with the device name and status
    """
    if request.method != "POST":
        return MethodNotAllowed(valid_methods=["POST"])

    data = json.loads(request.data)
    device_name = data.get("device_name")
    status = data.get("status")

    if not device_name or not status:
        return BadRequest(description="Parameters <device_name> and <status> are mandatory")

    notification = Notification(API_KEY)
    notification.send(registration_ids=registration_ids, data=data)
    logging.info("Notification sent about {0} with status '{1}'".format(device_name, status))
    return "200 OK"
Exemplo n.º 4
0
def postmessage(request):
    """ Post a message as AJAX """
    remote_addr = request.META.get('REMOTE_ADDR')
    http_referer = request.META.get('HTTP_REFERER')

    L.info("Post a message from {remote} for the page {referer}".format(remote=remote_addr, referer=http_referer))

    if request.method == 'POST':
        if CommentPref.objects.get_preferences().only_registred and not request.user.is_authenticated():
            L.error('ucomment.views.postmessage: Try to post when not authenticated. ')
            return HttpResponseBadRequest('')

        parent = int(request.POST.get('parent'))
        parent = Comment.objects.get(pk=parent) if parent != 0 else None
        content = request.POST['content']
        onwallurl = request.POST.get('onwallurl')

        if content:
            referer = request.POST.get('url')
            if not referer:
                referer = "/"

            if not onwallurl and referer == '/' and onwallurl != '/':
                referer = http_referer.replace('http://%s' % Site.objects.get_current().domain, '')

            # comment = Comment.objects.create(
            comment = Comment.objects.post_comment(
                url=referer,
                message=content,
                raw_html=False,
                user=request.user,
                ip=remote_addr,
                parent=parent
            )

            # Prepare JSON
            data = {
                'username': request.user.username,
                'submission_date': convert_date(timezone.now()),
                'knowuser': True,
                'avatar': request.user.profile.avatar_or_default(),
                'userid': request.user.id,
                'commentcount': Comment.objects.filter(user=request.user, visible=True, moderate=False).only('id').count(),
                'pigstiescount': Picture.objects.filter(user=request.user, trash=False).only('id').count(),
                'content': comment.content,
                'commentid': comment.id,
                'user_authenticated': request.user.is_authenticated(),
                'csrf_token': get_token(request),
            }

            if parent is not None:
                data['parentid'] = parent.id
            else:
                data['parentid'] = comment.id

            # Send a email to all users
            if parent is not None:
                comments = list(Comment.objects.filter((Q(parent=parent) & ~Q(user=request.user))).only('user__email'))
                mails = {}
                for comment in comments:
                    mails[comment.user.email] = ''

                req = RequestContext(request, {
                    'username': request.user.username,
                    'message': comment.content,
                    'url': comment.url
                })

                if not settings.IS_LOCAL:
                    notif = Notification(settings.BANDCOCHON_CONFIG.EmailTemplates.user_comment)
                    for mail in mails.keys():
                        notif.push(mail, req)
                    notif.send()

            # Send Json
            return JsonResponse(data)
        else:
            L.error("ucomment.views.postmessage : Don't have a content message")
    else:
        L.error("ucomment.views.postmessage: Not a POST call :")

    return HttpResponseBadRequest('')