コード例 #1
0
ファイル: general_views.py プロジェクト: nomadmtb/mailprime
def user_account(request, param_username):
	page_vars = { "page_title": "Account: " + request.user.username }

	if current_user(request) and param_username == request.user.username:

		try:
			requested_user = User.objects.get(username=param_username)
		except User.DoesNotExist:
			raise Http404

		if request.method == "GET":
			user_profile = Profile.objects.get(user = request.user)
			init_values = {'time_zone': user_profile.time_zone, 'email': request.user.email}
			page_vars['form'] = UserProfileForm(initial=init_values)
			csrfContext = RequestContext(request, page_vars)
			
			return render(request, 'auth/user_account.html', csrfContext)

		elif request.method == "POST":
			if current_user(request):
				completed_form = UserProfileForm(request.POST)

				if completed_form.is_valid():

					user_profile = Profile.objects.get(user=request.user)
					user_obj = User.objects.get(username=request.user.username)

					# Updating User and Profile Objects with form data
					user_profile.time_zone = completed_form.cleaned_data['time_zone']

					request.session['user_timezone'] = completed_form.cleaned_data['time_zone']

					user_obj.email = completed_form.cleaned_data['email']

					# Only update the user's password if it's not empty
					if completed_form.cleaned_data['password'] != '':
						user_obj.set_password(completed_form.cleaned_data['password'])

					# Commiting the edited objects to the database
					user_profile.save()
					user_obj.save()

					messages.add_message(request, messages.SUCCESS, 'Success: Your Account Has Been Updated')
					return HttpResponseRedirect('/' + request.user.username + '/account')
				else:
					generate_form_errors(request, completed_form)
					return HttpResponseRedirect('/' + request.user.username + '/account')
			else:
				raise Http404
		
	else:
		raise Http404
コード例 #2
0
ファイル: campaign_views.py プロジェクト: nomadmtb/mailprime
def user_campaign_new(request, param_username):
	if current_user(request) and request.user.username == param_username:
		page_vars = {"page_title": "New Campaign"}

		if request.method == 'POST':

			completed_form = CampaignForm(request.POST)

			if completed_form.is_valid():

				campaign = completed_form.save(commit=False)
				campaign.user = request.user
				campaign.active = True
				campaign.save()

				messages.add_message(request, messages.SUCCESS, 'Created New Campaign')

				return HttpResponseRedirect('/' + request.user.username + '/campaign-' + str(campaign.pk))
			else:
				generate_form_errors(request, completed_form)
				page_vars['form'] = completed_form
				return render(request, 'campaign/new.html', page_vars)
				
		elif request.method == "GET":
			page_vars['form'] = CampaignForm()
			csrfContext = RequestContext(request, page_vars)
			return render(request, 'campaign/new.html', csrfContext)
	else:
		raise Http404
コード例 #3
0
ファイル: views.py プロジェクト: nomadmtb/mailprime
def user_campaign_message_events(request, param_username, param_campaign_pk, param_message_pk):
	page_vars = {"page_title": 'Message Events'}

	if current_user(request) and request.user.username == param_username:
		events = Event.objects.filter(message__campaign__pk = param_campaign_pk, message__pk = param_message_pk)
		page_vars['events'] = events
		return render(request, 'user_campaign_message_events.html', page_vars)
	else:
		raise Http404
コード例 #4
0
ファイル: views.py プロジェクト: nomadmtb/mailprime
def user_campaign_recipients(request, param_username, param_campaign_pk):
	page_vars = {"page_title": 'Campaign Recipients'}

	if current_user(request) and request.user.username == param_username:
		recipients = Recipient.objects.filter(campaign__pk = param_campaign_pk)
		page_vars['recipients'] = recipients
		return render(request, 'user_campaign_recipients.html', page_vars)
	else:
		raise Http404
