<commit_before>from django.contrib.auth.models import User, Group
from django.utils import timezone
from django.contrib.sites.models import Site
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from PIL import Image
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from gather.forms import EventForm, NewUserForm
import datetime
from django.contrib import messages
from django.conf import settings
from django.db.models import Q
from gather.models import Event, EventAdminGroup, EventSeries
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib import messages
import json
import requests
from django.views.decorators.csrf import csrf_exempt
from django.template.loader import get_template
from django.template import Context
from django.core.urlresolvers import reverse
from django.db.models.loading import get_model
from gather.emails import new_event_notification, event_approved_notification, event_published_notification
import logging

logger = logging.getLogger(__name__)

Location = get_model(*settings.LOCATION_MODEL.split(".", 1))

class LocationNotUniqueException(Exception):
	pass

def get_location(location_slug=None):
	if location_slug:
		location = Location.objects.get(slug=location_slug)
	else:
		if Location.objects.count() == 1:
			# the single object might not have pk=1 if a locationw as
			# previously created and then deleted, so by using the all() (after
			# checking there is only one location object) we aren't assuming
			# any particular id. 
			location = Location.objects.all()[0]
		else:
			raise LocationNotUniqueException("You did not specify a location and yet there is more than one location defined. Please specify a location.")
	return location

def event_guide(request, location_slug=None):
	location = get_location(location_slug)
	return render(request, 'gather_event_guide.html')

def create_event(request, location_slug=None):
	location = get_location(location_slug)
	current_user = request.user
	logger.debug("create_event: location:%s, user:%s" % (location, current_user))

	# if the user doesn't have a proper profile, then make sure they extend it first
	# TODO FIXME This is a direct dependency on an external app (the core app where the UserProfile model lives) 
	print current_user.id
	if current_user.id == None :
		messages.add_message(request, messages.INFO, 'We want to know who you are! Please create a profile before submitting an event.')
		return HttpResponseRedirect('/people/register/?next=/events/create/')
	elif current_user.is_authenticated and ((not current_user.profile.bio) or (not current_user.profile.image)):
		messages.add_message(request, messages.INFO, 'We want to know a bit more about you! Please complete your profile before submitting an event.')
		return HttpResponseRedirect('/people/%s/edit/' % current_user.username)

	other_users = User.objects.exclude(id=current_user.id)
	# get a list of users so that those creating an event can select from
	# existing users as event co-organizers
	user_list = [u.username for u in other_users]
	location_admin_group = EventAdminGroup.objects.get(location=location)
	if current_user in location_admin_group.users.all():
		is_event_admin = True
	else:
		is_event_admin = False

	if request.method == 'POST':
		logger.debug("create_event: POST=%s" % request.POST)
		form = EventForm(request.POST, request.FILES)
		if form.is_valid():
			event = form.save(commit=False)
			event.creator = current_user
			# associate this event with a specific location and admin group
			event.location = location
			event.admin = location_admin_group
			event.save()
			co_organizers = form.cleaned_data.get('co_organizers')
			# always make sure current user is an organizer
			event.organizers.add(current_user)
			event.organizers.add(*co_organizers)
			# organizers should be attendees by default, too. 
			event.attendees.add(current_user)
			event.save()

			new_event_notification(event, location)

			messages.add_message(request, messages.INFO, 'The event has been created.')
			return HttpResponseRedirect(reverse('gather_view_event', args=(event.location.slug, event.id, event.slug)))
		else:
			print "form error"
			print form.errors

	else:
		form = EventForm()
	return render(request, 'gather_event_create.html', {'form': form, 'current_user': current_user, 'user_list': json.dumps(user_list), 'is_event_admin': is_event_admin, 'location': location})

@login_required
def edit_event(request, event_id, event_slug, location_slug=None):
	location = get_location(location_slug)
	current_user = request.user
	other_users = User.objects.exclude(id=current_user.id)
	user_list = [u.username for u in other_users]
	event = Event.objects.get(id=event_id)
	if not (request.user.is_authenticated() and request.user in event.organizers.all()):
		return HttpResponseRedirect("/")

	if request.method == 'POST':
		form = EventForm(request.POST, request.FILES, instance=event)
		if form.is_valid():
			event = form.save(commit=False)
			co_organizers = form.cleaned_data.get('co_organizers')
			# always make sure current user is an organizer
			event.organizers.add(current_user)
			event.organizers.add(*co_organizers)
			event.save()
			messages.add_message(request, messages.INFO, 'The event has been saved.')
			return HttpResponseRedirect(reverse('gather_view_event', args=(event.location.slug, event.id, event.slug)))
		else:
			print "form error"
			print form.errors

	else:
		# format the organizers as a string for use with the autocomplete field
		other_organizers = event.organizers.exclude(id=current_user.id)
		other_organizer_usernames = [u.username for u in other_organizers]
		other_organizer_usernames_string = ",".join(other_organizer_usernames)
		print event.organizers.all()
		form = EventForm(instance=event, initial={'co_organizers': other_organizer_usernames_string})
	return render(request, 'gather_event_edit.html', {'form': form, 'current_user': current_user, 'event_id': event_id, 'event_slug': event_slug, 'user_list': json.dumps(user_list), 'location': location})

