예제 #1
0
def importcsv(filerows, welcomeemail, defaults, newsletter, user):
	columns = None
	subscribers_imported = 0
	most_recent_issue = newsletter.get_most_recent()
	if defaults['type']:
		defaults['subscriber_type_id'] = defaults['type'].pk
	countries = Country.objects.all()
	country_ids = []
	for country in countries:
		country_ids.append(country.pk)
	for row in filerows:
		try:
			# Get column names from first row
			if (columns == None):
				columns = row
				if 'email' not in columns:
					raise RgImportCsvException('You must specify an email field')
				continue
			
			# Create new user
			newsubscriber = NewsletterSubscriber()
			
			# Process row
			i = 0;
			send_most_recent = defaults['send_most_recent']
			send_email = False
			for cell in row:
				colname = columns[i]
				if colname == 'email':
					stringval(colname, cell, newsubscriber, defaults)
					if not email_re.match(newsubscriber.email):
						raise SkipRowException
					if NewsletterSubscriber.objects.filter(email=newsubscriber.email, newsletter=newsletter).count() > 0:
						raise SkipRowException   # This email address is already subscribed
					if newsletter.pk == 1:
						users_count = User.objects.filter(is_active=True, email=newsubscriber.email, email_newsletter_optin=True).count()
						if users_count > 0:
							raise SkipRowException   # This email address is already subscribed by having User.email_newsletter_optin True
				elif colname == 'first_name':
					stringval(colname, cell, newsubscriber, defaults)
				elif colname == 'last_name':
					stringval(colname, cell, newsubscriber, defaults)
				elif colname == 'company':
					stringval(colname, cell, newsubscriber, defaults)
				elif colname == 'type':
					types = SubscriberType.objects.all()
					type_ids = []
					for type in types:
						type_ids.append(type.pk)
					numval('subscriber_type_id', cell, newsubscriber, defaults, type_ids)
				elif colname == 'country':
					if cell in country_ids:
						stringval('country_id', cell, newsubscriber, defaults)
					else:
						newsubscriber.country = defaults['country']
				elif colname == 'details_verified':
					boolval(colname, cell, newsubscriber, defaults)
				elif colname == 'send_most_recent':
					data = cell.strip()
					if data == 'true':
						send_most_recent = True
					elif data == '1':
						send_most_recent = True
					elif data == 'yes':
						send_most_recent = True
					if data == 'false':
						send_most_recent = False
					elif data == '0':
						send_most_recent = False
					elif data == 'no':
						send_most_recent = False
				elif colname == 'send_email':
					data = cell.strip()
					if data == 'true':
						send_email = True
					elif data == '1':
						send_email = True
					elif data == 'yes':
						send_email = True
				else:
					pass   # Unknown column, ignore
				# Increment column and do the loop again
				i += 1
	
			# Apply any unapplied defaults
			if 'type' not in columns:
				if 'subscriber_type_id' in defaults:
					newsubscriber.subscriber_type_id = defaults['subscriber_type_id']
			if 'details_verified' not in columns:
				if 'details_verified' in defaults:
					newsubscriber.details_verified = defaults['details_verified']
			if 'country' not in columns:
				if 'country' in defaults:
					newsubscriber.country = defaults['country']
	
			# Set some other important attributes
			newsubscriber.newsletter = newsletter
			newsubscriber.subscribed_date = datetime.now()
			newsubscriber.active = True
	
			# And finally...
			newsubscriber.save()
	
			# Send welcome email, if applicable
			if (welcomeemail['importaction'] == '1' or (welcomeemail['importaction'] == '3' and send_email)):
				message = EmailMessage()
				message.subject = welcomeemail['subject']
				try:
					message.body = welcomeemail['body'].format(
						newsletter=newsletter,
						subscriber=newsubscriber)
				except Exception:
					newsubscriber.delete()
					raise RgImportCsvException('Welcome email format is invalid')
				message.from_address = welcomeemail['from_address']
				message.reply_address = welcomeemail['reply_address']
				message.from_name = welcomeemail['from_name']
				message.sender = user
				message.html = welcomeemail['html']
				message.status = -1
				message.save()
				recipient = EmailRecipient()
				recipient.message = message
				recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name
				recipient.to_address = newsubscriber.email
				recipient.save()
				message.status = 0
				message.save()
			
			# Send most recent newsletter, if applicable
			if send_most_recent:
				recipient = EmailRecipient()
				recipient.message = most_recent_issue
				recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name
				recipient.to_address = newsubscriber.email
				recipient.save()
	
			# Increment counter
			subscribers_imported += 1
		except SkipRowException:
			continue   # Skip this row

	# Tell the most recent issue to send with new subscribers,
	# if applicable
	most_recent_issue.status = 0
	most_recent_issue.save()
	return subscribers_imported