コード例 #5
0
ファイル: campaign_views.py プロジェクト: nomadmtb/mailprime
def user_campaigns(request, param_username):
	page_vars = { "page_title": request.user.username + '\'s campaigns' }

	if current_user(request) and param_username == request.user.username:
		user_campaigns = Campaign.objects.filter(user = request.user).order_by('-created_date')
		page_vars['campaigns'] = user_campaigns
		return render(request, 'campaign/index.html', page_vars)
	else:
		raise Http404
コード例 #6
0
ファイル: campaign_views.py プロジェクト: nomadmtb/mailprime
def user_campaign_edit(request, param_username, param_campaign_pk):
	page_vars = {"page_title": "Edit Campaign"}

	if current_user(request) and param_username == request.user.username:
		try:
			user_campaign = Campaign.objects.get(pk = param_campaign_pk)
		except Campaign.DoesNotExist:
			raise Http404

		if user_campaign.user != request.user:
			raise Http404

		page_vars['campaign'] = user_campaign

		if user_campaign.user == request.user:

			if request.method == "GET":
				action = request.GET.get('action')

				if action == "delete":
					# We want to delete the campaign
					Campaign.objects.filter(pk=param_campaign_pk).delete()
					messages.add_message(request, messages.SUCCESS, 'Successfully deleted Campaign')
					return HttpResponseRedirect('/' + request.user.username + '/campaigns')

				else:
					# We want to edit the campaign, render form				
					page_vars['form'] = CampaignForm(instance=user_campaign)

					# Generate warning is campaign is disabled
					if user_campaign.active == False:
						messages.add_message(request, messages.ERROR, 'Campaign disabled by MailPrime Administrator')

					# Generate CSRF Context
					csrfContext = RequestContext(request, page_vars)

					# Render page for user
					return render(request, 'campaign/edit.html', csrfContext)

			elif request.method == "POST":

				# Check if campaign is disabled
				if user_campaign.active == False:
					return HttpResponseRedirect('/{0}/campaign-{1}'.format(request.user.username, user_campaign.pk))

				# It's safe to assume that the campaign is active, process form
				completed_form = CampaignForm(request.POST, instance=user_campaign)

				if completed_form.is_valid():
					completed_form.save()
					messages.add_message(request, messages.SUCCESS, 'Successfully Updated Campaign')
					return HttpResponseRedirect('/' + request.user.username + '/campaign-' + str(user_campaign.pk))
				else:
					generate_form_errors(request, completed_form)
					page_vars['form'] = completed_form
					return render(request, 'campaign/edit.html', page_vars)
コード例 #7
0
ファイル: views.py プロジェクト: nomadmtb/mailprime
def user_campaign_message_event(request, param_username, param_campaign_pk, param_message_pk, param_event_pk):
	page_vars = {"page_title": 'View Event'}

	if current_user(request) and request.user.username == param_username:
		try:
			event = Event.objects.get(pk = param_event_pk, recipient__campaign__pk = param_campaign_pk, message__pk = param_message_pk)
		except Event.DoesNotExist:
			messages.add_message(request, messages.WARNING, "Something went wrong")
			raise Http404

		page_vars['event'] = event
		return render(request, 'user_campaign_message_event.html', page_vars)
	else:
		raise Http404
コード例 #8
0
ファイル: json_views.py プロジェクト: nomadmtb/mailprime
def get_campaign_data(request, param_username, param_campaign_pk):

    if current_user(request) and request.user.username == param_username:

        # Data dictionary that will contain our pre-json data.
        data = {}

        read_events = Event.objects.filter(
            message__campaign__pk=param_campaign_pk,
            message__campaign__user__username=param_username)

        # Getting User Tz
        user_tz = pytz.timezone(
            Profile.objects.get(user=request.user).time_zone)

        if read_events.count() == 0:
            return HttpResponse(
                json.dumps({
                    "ERROR": 'No Data'
                }),
                content_type='application/json')

        # Load Line Graph
        read_by_day_data = []
        read_dates = []
        read_events = read_events.order_by('-created_date')

        for event in read_events:
            cur_date = event.created_date.astimezone(user_tz).strftime("%m/%d")
            read_dates.append(cur_date)

        read_counter = Counter(item for item in read_dates)

        for k, v in read_counter.iteritems():
            read_by_day_data.insert(1, [k, v])

        # Sorting the data by date which is x[0]
        read_by_day_data.sort(key=lambda x: x[0])

        # Insert the title data into the array of sorted data
        read_by_day_data.insert(0, ['Date', 'Read-Events'])

        data['read_by_day_data'] = read_by_day_data

        # End Load Line Graph

        return HttpResponse(json.dumps(data), content_type='application/json')
    else:
        return HttpResponse('Unauthorized', status=401)