def view_event(request, event_id, event_slug, location_slug=None):
	# XXX should we double check the associated location here? currently the
	# assumption is that if an event is being viewed under a specific location
	# that that will be reflected in the URL path. 
	try:
		event = Event.objects.get(id=event_id)
	except:
		print 'event not found'
		return HttpResponseRedirect('/404')

	location = get_location(location_slug)
	# if the slug has changed, redirect the viewer to the correct url (one
	# where the url matches the current slug)
	if event.slug != event_slug:
		print 'event slug has changed'
		# there's some tomfoolery here since we don't know for sure if the app
		# is being used in a project that specifies the location as part of the
		# url. probably a better way to do this...
		return HttpResponseRedirect(reverse('gather_view_event', args=(event.location.slug, event.id, event.slug)))

	# is the event in the past?
	today = timezone.now()
	print event.end
	if event.end < today:
		past = True
	else:
		past = False

	# set up for those without accounts to RSVP
	if request.user.is_authenticated():
		current_user = request.user
		new_user_form = None
		login_form = None
		location_event_admin = EventAdminGroup.objects.get(location=location)
		if request.user in location_event_admin.users.all():
			user_is_event_admin = True
		else:
			user_is_event_admin = False
	else:
		current_user = None
		new_user_form = NewUserForm()
		login_form = AuthenticationForm()
		user_is_event_admin = False

	# this is counter-intuitive - private events are viewable to those who have
	# the link. so private events are indeed shown to anyone (once they are approved). 
	if (event.status == 'live' and event.private) or event.is_viewable(current_user):
		if current_user and current_user in event.organizers.get_query_set():
			user_is_organizer = True
		else:
			user_is_organizer = False
		num_attendees = len(event.attendees.all())
		# only meaningful if event.limit > 0
		spots_remaining = event.limit - num_attendees
		event_email = 'event%d@%s' % (event.id, settings.LIST_DOMAIN)
		domain = Site.objects.get_current().domain
		return render(request, 'gather_event_view.html', {'event': event, 'current_user': current_user, <commit_msg>Added location stub to event email<commit_after>from django.contrib.auth.models import User, Group
from django.utils import timezone
from django.contrib.sites.models import Site
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from PIL import Image
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from gather.forms import EventForm, NewUserForm
import datetime
from django.contrib import messages
from django.conf import settings
from django.db.models import Q
from gather.models import Event, EventAdminGroup, EventSeries
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib import messages
import json
import requests
from django.views.decorators.csrf import csrf_exempt
from django.template.loader import get_template
from django.template import Context
from django.core.urlresolvers import reverse
from django.db.models.loading import get_model
from gather.emails import new_event_notification, event_approved_notification, event_published_notification
import logging

logger = logging.getLogger(__name__)

Location = get_model(*settings.LOCATION_MODEL.split(".", 1))

class LocationNotUniqueException(Exception):
	pass

def get_location(location_slug=None):
	if location_slug:
		location = Location.objects.get(slug=location_slug)
	else:
		if Location.objects.count() == 1:
			# the single object might not have pk=1 if a locationw as
			# previously created and then deleted, so by using the all() (after
			# checking there is only one location object) we aren't assuming
			# any particular id. 
			location = Location.objects.all()[0]
		else:
			raise LocationNotUniqueException("You did not specify a location and yet there is more than one location defined. Please specify a location.")
	return location

def event_guide(request, location_slug=None):
	location = get_location(location_slug)
	return render(request, 'gather_event_guide.html')

def create_event(request, location_slug=None):
	location = get_location(location_slug)
	current_user = request.user
	logger.debug("create_event: location:%s, user:%s" % (location, current_user))

	# if the user doesn't have a proper profile, then make sure they extend it first
	# TODO FIXME This is a direct dependency on an external app (the core app where the UserProfile model lives) 
	print current_user.id
	if current_user.id == None :
		messages.add_message(request, messages.INFO, 'We want to know who you are! Please create a profile before submitting an event.')
		return HttpResponseRedirect('/people/register/?next=/events/create/')
	elif current_user.is_authenticated and ((not current_user.profile.bio) or (not current_user.profile.image)):
		messages.add_message(request, messages.INFO, 'We want to know a bit more about you! Please complete your profile before submitting an event.')
		return HttpResponseRedirect('/people/%s/edit/' % current_user.username)

	other_users = User.objects.exclude(id=current_user.id)
	# get a list of users so that those creating an event can select from
	# existing users as event co-organizers
	user_list = [u.username for u in other_users]
	location_admin_group = EventAdminGroup.objects.get(location=location)
	if current_user in location_admin_group.users.all():
		is_event_admin = True
	else:
		is_event_admin = False

	if request.method == 'POST':
		logger.debug("create_event: POST=%s" % request.POST)
		form = EventForm(request.POST, request.FILES)
		if form.is_valid():
			event = form.save(commit=False)
			event.creator = current_user
			# associate this event with a specific location and admin group
			event.location = location
			event.admin = location_admin_group
			event.save()
			co_organizers = form.cleaned_data.get('co_organizers')
			# always make sure current user is an organizer
			event.organizers.add(current_user)
			event.organizers.add(*co_organizers)
			# organizers should be attendees by default, too. 
			event.attendees.add(current_user)
			event.save()

			new_event_notification(event, location)

			messages.add_message(request, messages.INFO, 'The event has been created.')
			return HttpResponseRedirect(reverse('gather_view_event', args=(event.location.slug, event.id, event.slug)))
		else:
			print "form error"
			print form.errors

	else:
		form = EventForm()
	return render(request, 'gather_event_create.html', {'form': form, 'current_user': current_user, 'user_list': json.dumps(user_list), 'is_event_admin': is_event_admin, 'location': location})

@login_required
def edit_event(request, event_id, event_slug, location_slug=None):
	location = get_location(location_slug)
	current_user = request.user
	other_users = User.objects.exclude(id=current_user.id)
	user_list = [u.username for u in other_users]
	event = Event.objects.get(id=event_id)
	if not (request.user.is_authenticated() and request.user in event.organizers.all()):
		return HttpResponseRedirect("/")

	if request.method == 'POST':
		form = EventForm(request.POST, request.FILES, instance=event)
		if form.is_valid():
			event = form.save(commit=False)
			co_organizers = form.cleaned_data.get('co_organizers')
			# always make sure current user is an organizer
			event.organizers.add(current_user)
			event.organizers.add(*co_organizers)
			event.save()
			messages.add_message(request, messages.INFO, 'The event has been saved.')
			return HttpResponseRedirect(reverse('gather_view_event', args=(event.location.slug, event.id, event.slug)))
		else:
			print "form error"
			print form.errors

	else:
		# format the organizers as a string for use with the autocomplete field
		other_organizers = event.organizers.exclude(id=current_user.id)
		other_organizer_usernames = [u.username for u in other_organizers]
		other_organizer_usernames_string = ",".join(other_organizer_usernames)
		print event.organizers.all()
		form = EventForm(instance=event, initial={'co_organizers': other_organizer_usernames_string})
	return render(request, 'gather_event_edit.html', {'form': form, 'current_user': current_user, 'event_id': event_id, 'event_slug': event_slug, 'user_list': json.dumps(user_list), 'location': location})

def view_event(request, event_id, event_slug, location_slug=None):
	# XXX should we double check the associated location here? currently the
	# assumption is that if an event is being viewed under a specific location
	# that that will be reflected in the URL path. 
	try:
		event = Event.objects.get(id=event_id)
	except:
		print 'event not found'
		return HttpResponseRedirect('/404')

	location = get_location(location_slug)
	# if the slug has changed, redirect the viewer to the correct url (one
	# where the url matches the current slug)
	if event.slug != event_slug:
		print 'event slug has changed'
		# there's some tomfoolery here since we don't know for sure if the app
		# is being used in a project that specifies the location as part of the
		# url. probably a better way to do this...
		return HttpResponseRedirect(reverse('gather_view_event', args=(event.location.slug, event.id, event.slug)))

	# is the event in the past?
	today = timezone.now()
	print event.end
	if event.end < today:
		past = True
	else:
		past = False

	# set up for those without accounts to RSVP
	if request.user.is_authenticated():
		current_user = request.user
		new_user_form = None
		login_form = None
		location_event_admin = EventAdminGroup.objects.get(location=location)
		if request.user in location_event_admin.users.all():
			user_is_event_admin = True
		else:
			user_is_event_admin = False
	else:
		current_user = None
		new_user_form = NewUserForm()
		login_form = AuthenticationForm()
		user_is_event_admin = False

	# this is counter-intuitive - private events are viewable to those who have
	# the link. so private events are indeed shown to anyone (once they are approved). 
	if (event.status == 'live' and event.private) or event.is_viewable(current_user):
		if current_user and current_user in event.organizers.get_query_set():
			user_is_organizer = True
		else:
			user_is_organizer = False
		num_attendees = len(event.attendees.all())
		# only meaningful if event.limit > 0
		spots_remaining = event.limit - num_attendees
		event_email = 'event%d@%s.%s' % (event.id, event.location.stub, settings.LIST_DOMAIN)
		domain = Site.objects.get_current().domain
		return render(request, 'gather_event_view.html', {'event': event, 'current_user': current_user, 
{'fraction_non_alphanumeric': 0.08937861694043374, 'fraction_numerical': 0.0009352896475127141, 'mean_word_length': 5.2210909090909094, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5851632', 'n_tokens_mistral': 5378, 'n_tokens_neox': 5063, 'n_words': 1558}