예제 #2
0
def importcsv(filerows, welcomeemail, defaults, newsletter, user):
    columns = None
    subscribers_imported = 0
    most_recent_issue = newsletter.get_most_recent()
    if defaults['type']:
        defaults['subscriber_type_id'] = defaults['type'].pk
    countries = Country.objects.all()
    country_ids = []
    for country in countries:
        country_ids.append(country.pk)
    for row in filerows:
        try:
            # Get column names from first row
            if (columns == None):
                columns = row
                if 'email' not in columns:
                    raise RgImportCsvException('You must specify an email field')
                continue

            # Create new user
            newsubscriber = NewsletterSubscriber()

            # Process row
            i = 0
            send_most_recent = defaults['send_most_recent']
            send_email = False
            for cell in row:
                colname = columns[i]
                if colname == 'email':
                    stringval(colname, cell, newsubscriber, defaults)
                    if not email_re.match(newsubscriber.email):
                        raise SkipRowException
                    if NewsletterSubscriber.objects.filter(email=newsubscriber.email,
                                                           newsletter=newsletter).count() > 0:
                        raise SkipRowException  # This email address is already subscribed
                    if newsletter.pk == 1:
                        users_count = User.objects.filter(is_active=True, email=newsubscriber.email,
                                                          email_newsletter_optin=True).count()
                        if users_count > 0:
                            raise SkipRowException  # This email address is already subscribed by having User.email_newsletter_optin True
                    if newsletter.pk == 5:
                        users_count = User.objects.filter(is_active=True, email=newsubscriber.email,
                                                          email_careers_newsletter_AU_optin=True).count()
                        if users_count > 0:
                            raise SkipRowException  # This email address is already subscribed by having User.email_newsletter_optin True
                elif colname == 'first_name':
                    stringval(colname, cell, newsubscriber, defaults)
                elif colname == 'last_name':
                    stringval(colname, cell, newsubscriber, defaults)
                elif colname == 'company':
                    stringval(colname, cell, newsubscriber, defaults)
                elif colname == 'type':
                    types = SubscriberType.objects.all()
                    type_ids = []
                    for type in types:
                        type_ids.append(type.pk)
                    numval('subscriber_type_id', cell, newsubscriber, defaults, type_ids)
                elif colname == 'country':
                    if cell in country_ids:
                        stringval('country_id', cell, newsubscriber, defaults)
                    else:
                        newsubscriber.country = defaults['country']
                elif colname == 'details_verified':
                    boolval(colname, cell, newsubscriber, defaults)
                elif colname == 'send_most_recent':
                    data = cell.strip()
                    if data == 'true':
                        send_most_recent = True
                    elif data == '1':
                        send_most_recent = True
                    elif data == 'yes':
                        send_most_recent = True
                    if data == 'false':
                        send_most_recent = False
                    elif data == '0':
                        send_most_recent = False
                    elif data == 'no':
                        send_most_recent = False
                elif colname == 'send_email':
                    data = cell.strip()
                    if data == 'true':
                        send_email = True
                    elif data == '1':
                        send_email = True
                    elif data == 'yes':
                        send_email = True
                else:
                    pass  # Unknown column, ignore
                # Increment column and do the loop again
                i += 1

            # Apply any unapplied defaults
            if 'type' not in columns:
                if 'subscriber_type_id' in defaults:
                    newsubscriber.subscriber_type_id = defaults['subscriber_type_id']
            if 'details_verified' not in columns:
                if 'details_verified' in defaults:
                    newsubscriber.details_verified = defaults['details_verified']
            if 'country' not in columns:
                if 'country' in defaults:
                    newsubscriber.country = defaults['country']

            # Set some other important attributes
            newsubscriber.newsletter = newsletter
            newsubscriber.subscribed_date = datetime.now()
            newsubscriber.active = True

            # And finally...
            newsubscriber.save()

            # Send welcome email, if applicable
            if (welcomeemail['importaction'] == '1' or (welcomeemail['importaction'] == '3' and send_email)):
                message = EmailMessage()
                message.subject = welcomeemail['subject']
                try:
                    message.body = welcomeemail['body'].format(
                        newsletter=newsletter,
                        subscriber=newsubscriber)
                except Exception:
                    newsubscriber.delete()
                    raise RgImportCsvException('Welcome email format is invalid')
                message.from_address = welcomeemail['from_address']
                message.reply_address = welcomeemail['reply_address']
                message.from_name = welcomeemail['from_name']
                message.sender = user
                message.html = welcomeemail['html']
                message.status = -1
                message.save()
                recipient = EmailRecipient()
                recipient.message = message
                recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name
                recipient.to_address = newsubscriber.email
                recipient.save()
                message.status = 0
                message.save()

            # Send most recent newsletter, if applicable
            if send_most_recent:
                recipient = EmailRecipient()
                recipient.message = most_recent_issue
                recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name
                recipient.to_address = newsubscriber.email
                recipient.save()

            # Increment counter
            subscribers_imported += 1
        except SkipRowException:
            continue  # Skip this row

    # Tell the most recent issue to send with new subscribers,
    # if applicable
    most_recent_issue.status = 0
    most_recent_issue.save()
    return subscribers_imported