コード例 #9
0
ファイル: views.py プロジェクト: nomadmtb/mailprime
def user_campaign_message(request, param_username, param_campaign_pk, param_message_pk):
	page_vars = {"page_title": 'Campaign Message'}

	if current_user(request) and request.user.username == param_username:

		try:
			message = Message.objects.get(campaign__pk = param_campaign_pk, campaign__user__username = request.user.username, pk = param_message_pk)
		except Message.DoesNotExist:
			raise Http404

		page_vars['message'] = message
		return render(request, 'message/show.html', page_vars)

	else:
		raise Http404
コード例 #10
0
ファイル: views.py プロジェクト: nomadmtb/mailprime
def login(request):
	page_vars = { "page_title": "login" }

	if request.method == 'POST':

		if authenticate_user(request, request.POST['username'], request.POST['password']):
			return HttpResponseRedirect('/' + request.user.username + '/campaigns')
		else:
			return HttpResponseRedirect('/login')
	elif request.method == 'GET':
		if current_user(request):
			return HttpResponseRedirect('/')
		else:
			page_vars['form'] = LoginForm()
			csrfContext = RequestContext(request, page_vars)
			return render(request, 'auth/login.html', csrfContext)
コード例 #11
0
ファイル: views.py プロジェクト: nomadmtb/mailprime
def user_account(request, param_username):
	page_vars = { "page_title": "Account: " + request.user.username }

	if current_user(request):

		try:
			requested_user = User.objects.get(username=param_username)
		except User.DoesNotExist:
			raise Http404
			
		if requested_user.username == request.user.username:
			page_vars['user'] = request.user
			return render(request, 'user_account.html', page_vars)
		else:
			raise Http404
	else:
		raise Http404
コード例 #12
0
ファイル: recipient_views.py プロジェクト: nomadmtb/mailprime
def add_recipient(request, param_username, param_campaign_pk):
	if current_user(request) and request.user.username == param_username:
		page_vars = {'page_title': 'Add Recipient'}

		try:
			page_vars['campaign'] = Campaign.objects.get(pk=param_campaign_pk, user=request.user)
		except Campaign.DoesNotExist:
			raise Http404

		# User is requesting page
		if request.method == "GET":
			page_vars['form'] = RecipientForm()

			csrfContext = RequestContext(request, page_vars)
			return render(request, 'recipient/add.html', csrfContext)

		# User is uploading from the form
		elif request.method == "POST":

			# Check to see if the campaign is disabled
			if page_vars['campaign'].active:
				completed_form = RecipientForm(request.POST)

				if completed_form.is_valid():
					recipient = completed_form.save(commit=False)

					recipient.campaign = page_vars['campaign']
					recipient.save()

					# Send out invitation!!!
					os.system("python /var/www/mailprime/manage.py deploy_invitations {0} &".format( recipient.campaign.pk ))
					
					return HttpResponseRedirect('/' + request.user.username + '/campaign-' + str(page_vars['campaign'].pk) + '/recipients')
				else:
					generate_form_errors(request, completed_form)
					page_vars['form'] = completed_form
					return render(request, 'recipient/add.html', page_vars)

			else:

				# Campaign is deactivated, generate message.
				messages.add_message(request, messages.SUCCESS, 'Campaign disabled by MailPrime Administrator')
				return HttpResponseRedirect('/{0}/campaign-{1}/recipients/add'.format(request.user.username, page_vars['campaign'].pk))

	else:
		raise Http404
