def group_create(request): """ create a form a user can use to create a custom group, on POST save this group to the database and automatically add the creator to the said group as a manager. """ nav_selected = "communities" if request.method == "POST": form = GroupForm(request.POST, request.FILES) if form.is_valid(): group = form.save() GroupUsers.objects.create(group=group, user=request.user, is_manager=True) Stream.objects.get(slug="community-create").enqueue( content_object=group, start=group.created) Record.objects.create_record(request.user, 'group_create', group) badge_cache.possibly_award_badge('created_a_community', user=request.user) messages.success(request, "%s has been created." % group) return redirect("group_detail", group_slug=group.slug) else: form = GroupForm() return render_to_response("groups/group_create.html", { "form": form, "site": Site.objects.get_current(), "nav_selected": nav_selected }, context_instance=RequestContext(request))
def register(request): if request.user.is_authenticated(): return redirect(reverse('home')) _request = None if request.method == 'POST': _request = request.POST.copy() else: _request = request.GET.copy() next_uri = _request.get( 'next', get_config('FIRST_LOGIN_REDIRECT_URL', reverse('first_steps'))) # rescuing poor users from infinite redirection loop if next_uri == get_config('LOGIN_URL', reverse('login')): next_uri = get_config('FIRST_LOGIN_REDIRECT_URL', reverse('first_steps')) register_form = RegisterForm() if request.method == 'POST': register_form = RegisterForm(request.POST) if register_form.is_valid(): register_form.save() username = register_form.cleaned_data['username'] password = register_form.cleaned_data['password1'] user = authenticate(username=username, password=password) if user is not None: auth_login(request, user) messages.success(request, "Welcome aboard, {0}.".format(user)) badges.possibly_award_badge("logged_in", user=user) return redirect(next_uri) return { 'register_form': register_form, 'next': next_uri, }
def group_external_link_only_create(request): """ create a form a user can use to create a minimal group which is added to the map but does not offer any features, since it has a home somewhere else on the web. on POST save this group to the database and automatically add the creator to the said group as a manager. """ nav_selected = "communities" if request.method == "POST": form = GroupExternalLinkOnlyForm(request.POST, request.FILES) link_form = ExternalLinkForm(request.POST, request.FILES) if form.is_valid() and link_form.is_valid(): group = form.save() link = link_form.save(group) GroupUsers.objects.create(group=group, user=request.user, is_manager=True) Stream.objects.get(slug="external-community-create").enqueue(content_object=group, start=group.created) Record.objects.create_record(request.user, 'group_create', group) badge_cache.possibly_award_badge('created_a_community', user=request.user) messages.success(request, _("%(group)s has been created.") % { 'group': group}) return redirect("group_detail", group_slug=group.slug) else: form = GroupExternalLinkOnlyForm() link_form = ExternalLinkForm() return render_to_response("groups/group_create.html", { "form": form, "link_form": link_form, "site": Site.objects.get_current(), "nav_selected": nav_selected, 'external_group': True, }, context_instance=RequestContext(request))
def group_create(request): """ create a form a user can use to create a custom group, on POST save this group to the database and automatically add the creator to the said group as a manager. """ nav_selected = "communities" if request.method == "POST": form = GroupForm(request.POST, request.FILES) if form.is_valid(): group = form.save() GroupUsers.objects.create(group=group, user=request.user, is_manager=True) Stream.objects.get(slug="community-create").enqueue(content_object=group, start=group.created) Record.objects.create_record(request.user, 'group_create', group) badge_cache.possibly_award_badge('created_a_community', user=request.user) messages.success(request, _("%(group)s has been created.") % { 'group': group}) return redirect("group_detail", group_slug=group.slug) else: form = GroupForm() return render_to_response("groups/group_create.html", { "form": form, "site": Site.objects.get_current(), "nav_selected": nav_selected, 'external_group': False, }, context_instance=RequestContext(request))
def test_lazy_user(self): u = User.objects.create_user("Lars Bak", "*****@*****.**", "x864lyfe") PlayerStat.objects.create(user=u, points=5001) badges.possibly_award_badge("points_awarded", user=u) self.assertEqual(u.badges_earned.count(), 1) self.assert_num_queries(1, lambda: u.badges_earned.get().badge)
def login(request): if request.user.is_authenticated(): return redirect(reverse('home')) _request = None if request.method == 'POST': _request = request.POST.copy() else: _request = request.GET.copy() next_uri = _request.get('next', get_config('LOGIN_REDIRECT_URL', reverse('home'))) # rescuing poor users from infinite redirection loop if next_uri == get_config('LOGIN_URL', reverse('login')): next_uri = get_config('LOGIN_REDIRECT_URL', reverse('home')) login_form = LoginForm() if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid() and login_form.user: auth_login(request, login_form.user) messages.success(request, "Hello, {0}.".format(login_form.user)) badges.possibly_award_badge("logged_in", user=login_form.user) return redirect(next_uri) return { 'login_form': login_form, 'next': next_uri, }
def register(request): if request.user.is_authenticated(): return redirect(reverse('home')) next_uri = request.REQUEST.get('next', get_config('FIRST_LOGIN_REDIRECT_URL', reverse('first_steps'))) # rescuing poor users from infinite redirection loop if next_uri == get_config('LOGIN_URL', reverse('login')): next_uri = get_config('FIRST_LOGIN_REDIRECT_URL', reverse('first_steps')) register_form = RegisterForm() if request.method == 'POST': register_form = RegisterForm(request.POST) if register_form.is_valid(): register_form.save() username = register_form.cleaned_data['username'] password = register_form.cleaned_data['password1'] user = authenticate(username=username, password=password) if user is not None: auth_login(request, user) messages.success(request, "Welcome aboard, {0}.".format(user)) badges.possibly_award_badge("logged_in", user=user) return redirect(next_uri) return { 'register_form': register_form, 'next': next_uri, }
def award_training_badges(qualification_level, user): task = Task.objects.filter(kind=Task.TRAINING, provides_qualification=qualification_level).first() UserQuestRelationship.objects.create(task=task, user=user, completed=True) user.profile.rating.add(score=task.points, user=None, ip_address=os.urandom(7).encode('hex')) badges.possibly_award_badge("points_awarded", user=user) badges.possibly_award_badge("skill_awarded", user=user, level=task.provides_qualification, force=True)
def create_new_user_accounts(self, user_names): """ Input is a list of users to initiate first login""" for user_name in user_names: user_name = User.objects.create_user(user_name, password='******') badges.possibly_award_badge("skill_awarded", user=user_name, level=7, force=True)
def db_metric_task(slug, num=1, **kwargs): met = Metric.objects.get(slug=slug) user = kwargs['user'] if met.unique: obj, created = MetricItem.objects.get_or_create( metric=met, user=user, item_content_type=kwargs['content_type'], item_object_id=kwargs['object_id'], site_id=settings.SITE_ID ) if created: obj.points = met.points obj.num = 1 obj.save() if met.points > 0: save_user_points(user, met.points) else: MetricItem.objects.create(metric=met, num=num, user=user, points=met.points, site_id=settings.SITE_ID) if met.points > 0: save_user_points(user, met.points) if kwargs.get('badge'): badges.possibly_award_badge(kwargs['badge']['event'], **kwargs['badge']['state'])
def user_creation(request): if request.user.is_authenticated(): return redirect('common:dashboard') user_create_form = forms.UserCreateForm(data=request.POST or None) if request.POST and user_create_form.is_valid(): user = user_create_form.save() user = authenticate( username=request.POST['username'], password=request.POST['password1']) auth_login(request, user) # In order to create an account they've already done the # first 2 training Tasks task = Task.objects.first() badges.possibly_award_badge('skill_awarded', user=user, level=task.provides_qualification) from django.contrib.contenttypes.models import ContentType from django.utils import timezone content_type = ContentType.objects.get_for_model(task) Point.objects.create(user=request.user, amount=task.points, content_type=content_type, object_id=task.id, created=timezone.now()) UserQuestRelationship.objects.create(task=task, user=user, completed=True) # Redirect them back b/c of the UserProfileForm return redirect('registration:user_creation_settings') return TemplateResponse(request, 'registration/create.jade', {'form': user_create_form})
def possibly_award_paparazzi_badge(sender, instance, created, **kwargs): if instance.approved: import badges try: user = User.objects.get(email=instance.email) badge_cache.possibly_award_badge('uploaded_an_image', user=user) except User.DoesNotExist: pass
def setUp(cls): cls.group = Group.objects.first() cls.task = Task.objects.first() cls.player = User.objects.create_user('player', password='******') badges.possibly_award_badge("skill_awarded", user=cls.player, level=7, force=True) cls.opponent = User.objects.create_user('opponent', password='******') badges.possibly_award_badge("skill_awarded", user=cls.opponent, level=7, force=True)
def setUp(cls): cls.group = Group.objects.first() cls.task = Task.objects.first() cls.user_names = ['UserA', 'UserB', 'UserC', 'UserD', 'UserE', 'UserF', 'UserG'] cls.users = {} for user_name in cls.user_names: cls.users[user_name] = User.objects.create_user(user_name, password='******') badges.possibly_award_badge("skill_awarded", user=cls.users[user_name], level=7, force=True)
def award_training_badges(qualification_level, user): task = Task.objects.filter(kind=Task.TRAINING, provides_qualification=qualification_level).first() UserQuestRelationship.objects.create(task=task, user=user, completed=True) from django.contrib.contenttypes.models import ContentType from django.utils import timezone content_type = ContentType.objects.get_for_model(task) Point.objects.create(user=user, amount=task.points, content_type=content_type, object_id=task.id, created=timezone.now()) badges.possibly_award_badge("skill_awarded", user=user, level=task.provides_qualification, force=True)
def redo_ranks(run_id): from brabeion import badges logger = redo_ranks.get_logger() try: user_run = Run.objects.get(pk=run_id) except Run.DoesNotExist: logger.error("[R- /U- /M- ] Run not found (pk={0}).".format(run_id)) return False map_obj = user_run.map if user_run.user == None: logger.info("[R-{0}/U- /M-{1}] Anonymous run, not" " processing the rank.".format(run_id, map_obj.id)) return user_best = BestRun.objects.get(map=map_obj, user=user_run.user) if not user_best.run_id == user_run.id: logger.info("[R-{0}/U-{1}/M-{2}] Not best run," " not processing the rank.".format(run_id, user_run.user_id, map_obj.id)) return runs = BestRun.objects.filter(map=map_obj) # ranked = player that receives points for his place ranked_count = len(BestRun.SCORING) # exclude banned users from scoring ranked = runs.exclude(user__is_active=False)[:ranked_count] try: if user_run.time >= ranked[ranked_count-1].run.time: logger.info("[R-{0}/U-{1}/M-{2}] Run won't affect scoring," " not processing the rank.".format(run_id, user_run.user_id, map_obj.id)) return except IndexError: pass old_rank = user_run.user.profile.map_position(map_obj.id) new_rank = None i = 0 for run in ranked: run.points = BestRun.SCORING[i] run.save() # FIXME it's 3 AM, sorry for that run.user.profile.points = BestRun.objects.filter(user=run.user).aggregate( Sum('points') )['points__sum'] or 0 run.user.profile.save() i += 1 if user_run.user_id == run.user_id: new_rank = i runs.exclude(id__in=ranked.values_list('id', flat=True)).update( points=0 ) badges.possibly_award_badge("rank_processed", user=user_run.user) logger.info("[R-{0}/U-{1}/M-{2}] {3}'s new map rank is {4} (was: {5})." \ .format(run_id, user_run.user_id, map_obj.id, user_run.user, new_rank, old_rank))
def quest_submit(request, task, bypass_post=False): # (TODO) Add validation check here at some point if request.POST or bypass_post: user_quest_relationship = task.user_relationship(request.user, False) if not user_quest_relationship.completed: request.user.profile.rating.add(score=task.points, user=None, ip_address=os.urandom(7).encode("hex")) badges.possibly_award_badge("points_awarded", user=request.user) badges.possibly_award_badge("skill_awarded", user=request.user, level=task.provides_qualification) user_quest_relationship.completed = True user_quest_relationship.save()
def handle(self, *args, **options): user = User.objects.get(username=args[0]) print user badges.possibly_award_badge("skill_awarded", user=user, level=1) task = Task.objects.first() # Required importing from django.contrib.contenttypes.models import ContentType from django.utils import timezone content_type = ContentType.objects.get_for_model(task) Point.objects.create(user=user, amount=task.points, content_type=content_type, object_id=task.id, created=timezone.now()) UserQuestRelationship.objects.create(task=task, user=user, completed=True) badges.possibly_award_badge("skill_awarded", user=user, level=2) task = Task.objects.get(pk=2) UserQuestRelationship.objects.create(task=task, user=user, completed=True) Point.objects.create(user=user, amount=task.points, content_type=content_type, object_id=task.id, created=timezone.now()) badges.possibly_award_badge("skill_awarded", user=user, level=3) task = Task.objects.get(pk=3) UserQuestRelationship.objects.create(task=task, user=user, completed=True) Point.objects.create(user=user, amount=task.points, content_type=content_type, object_id=task.id, created=timezone.now()) badges.possibly_award_badge("skill_awarded", user=user, level=4)
def recipe_vote(request): 'Recipe voting' if 'id' in request.GET: try: recipe_id = request.GET['id'] recipe = Recipe.objects.get(id=recipe_id) #if request.user != recipe.submitor: if 'ing' in request.GET: recipe.ingVote(request.user) elif 'theme' in request.GET: recipe.themeVote(request.user) elif 'overall' in request.GET: recipe.overallVote(request.user) submitor = recipe.submitor.get_profile().awardRecipeLiked(1,request) badges.possibly_award_badge("vote_submitted", user=request.user) except Recipe.DoesNotExist: raise Http404('Recipe Not Found') if 'HTTP_REFERER' in request.META: return HttpResponseRedirect(request.META['HTTP_REFERER']) return HttpResponseRedirect('/')
def _create_new(self, request, *args, **kwargs): try: filtered_checkpoints = ";".join([v for v in \ request.form.cleaned_data['checkpoints'].split(";") if float(v) != 0.0]) except ValueError: filtered_checkpoints = "" run = Run( map = request.form.map, server = request.server, user = request.form.user, nickname = request.form.cleaned_data['nickname'], clan = request.form.cleaned_data['clan'], time = request.form.cleaned_data['time'], checkpoints = filtered_checkpoints, ) run.save() tasks.redo_ranks.apply(args=[run.id]) if request.form.user != None: request.form.user.profile.update_connection(request.server) badges.possibly_award_badge("run_finished", user=request.form.user, run=run) return run
def _create_new(self, request, *args, **kwargs): try: filtered_checkpoints = ";".join([v for v in \ request.form.cleaned_data['checkpoints'].split(";") if float(v) != 0.0]) except ValueError: filtered_checkpoints = "" run = Run( map=request.form.map, server=request.server, user=request.form.user, nickname=request.form.cleaned_data['nickname'], clan=request.form.cleaned_data['clan'], time=request.form.cleaned_data['time'], checkpoints=filtered_checkpoints, ) run.save() tasks.redo_ranks.apply(args=[run.id]) if request.form.user != None: request.form.user.profile.update_connection(request.server) badges.possibly_award_badge("run_finished", user=request.form.user, run=run) return run
def test_award(self): u = User.objects.create_user("Lars Bak", "*****@*****.**", "x864lyfe") PlayerStat.objects.create(user=u) badges.possibly_award_badge("points_awarded", user=u) self.assertEqual(u.badges_earned.count(), 0) u.stats.points += 5001 u.stats.save() badges.possibly_award_badge("points_awarded", user=u) self.assertEqual(u.badges_earned.count(), 1) self.assertEqual(u.badges_earned.all()[0].badge.name, "Bronze") badges.possibly_award_badge("points_awarded", user=u) self.assertEqual(u.badges_earned.count(), 1) u.stats.points += 2500 badges.possibly_award_badge("points_awarded", user=u) self.assertEqual(u.badges_earned.count(), 2)
def possibly_award_shout_out_badge(sender, instance, created, **kwargs): if instance.twitter_share or instance.facebook_share: import badges badge_cache.possibly_award_badge('opted_to_share_activity', user=instance.user)
def possibly_award_social_media_maven_badge(sender, instance, created, **kwargs): if instance.twitter_access_token or instance.facebook_access_token: import badges badge_cache.possibly_award_badge('linked_social_account', user=instance.user)
def possibly_award_follow_through_badge(sender, instance, created, **kwargs): if instance.entered_by: import badges badge_cache.possibly_award_badge('entered_commitment_card', user=instance.entered_by)
def possibly_award_gift_of_gab_badge(sender, instance, created, **kwargs): if created: import badges badge_cache.possibly_award_badge('created_a_comment', user=instance.user)
def submit(request): if request.method == 'POST': form = recipeNewSaveForm(request.POST,request.FILES) if form.is_valid(): from django.template.defaultfilters import slugify recipe = Recipe() recipe.name = form.cleaned_data['name'] recipe.published = datetime.datetime.now() recipe.yields = form.cleaned_data['yields'] recipe.summary = form.cleaned_data['summary'] recipe.instructions = form.cleaned_data['instructions'] #recipe.photos = form.cleaned_data['photos'] recipe.submitor = request.user #save the recipe because it needs a key before it can have many to many rels. recipe.save() # create a url, we will make sure it is unique by adding the id number to the end. url = form.cleaned_data['name'] + "-" + str(recipe.id) recipe.url = slugify(url) try: if request.FILES['photo']: file = request.FILES['photo'] photo = Photo.objects.create() photo.photo.save(file.name,file) photo.recipe_set.add(recipe) #now that we have the image lets resize it to a decent size #_handleImageResize(photo.photo) except: pass difficulty, dummy = Difficulty.objects.get_or_create(name=form.cleaned_data['difficulty']) difficulty.recipe_set.add(recipe) difficulty.save() course, dummy = Course.objects.get_or_create(name=form.cleaned_data['course']) course.recipe_set.add(recipe) course.save() for tagName in form.cleaned_data['tags'].split(","): if tagName != None: tag, dummy = Tag.objects.get_or_create(name=tagName.strip()) tag.recipe_set.add(recipe) tag.save() durObject, dummy = Duration.objects.get_or_create( duration= form.cleaned_data['durations'] ) durObject.recipe_set.add(recipe) durObject.save() theme = CookoffTheme.objects.currentTheme() theme.recipes.add(recipe) theme.save() recipe = _ingredientsProcess(form.cleaned_data['ingredients'].rstrip('\n'), recipe) badges.possibly_award_badge("recipe_submitted", user=request.user) brabeion.signals.badge_awarded.connect(_get_badge) recipe.save() createUserProfile(request.user) profile = request.user.get_profile() profile.awardRecipe(1,request) redirectTo = "/recipes/recipe/%s" % recipe.url return HttpResponseRedirect(redirectTo) else: form = recipeNewSaveForm() variables = RequestContext(request, { 'form': form }) return render_to_response('submit.html', response_data, context_instance = variables)
def possibly_award_unbelievable_badge(sender, instance, created, **kwargs): if instance.is_completed: import badges badge_cache.possibly_award_badge('completed_an_action', user=instance.user)
def possibly_award_trendsetter_badge(sender, instance, created, **kwargs): if created and instance.question == 'pledge': import badges badge_cache.possibly_award_badge('took_the_pledge', user=instance.contributor.user)
def handle(self, *args, **options): user = User.objects.get(username=args[0]) print user badges.possibly_award_badge("skill_awarded", user=user, level=1) task = Task.objects.first() user.profile.rating.add(score=task.points, user=None, ip_address=os.urandom(7).encode("hex")) UserQuestRelationship.objects.create(task=task, user=user, completed=True) badges.possibly_award_badge("skill_awarded", user=user, level=2) task = Task.objects.get(pk=2) UserQuestRelationship.objects.create(task=task, user=user, completed=True) user.profile.rating.add(score=task.points, user=None, ip_address=os.urandom(7).encode("hex")) badges.possibly_award_badge("points_awarded", user=user) badges.possibly_award_badge("skill_awarded", user=user, level=3) task = Task.objects.get(pk=3) UserQuestRelationship.objects.create(task=task, user=user, completed=True) user.profile.rating.add(score=task.points, user=None, ip_address=os.urandom(7).encode("hex")) badges.possibly_award_badge("points_awarded", user=user) badges.possibly_award_badge("skill_awarded", user=user, level=4)
def possibly_award_dogged_badge(sender, instance, created, **kwargs): if instance.is_completed and instance.date_committed: import badges badge_cache.possibly_award_badge('completed_a_commitment', user=instance.user)
def possibly_award_storyteller_badge(sender, instance, created, **kwargs): if instance.location and instance.building_type and instance.about and \ instance.get_profile().first_name and instance.get_profile().last_name: import badges badge_cache.possibly_award_badge('completed_profile', user=instance.user)
def possibly_award_hosting_hero_badge(sender, instance, created, **kwargs): if created: import badges badge_cache.possibly_award_badge('created_an_event', user=instance.creator)
def possibly_award_action_badge(sender, instance, created, **kwargs): if instance.is_completed: import badges # this is a hack to make sure all Badge Classes have been loaded into the BadgeCache from badges import event_name badge_cache.possibly_award_badge(event_name(instance.action), user=instance.user)
def currentThemeWinners(self): "Get the top three voted recipes and set the winners" recipesbyrank = self.recipes.all().order_by('-votes')[:3] self.winning_recipe = recipesbyrank[0] #we will award a badge, since we know what badge to award we will not check in the badge class #instead we will pass a keyword of what and a number of the place badges.possibly_award_badge("end_theme", user=recipesbyrank[0].submitor, theme=self, award="overall1") self.runner_up_recipe = recipesbyrank[1] badges.possibly_award_badge("end_theme", user=recipesbyrank[1].submitor, theme=self, award="overall2") self.third_place_recipe = recipesbyrank[2] badges.possibly_award_badge("end_theme", user=recipesbyrank[2].submitor, theme=self, award="overall3") recipesbyrank = self.recipes.all().order_by('-votes_theme')[:3] self.winning_theme_recipe = recipesbyrank[0] badges.possibly_award_badge("end_theme", user=recipesbyrank[0].submitor, theme=self, award="themeuse1") self.runner_up_theme_recipe = recipesbyrank[1] badges.possibly_award_badge("end_theme", user=recipesbyrank[1].submitor, theme=self, award="themeuse2") self.third_place_theme_recipe = recipesbyrank[2] badges.possibly_award_badge("end_theme", user=recipesbyrank[2].submitor, theme=self, award="themeuse3") recipesbyrank = self.recipes.all().order_by('-votes_ing')[:3] self.winning_ing_recipe = recipesbyrank[0] badges.possibly_award_badge("end_theme", user=recipesbyrank[0].submitor, theme=self, award="ing1") self.runner_up_ing_recipe = recipesbyrank[1] badges.possibly_award_badge("end_theme", user=recipesbyrank[1].submitor, theme=self, award="ing2") self.third_place_ing_recipe = recipesbyrank[2] badges.possibly_award_badge("end_theme", user=recipesbyrank[2].submitor, theme=self, award="ing3") self.save() return self
def possibly_award_momentum_builder_badge(sender, instance, created, **kwargs): if created: import badges badge_cache.possibly_award_badge('invited_a_friend', user=instance.user)
def award_badges(event, user): assert isinstance(event, str) from brabeion import badges badges.possibly_award_badge(event, user=user)