예제 #3
0
def api(request):
	if 'api' not in request.GET:
		return HttpResponse("-1")
	elif request.GET['api'] != API_SECRET:
		return HttpResponse("-1")
	elif 'action' in request.GET:
		try:
			n = Newsletter.objects.get(pk=request.GET['newsletter'])
		except Newsletter.DoesNotExist:
			return HttpResponse("-1")
		try:
			if request.GET['action'] == 'subscribe':
				email = unquote_plus(request.GET['email']).strip()
				try:
					validate_email(email)
				except ValidationError:
					valid_email = False
				else:
					valid_email = True
				if not valid_email:
					return HttpResponse("C")  # Invalid email
				c = NewsletterSubscriber.objects.filter(email=email, newsletter=n, active=True).count()
				if c != 0:
					return HttpResponse("B")  # Already subscribed
				if n.pk == 1:
					users_count = User.objects.filter(is_active=True, email=email, email_newsletter_optin=True).count()
					if users_count > 0:
						return HttpResponse("B")  # Already subscribed
				# They've tried to subscribe already, so resend confirmation email
				p = PendingNewsletterSubscriber.objects.filter(email=email, newsletter=n)
				if p:
					p = p[0]
				else:
					p = PendingNewsletterSubscriber()
					p.email = email
					p.uniqid = md5(SECRET_KEY + email + n.name).hexdigest()
					p.newsletter = n
					p.save()
				confirm_url = n.confirm_url + "pid=" + str(p.pk) + "&key=" + p.uniqid
				message = EmailMessage()
				message.subject = n.confirm_subject
				message.body = n.confirm_email.replace('{email}', email).replace('{url}', confirm_url)
				message.from_address = n.confirm_from_email
				message.from_name = n.confirm_from_name
				message.reply_address = n.confirm_from_email
				message.sender = n.confirm_from_user
				message.html = n.confirm_html
				# Don't send it yet until the recipient list is done
				message.status = -1
				# Save to database so we get a value for the primary key,
				# which we need for entering the recipient entries
				message.save()
				recipient = EmailRecipient()
				recipient.message = message
				recipient.to_name = ""
				recipient.to_address = email
				recipient.save()
				message.status = 0
				message.save()
				return HttpResponse("A")  # Success!
			elif request.GET['action'] == 'confirm':
				pid = unquote_plus(request.GET['id'])
				key = unquote_plus(request.GET['key'])
				try:
					p = PendingNewsletterSubscriber.objects.get(pk=pid, newsletter=n, uniqid=key)
				except PendingNewsletterSubscriber.DoesNotExist:
					return HttpResponse("B")
				try:
					if n.pk != 1:
						# Only do the user thing for The Amplifier (id = 1)
						raise User.DoesNotExist
					try:
						u = User.objects.get(email=p.email)
					except User.MultipleObjectsReturned:
						# Subscribe the first user with this email address
						u = User.objects.filter(email=p.email)[0]
					# This user is already a Robogals member
					u.email_newsletter_optin = True
					u.save()
				except User.DoesNotExist:
					ns = NewsletterSubscriber()
					ns.newsletter = n
					ns.email = p.email
					ns.active = True
					ns.details_verified = False
					ns.save()
				PendingNewsletterSubscriber.objects.filter(email=p.email, newsletter=n).delete()
				return HttpResponse("A")
			elif request.GET['action'] == 'unsubscribe':
				email = unquote_plus(request.GET['email']).strip()
				try:
					ns = NewsletterSubscriber.objects.get(email=email, newsletter=n, active=True)
				except NewsletterSubscriber.DoesNotExist:
					# Not on the list. Perhaps subscribed as a Robogals member?
					if n.pk != 1:
						# Only do the user thing for The Amplifier (id = 1)
						return HttpResponse("B")  # Not subscribed
					try:
						for u in User.objects.filter(email=email):
							if u.email_newsletter_optin:
								u.email_newsletter_optin = False
								u.save()
								return HttpResponse("A")
						return HttpResponse("B")  # Not subscribed
					except User.DoesNotExist:
						return HttpResponse("B")  # Not subscribed
				ns.unsubscribed_date = datetime.now()
				ns.active = False
				ns.save()
				if n.pk == 1:
					for u in User.objects.filter(is_active=True, email=email, email_newsletter_optin=True):
						u.email_newsletter_optin = False
						u.save()
				return HttpResponse("A")
			else:
				return HttpResponse("-1")
		except KeyError:
			return HttpResponse("-1")
	else:
		return HttpResponse("-1")