コード例 #13
0
ファイル: recipient_views.py プロジェクト: nomadmtb/mailprime
def user_campaign_recipients(request, param_username, param_campaign_pk):
	page_vars = {"page_title": 'Campaign Recipients'}

	if current_user(request) and request.user.username == param_username:

		try:
			campaign = Campaign.objects.get(pk = param_campaign_pk, user=request.user)
		except Campaign.DoesNotExist:
			raise Http404

		recipients = Recipient.objects.filter(campaign = campaign).order_by('email')

		# Checking to see if the campaign is disabled
		if campaign.active:

			# Looking for the 'delete' GET parameter, so we can remove the recipient
			recipient_to_remove = request.GET.get('delete')
			print recipient_to_remove

			# Check to make sure, recip_pk belongs to campaign.
			# If so, delete it from the database.
			if recipient_to_remove is not None:

				for x in recipients:

					if int(recipient_to_remove) == x.pk:

						messages.add_message(request, messages.SUCCESS, 'Successfully Removed {0}'.format( x.email ))
						x.delete()

						# Update recipients queryset
						recipients = Recipient.objects.filter(campaign = campaign).order_by('email')
		else:

			# Generate warning because campaign is disabled
			messages.add_message(request, messages.SUCCESS, 'Campaign disabled by MailPrime Administrator')

		# Page varaibles and render page
		page_vars['campaign'] = campaign
		page_vars['recipients'] = recipients

		return render(request, 'recipient/index.html', page_vars)

	else:
		
		raise Http404
コード例 #14
0
ファイル: views.py プロジェクト: nomadmtb/mailprime
def user_campaign_messages(request, param_username, param_campaign_pk):
	page_vars = {"page_title": 'Campaign Messages'}

	try:
		campaign = Campaign.objects.get(pk = param_campaign_pk)
	except Campaign.DoesNotExist:
		raise Http404

	if campaign.user.username != request.user.username:
		raise Http404

	page_vars['campaign'] = campaign;

	if current_user(request) and request.user.username == param_username:
		campaign_messages = Message.objects.filter(campaign__pk = param_campaign_pk)
		page_vars['campaign_messages'] = campaign_messages
		return render(request, 'message/index.html', page_vars)
	else:
		raise Http404
コード例 #15
0
ファイル: message_views.py プロジェクト: nomadmtb/mailprime
def message_statistics(request, param_username, param_campaign_pk, param_message_pk):
	if current_user(request) and request.user.username == param_username:	

		page_vars = {}
		page_vars['page_title'] = 'Message Statistics'

		# Validate Message with supplied params
		try:
			requested_message = Message.objects.get(campaign__user__username=param_username, campaign__pk=param_campaign_pk, pk=param_message_pk)
		except Message.DoesNotExist:
			raise Http404

		page_vars['message'] = requested_message
		page_vars['campaign_pk'] = param_campaign_pk

		return render(request, 'message/stats.html', page_vars)

	else:
		raise Http404
コード例 #16
0
ファイル: json_views.py プロジェクト: nomadmtb/mailprime
def get_sample_message(request, param_username, param_campaign_pk, param_message_pk):

	if current_user(request) and request.user.username == param_username:

		data = {}

		try:
			message = Message.objects.get(	pk=param_message_pk,
											campaign__pk=param_campaign_pk,
											campaign__user__username=param_username)
		except Message.DoesNotExist:

			return HttpResponse('Unauthorized', status=401)

		sample_message_html = message.build_sample()

		return HttpResponse(sample_message_html, content_type='text/html')

	else:
		return HttpResponse('Unauthorized', status=401)
コード例 #17
0
ファイル: views.py プロジェクト: nomadmtb/mailprime
def user_campaign_message_new(request, param_username, param_campaign_pk):
	if current_user(request) and request.user.username == param_username:

		try:
			campaign = Campaign.objects.get(pk = param_campaign_pk)
		except Campaign.DoesNotExist:
			raise Http404

		if campaign.user_id == request.user.pk:
			page_vars = {"page_title": "New Message"}
			page_vars['campaign'] = campaign
			if request.method == "POST":
				# Process POST DATA...
				pass
			else:
				# Process GET DATA...
				page_vars['form'] = MessageForm()
				csrfContext = RequestContext(request, page_vars)
				return render(request, 'message/new.html', csrfContext)

	raise Http404
コード例 #18
0
ファイル: general_views.py プロジェクト: nomadmtb/mailprime
def login(request):
	page_vars = { "page_title": "login" }

	if request.method == 'POST':

		if authenticate_user(request, request.POST['username'], request.POST['password']):
			user_profile = Profile.objects.filter(user = request.user)

			# Create Profile if User doesn't have one.
			if not user_profile:
				Profile(time_zone="UTC", user=request.user).save()

			return HttpResponseRedirect('/' + request.user.username + '/campaigns')
		else:
			return HttpResponseRedirect('/login')
	elif request.method == 'GET':
		if current_user(request):
			return HttpResponseRedirect('/')
		else:
			page_vars['form'] = LoginForm()
			csrfContext = RequestContext(request, page_vars)
			return render(request, 'auth/login.html', csrfContext)
コード例 #19
0
ファイル: campaign_views.py プロジェクト: nomadmtb/mailprime
def user_campaign(request, param_username, param_campaign_pk):
	page_vars = {"page_title": 'Campaign View'}

	if current_user(request) and request.user.username == param_username:

		try:
			user_campaign = Campaign.objects.get(pk = param_campaign_pk)
		except Campaign.DoesNotExist:
			raise Http404

		if user_campaign.user.username != request.user.username:
			raise Http404

		if user_campaign.active == False:
			messages.add_message(request, messages.ERROR, 'Campaign disabled by MailPrime Administrator')

		page_vars['campaign'] = user_campaign
		page_vars['message_count'] = Message.objects.filter(campaign = user_campaign).count()
		page_vars['recipient_count'] = Recipient.objects.filter(campaign = user_campaign).count()
		return render(request, 'campaign/show.html', page_vars)
	else:
		raise Http404
コード例 #20
0
ファイル: message_views.py プロジェクト: nomadmtb/mailprime
def user_campaign_message_new(request, param_username, param_campaign_pk):
	if current_user(request) and request.user.username == param_username:

		try:
			campaign = Campaign.objects.get(pk = param_campaign_pk)
		except Campaign.DoesNotExist:
			raise Http404

		if campaign.user == request.user:
			page_vars = {"page_title": "New Message"}
			page_vars['campaign'] = campaign

			if request.method == "POST":
				
				completed_form = MessageForm(request.POST)

				if completed_form.is_valid():
					message = completed_form.save(commit=False)
					message.campaign_id = param_campaign_pk
					message.save()
					messages.add_message(request, messages.SUCCESS, 'Successfully Created Message')

					return HttpResponseRedirect('/'+ request.user.username + "/campaign-" + str(message.campaign.id) + "/messages")
				else:
					generate_form_errors(request, completed_form)
					page_vars['form'] = completed_form

					return render(request, 'message/new.html', page_vars)
			else:
				# Process GET DATA...
				page_vars['form'] = MessageForm()
				csrfContext = RequestContext(request, page_vars)
				
				return render(request, 'message/new.html', csrfContext)
	else:
		raise Http404