예제 #4
0
def api(request):
	if 'api' not in request.GET:
		return HttpResponse("-1")
	elif request.GET['api'] != API_SECRET:
		return HttpResponse("-1")
	elif 'action' in request.GET:
		try:
			n = Newsletter.objects.get(pk=request.GET['newsletter'])
		except Newsletter.DoesNotExist:
			return HttpResponse("-1")
		try:
			if request.GET['action'] == 'subscribe':
				email = unquote_plus(request.GET['email']).strip()
				if not email_re.match(email):
					return HttpResponse("C")  # Invalid email
				c = NewsletterSubscriber.objects.filter(email=email, newsletter=n, active=True).count()
				if c != 0:
					return HttpResponse("B")  # Already subscribed
				if n.pk == 1:
					users_count = User.objects.filter(is_active=True, email=email, email_newsletter_optin=True).count()
					if users_count > 0:
						return HttpResponse("B")  # Already subscribed
				try:
					# They've tried to subscribe already, so resend confirmation email
					p = PendingNewsletterSubscriber.objects.get(email=email, newsletter=n)
				except PendingNewsletterSubscriber.DoesNotExist:
					p = PendingNewsletterSubscriber()
					p.email = email
					p.uniqid = md5(SECRET_KEY + email + n.name).hexdigest()
					p.newsletter = n
					p.save()
				confirm_url = n.confirm_url + "pid=" + str(p.pk) + "&key=" + p.uniqid
				message = EmailMessage()
				message.subject = n.confirm_subject
				message.body = n.confirm_email.replace('{email}', email).replace('{url}', confirm_url)
				message.from_address = n.confirm_from_email
				message.from_name = n.confirm_from_name
				message.reply_address = n.confirm_from_email
				message.sender = n.confirm_from_user
				message.html = n.confirm_html
				# Don't send it yet until the recipient list is done
				message.status = -1
				# Save to database so we get a value for the primary key,
				# which we need for entering the recipient entries
				message.save()
				recipient = EmailRecipient()
				recipient.message = message
				recipient.to_name = ""
				recipient.to_address = email
				recipient.save()
				message.status = 0
				message.save()
				return HttpResponse("A")  # Success!
			elif request.GET['action'] == 'confirm':
				pid = unquote_plus(request.GET['id'])
				key = unquote_plus(request.GET['key'])
				try:
					p = PendingNewsletterSubscriber.objects.get(pk=pid, newsletter=n, uniqid=key)
				except PendingNewsletterSubscriber.DoesNotExist:
					return HttpResponse("B")
				try:
					if n.pk != 1:
						# Only do the user thing for The Amplifier (id = 1)
						raise User.DoesNotExist
					try:
						u = User.objects.get(email=p.email)
					except User.MultipleObjectsReturned:
						# Subscribe the first user with this email address
						u = User.objects.filter(email=p.email)[0]
					# This user is already a Robogals member
					u.email_newsletter_optin = True
					u.save()
				except User.DoesNotExist:
					ns = NewsletterSubscriber()
					ns.newsletter = n
					ns.email = p.email
					ns.active = True
					ns.details_verified = False
					ns.save()
				p.delete()
				return HttpResponse("A")
			elif request.GET['action'] == 'unsubscribe':
				email = unquote_plus(request.GET['email']).strip()
				try:
					ns = NewsletterSubscriber.objects.get(email=email, newsletter=n, active=True)
				except NewsletterSubscriber.DoesNotExist:
					# Not on the list. Perhaps subscribed as a Robogals member?
					if n.pk != 1:
						# Only do the user thing for The Amplifier (id = 1)
						return HttpResponse("B")  # Not subscribed
					try:
						for u in User.objects.filter(email=email):
							if u.email_newsletter_optin:
								u.email_newsletter_optin = False
								u.save()
								return HttpResponse("A")
						return HttpResponse("B")  # Not subscribed
					except User.DoesNotExist:
						return HttpResponse("B")  # Not subscribed
				ns.unsubscribed_date = datetime.now()
				ns.active = False
				ns.save()
				if n.pk == 1:
					for u in User.objects.filter(is_active=True, email=email, email_newsletter_optin=True):
						u.email_newsletter_optin = False
						u.save()
				return HttpResponse("A")
			else:
				return HttpResponse("-1")
		except KeyError:
			return HttpResponse("-1")
	else:
		return HttpResponse("-1")