コード例 #21
0
ファイル: message_views.py プロジェクト: nomadmtb/mailprime
def user_campaign_message(request, param_username, param_campaign_pk, param_message_pk):
	page_vars = {"page_title": 'Campaign Message'}

	if current_user(request) and request.user.username == param_username:

		try:
			message = Message.objects.get(campaign__pk = param_campaign_pk, campaign__user__username = request.user.username, pk = param_message_pk)
		except Message.DoesNotExist:
			raise Http404

		action = request.GET.get('action')

		# Check to see if the campaign is disabled.
		if message.campaign.active == False:

			# Campaign is locked, generate message for user, return.
			messages.add_message(request, messages.SUCCESS, 'Campaign disabled by MailPrime Administrator')

			page_vars['templates'] = Template.objects.all()
			page_vars['sample_link'] = "/api/{0}/c-{1}/m-{2}/sample_message.html".format(
																						request.user.username,
																						message.campaign.pk,
																						message.pk)
			page_vars['message'] = message
			page_vars['form'] = MessageForm(instance=message)
			page_vars['campaign'] = message.campaign
			page_vars['slick_present'] = True
			
			csrfContext = RequestContext(request, page_vars)
			return render(request, 'message/show.html', csrfContext)

		# Deploy message if deploy GET param is set
		if (action is not None) and (action == 'deploy'):

			if message.deployed == False:
				os.system('python /var/www/mailprime/manage.py deploy_messages ' + str(message.pk) + '&')
				messages.add_message(request, messages.SUCCESS, 'SUCCESS: Your Message Has Been Deployed')
			else:
				messages.add_message(request, messages.SUCCESS, 'ERROR: Message Has Already Been Deployed')

			return HttpResponseRedirect('/' + request.user.username + '/campaign-' + str(message.campaign.pk) + '/messages')

		elif (action is not None) and (action == 'delete'):

			# Storing the campaign in a var so we can delete the message.
			campaign_pk = message.campaign.pk

			# Add message for user.
			messages.add_message(request, messages.SUCCESS, 'SUCCESS: Deleted Message')

			# Delete the message from the database.
			message.delete()

			# Redirect back to the campaign homepage.
			return HttpResponseRedirect('/{0}/campaign-{1}'.format(request.user.username, campaign_pk))

		# Else, GET param not set, render regular page
		else:

			# Request method is GET, generate new form
			if request.method == "GET":

				page_vars['templates'] = Template.objects.all()
				page_vars['sample_link'] = "/api/{0}/c-{1}/m-{2}/sample_message.html".format(
																						request.user.username,
																						message.campaign.pk,
																						message.pk)
				page_vars['message'] = message
				page_vars['form'] = MessageForm(instance=message)
				page_vars['campaign'] = message.campaign
				page_vars['slick_present'] = True
			
				csrfContext = RequestContext(request, page_vars)
				return render(request, 'message/show.html', csrfContext)

			# Request method is POST, process form data to model
			elif request.method == "POST":

				# Creating Message instance from modelform
				completed_form = MessageForm(request.POST, instance=message)

				# Running validation w/ clean(), if valid
				if completed_form.is_valid():

					new_message = completed_form.save(commit=False)

					if new_message.can_update():

						new_message.save()
						messages.add_message(request, messages.SUCCESS, 'Successfully Updated Message')
						return HttpResponseRedirect('/{0}/campaign-{1}/message-{2}'.format(request.user.username, message.campaign.pk, message.pk))

					else:
						messages.add_message(request, messages.SUCCESS, 'ERROR: Message has already been deployed')
						return HttpResponseRedirect('/{0}/campaign-{1}/message-{2}'.format(request.user.username, message.campaign.pk, message.pk))

				# Validation errors occurred, regenerate form with vars
				else:
					generate_form_errors(request, completed_form)
					page_vars['form'] = completed_form
					page_vars['campaign'] = message.campaign
					page_vars['message'] = message
					page_vars['templates'] = Template.objects.all()
					page_vars['slick_present'] = True
					page_vars['sample_link'] = "/api/{0}/c-{1}/m-{2}/sample_message.html".format(
																							request.user.username,
																							message.campaign.pk,
																							message.pk)

					csrfContext = RequestContext(request, page_vars)
					return render(request, 'message/show.html', csrfContext)
	else:
		raise Http404
コード例 #22
0
ファイル: json_views.py プロジェクト: nomadmtb/mailprime
def get_message_region_data(request, param_username, param_campaign_pk, param_message_pk):

	if current_user(request) and request.user.username == param_username:

		# Pre-build data, See Google Format -> https://developers.google.com/chart/interactive/docs/gallery/geochart
		data = {}

		# Getting values for all of the associated read_events
		#country_data = Event.objects.values_list('country_code')

		read_events = Event.objects.filter( message__pk=param_message_pk,
											 message__campaign__pk=param_campaign_pk,
											 message__campaign__user__username=param_username )

		if read_events.count() == 0:
			return HttpResponse(json.dumps({"ERROR": 'No Data'}), content_type='application/json')

		# Load Region-data	
		region_data = []
		country_data = read_events.values_list('country_code')
		counter_data = Counter(item[0] for item in country_data)

		for k, v in counter_data.iteritems():
			entry = [ k, v ]
			region_data.append(entry)

		region_title = ['Region', 'Read Events']
		region_data = [region_title] + region_data
		data['region_data'] = region_data
		# End Region-data

		# Load Coordinate Data
		coordinate_data = []
		coord_data = read_events.values_list('latitude', 'longitude', 'recipient__email')

		for item in coord_data:
			entry = [ item[0], item[1], item[2] ]
			coordinate_data.append(entry)

		coord_title = ['Lat', 'Lon', 'Name']
		coordinate_data = [coord_title] + coordinate_data
		data['coordinate_data'] = coordinate_data
		# End Coordinate Data

		# Load Unsub Perc. Data
		unsub_data = []

		subscribed_count = Recipient.objects.filter(campaign__pk=param_campaign_pk, campaign__user__username=param_username).count()
		unsub_count = read_events[0].message.campaign.unsub_count

		unsub_title = ['Subscribe Status', 'Number of Users']
		unsub_data.append(['Subscribed', subscribed_count])
		unsub_data.append(['Unsubscribed', unsub_count])
		unsub_data = [unsub_title] + unsub_data

		data['unsub_data'] = unsub_data
		# END Unsub Data

		# Load Response Perc. Data
		response_data = []
		users_responded = read_events.values('recipient__email').distinct().count()

		num_users = Recipient.objects.filter( campaign__pk=param_campaign_pk,
											  campaign__user__username=param_username ).count()

		response_title = ['Status', 'Responce Rate']
		response_data.append(['Read', users_responded])
		response_data.append(['Not Read', (num_users - users_responded)])

		response_data = [response_title] + response_data
		data['response_data'] = response_data
		# End Response Perc. Data

		# Day of Week Data
		day_of_week_data = []
		weekly_data = []
		week_title = ['Weekday', 'Read Events']

		# Getting User Tz
		user_tz = pytz.timezone(
			Profile.objects.get( user=request.user).time_zone )

		event_week_data = read_events.values_list('created_date')

		# Convert all times to user_tz
		for event_date in event_week_data:
			local_time = event_date[0].replace(tzinfo=pytz.utc).astimezone(user_tz)
			weekly_data.append(local_time.strftime("%A"))

		# Count Data
		week_counter_data = Counter(weekly_data)

		# Loading Data into array
		for k, v in week_counter_data.iteritems():
			day_of_week_data += [[ k, v ]]

		day_of_week_data = [week_title] + day_of_week_data
		data['weekday_data'] = day_of_week_data
		# End Day of Week Data

		# Load Line Graph
		read_by_day_data = []
		read_dates = []
		read_events = read_events.order_by('-created_date')

		for event in read_events:
			cur_date = event.created_date.astimezone(user_tz).strftime("%m/%d")
			read_dates.append(cur_date)

		read_counter = Counter(item for item in read_dates)

		for k, v in read_counter.iteritems():
			read_by_day_data.insert(1,[k,v])

		# Sorting the data by date which is x[0]
		read_by_day_data.sort(key=lambda x: x[0])

		# Okay, now we add the title to the sorted array of data
		read_by_day_data.insert(0, ['Date', 'Read-Events'])

		data['read_by_day_data'] = read_by_day_data

		# End Load Line Graph

		return HttpResponse(json.dumps(data), content_type='application/json')
	else:
		return HttpResponse('Unauthorized', status=401)