예제 #5
0
def importcsv(filerows, welcomeemail, defaults, newsletter, user):
    columns = None
    subscribers_imported = 0
    most_recent_issue = newsletter.get_most_recent()
    if defaults["type"]:
        defaults["subscriber_type_id"] = defaults["type"].pk
    countries = Country.objects.all()
    country_ids = []
    for country in countries:
        country_ids.append(country.pk)
    for row in filerows:
        try:
            # Get column names from first row
            if columns == None:
                columns = row
                if "email" not in columns:
                    raise RgImportCsvException("You must specify an email field")
                continue

                # Create new user
            newsubscriber = NewsletterSubscriber()

            # Process row
            i = 0
            send_most_recent = defaults["send_most_recent"]
            send_email = False
            for cell in row:
                colname = columns[i]
                if colname == "email":
                    stringval(colname, cell, newsubscriber, defaults)
                    if not email_re.match(newsubscriber.email):
                        raise SkipRowException
                    if (
                        NewsletterSubscriber.objects.filter(email=newsubscriber.email, newsletter=newsletter).count()
                        > 0
                    ):
                        raise SkipRowException  # This email address is already subscribed
                elif colname == "first_name":
                    stringval(colname, cell, newsubscriber, defaults)
                elif colname == "last_name":
                    stringval(colname, cell, newsubscriber, defaults)
                elif colname == "company":
                    stringval(colname, cell, newsubscriber, defaults)
                elif colname == "type":
                    types = SubscriberType.objects.all()
                    type_ids = []
                    for type in types:
                        type_ids.append(type.pk)
                    numval("subscriber_type_id", cell, newsubscriber, defaults, type_ids)
                elif colname == "country":
                    if cell in country_ids:
                        stringval("country_id", cell, newsubscriber, defaults)
                    else:
                        newsubscriber.country = defaults["country"]
                elif colname == "details_verified":
                    boolval(colname, cell, newsubscriber, defaults)
                elif colname == "send_most_recent":
                    data = cell.strip()
                    if data == "true":
                        send_most_recent = True
                    elif data == "1":
                        send_most_recent = True
                    elif data == "yes":
                        send_most_recent = True
                    if data == "false":
                        send_most_recent = False
                    elif data == "0":
                        send_most_recent = False
                    elif data == "no":
                        send_most_recent = False
                elif colname == "send_email":
                    data = cell.strip()
                    if data == "true":
                        send_email = True
                    elif data == "1":
                        send_email = True
                    elif data == "yes":
                        send_email = True
                else:
                    pass  # Unknown column, ignore
                    # Increment column and do the loop again
                i += 1

                # Apply any unapplied defaults
            if "type" not in columns:
                if "subscriber_type_id" in defaults:
                    newsubscriber.subscriber_type_id = defaults["subscriber_type_id"]
            if "details_verified" not in columns:
                if "details_verified" in defaults:
                    newsubscriber.details_verified = defaults["details_verified"]
            if "country" not in columns:
                if "country" in defaults:
                    newsubscriber.country = defaults["country"]

                    # Set some other important attributes
            newsubscriber.newsletter = newsletter
            newsubscriber.subscribed_date = datetime.now()
            newsubscriber.active = True

            # And finally...
            newsubscriber.save()

            # Send welcome email, if applicable
            if welcomeemail["importaction"] == "1" or (welcomeemail["importaction"] == "3" and send_email):
                message = EmailMessage()
                message.subject = welcomeemail["subject"]
                try:
                    message.body = welcomeemail["body"].format(newsletter=newsletter, subscriber=newsubscriber)
                except Exception:
                    newsubscriber.delete()
                    raise RgImportCsvException("Welcome email format is invalid")
                message.from_address = welcomeemail["from_address"]
                message.reply_address = welcomeemail["reply_address"]
                message.from_name = welcomeemail["from_name"]
                message.sender = user
                message.html = welcomeemail["html"]
                message.status = -1
                message.save()
                recipient = EmailRecipient()
                recipient.message = message
                recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name
                recipient.to_address = newsubscriber.email
                recipient.save()
                message.status = 0
                message.save()

                # Send most recent newsletter, if applicable
            if send_most_recent:
                recipient = EmailRecipient()
                recipient.message = most_recent_issue
                recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name
                recipient.to_address = newsubscriber.email
                recipient.save()

                # Increment counter
            subscribers_imported += 1
        except SkipRowException:
            continue  # Skip this row

            # Tell the most recent issue to send with new subscribers,
            # if applicable
    most_recent_issue.status = 0
    most_recent_issue.save()
    return subscribers_imported