コード例 #23
0
ファイル: recipient_views.py プロジェクト: nomadmtb/mailprime
def upload_recipients(request, param_username, param_campaign_pk):
	page_vars = {"page_title": 'Upload Recipients'}

	if current_user(request) and request.user.username == param_username:

		# Capturing Campaign that will be used with the recipient entries
		try:
			campaign = Campaign.objects.get(pk=param_campaign_pk, user=request.user)
		except Campaign.DoesNotExist:
			raise Http404

		# User is requesting page, render form
		if request.method == 'GET':

			page_vars['campaign'] = campaign
			page_vars['form'] = ContactUploadForm()
			
			csrfContext = RequestContext(request, page_vars)
			return render(request, 'recipient/upload.html', csrfContext)

		# User is uploading from form, parse data
		elif request.method == 'POST':

			# Check to see if campaign is disabled
			if campaign.active == False:

				#Generate warning, redirect.
				messages.add_message(request, messages.SUCCESS, 'Campaign disabled by MailPrime Administrator')
				return HttpResponseRedirect('/{0}/campaign-{1}/recipients/upload'.format(request.user.username, campaign.pk))

			# Can be assumed that the campaign is not disabled now

			# Page Vars
			page_vars = { 'page_title': 'Upload Report'}

			# Array that will contain invalid/valid emails
			invalid_emails = {}
			valid_emails = {}

			# Valid email flag
			valid = True
			valid_recip = True
			valid_email_count = 0
			invalid_email_count = 0

			form = ContactUploadForm(request.POST, request.FILES)

			if form.is_valid():

				uploaded_file = request.FILES['contact_file']

				# Splitting file into chunks so it doesn't eat up system resources
				for chunk in uploaded_file.chunks():

					# Iterate through each line
					for line in chunk.rstrip().split('\n'):

						try:
							validate_email(line)
						except forms.ValidationError:
							valid = False

						if valid:

							# Save new Recipient to database
							try:
								Recipient(email=line, campaign=campaign).save()
							except IntegrityError:
								valid_recip = False


							# Increment counter
							if (valid_recip):

								valid_email_count += 1
								valid_emails[line] = 'Success'

							else:

								invalid_email_count += 1
								invalid_emails[line] = 'Repeated'

						else:

							# Increment counter
							invalid_email_count += 1
							invalid_emails[line] = 'Invalid'

						# Reset valid flag
						valid = True
						valid_recip = True

				# Giving campaign to template for URL reasons
				page_vars['campaign'] = campaign

				# Generate messages for user
				if (valid_email_count > 0):
					messages.add_message(request, messages.SUCCESS, "{0} Successful Entries".format(valid_email_count))
					page_vars['valid_emails'] = valid_emails

				if (invalid_email_count > 0):
					messages.add_message(request, messages.SUCCESS, "{0} Entries Failed".format(invalid_email_count))
					page_vars['invalid_emails'] = invalid_emails

				# Send out Invitations if necessary
				if valid_email_count > 0:
					os.system("python /var/www/mailprime/manage.py deploy_invitations {0} &".format(campaign.pk))

				return render(request, 'recipient/upload_report.html', page_vars)

			# Form is NOT valid
			else:
				generate_form_errors(request, form)
				return HttpResponseRedirect('/{0}/campaign-{1}/recipients/upload'.format( request.user.username, campaign.pk ))
				
	else:
		raise Http404