def get(self, event_key=None):
        self._require_login()
        self._require_registration()

        if event_key is None:
            events = EventHelper.getEventsWithinADay()
            EventHelper.sort_events(events)
            self.template_values['events'] = events
            self.response.out.write(jinja2_engine.render('mytba_add_hot_matches_base.html', self.template_values))
            return

        event = Event.get_by_id(event_key)
        if not event:
            self.abort(404)

        subscriptions_future = Subscription.query(
            Subscription.model_type==ModelType.MATCH,
            Subscription.notification_types==NotificationType.UPCOMING_MATCH,
            ancestor=self.user_bundle.account.key).fetch_async(projection=[Subscription.model_key])

        matches = []
        if event.matchstats and 'match_predictions' in event.matchstats:
            match_predictions = event.matchstats['match_predictions']
            max_hotness = 0
            min_hotness = float('inf')
            for match in event.matches:
                if not match.has_been_played and match.key.id() in match_predictions:
                    prediction = match_predictions[match.key.id()]
                    red_score = prediction['red']['score']
                    blue_score = prediction['blue']['score']
                    if red_score > blue_score:
                        winner_score = red_score
                        loser_score = blue_score
                    else:
                        winner_score = blue_score
                        loser_score = red_score

                    hotness = winner_score + 2.0*loser_score  # Favor close high scoring matches

                    max_hotness = max(max_hotness, hotness)
                    min_hotness = min(min_hotness, hotness)
                    match.hotness = hotness
                    matches.append(match)

        existing_subscriptions = set()
        for sub in subscriptions_future.get_result():
            existing_subscriptions.add(sub.model_key)

        hot_matches = []
        for match in matches:
            match.hotness = 100 * (match.hotness - min_hotness) / (max_hotness - min_hotness)
            match.already_subscribed = match.key.id() in existing_subscriptions
            hot_matches.append(match)
        hot_matches = sorted(hot_matches, key=lambda match: -match.hotness)
        matches_dict = {'qm': hot_matches[:25]}

        self.template_values['event'] = event
        self.template_values['matches'] = matches_dict

        self.response.out.write(jinja2_engine.render('mytba_add_hot_matches.html', self.template_values))
    def get(self, event_key=None):
        self._require_registration()

        if event_key is None:
            events = EventHelper.getEventsWithinADay()
            EventHelper.sort_events(events)
            self.template_values['events'] = events
            self.response.out.write(jinja2_engine.render('mytba_add_hot_matches_base.html', self.template_values))
            return

        event = Event.get_by_id(event_key)
        if not event:
            self.abort(404)

        subscriptions_future = Subscription.query(
            Subscription.model_type==ModelType.MATCH,
            Subscription.notification_types==NotificationType.UPCOMING_MATCH,
            ancestor=self.user_bundle.account.key).fetch_async(projection=[Subscription.model_key])

        matches = []
        if event.matchstats and 'match_predictions' in event.matchstats:
            match_predictions = event.matchstats['match_predictions']
            max_hotness = 0
            min_hotness = float('inf')
            for match in event.matches:
                if not match.has_been_played and match.key.id() in match_predictions:
                    prediction = match_predictions[match.key.id()]
                    red_score = prediction['red']['score']
                    blue_score = prediction['blue']['score']
                    if red_score > blue_score:
                        winner_score = red_score
                        loser_score = blue_score
                    else:
                        winner_score = blue_score
                        loser_score = red_score

                    hotness = winner_score + 2.0*loser_score  # Favor close high scoring matches

                    max_hotness = max(max_hotness, hotness)
                    min_hotness = min(min_hotness, hotness)
                    match.hotness = hotness
                    matches.append(match)

        existing_subscriptions = set()
        for sub in subscriptions_future.get_result():
            existing_subscriptions.add(sub.model_key)

        hot_matches = []
        for match in matches:
            match.hotness = 100 * (match.hotness - min_hotness) / (max_hotness - min_hotness)
            match.already_subscribed = match.key.id() in existing_subscriptions
            hot_matches.append(match)
        hot_matches = sorted(hot_matches, key=lambda match: -match.hotness)
        matches_dict = {'qm': hot_matches[:25]}

        self.template_values['event'] = event
        self.template_values['matches'] = matches_dict

        self.response.out.write(jinja2_engine.render('mytba_add_hot_matches.html', self.template_values))
    def get(self):
        super(SuggestDesignsReviewController, self).get()
        if self.request.get('action') and self.request.get('id'):
            # Fast-path review
            self._fastpath_review()

        suggestions = Suggestion.query().filter(
            Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
            Suggestion.target_model == "robot").fetch(limit=50)

        reference_keys = []
        for suggestion in suggestions:
            reference_key = suggestion.contents['reference_key']
            reference = Media.create_reference(
                suggestion.contents['reference_type'],
                reference_key)
            reference_keys.append(reference)

        reference_futures = ndb.get_multi_async(reference_keys)
        references = map(lambda r: r.get_result(), reference_futures)
        suggestions_and_references = zip(suggestions, references)

        self.template_values.update({
            "suggestions_and_references": suggestions_and_references,
        })

        self.response.out.write(jinja2_engine.render('suggestions/suggest_designs_review.html', self.template_values))
Пример #4
0
    def get(self):
        self._require_login("/suggest/match/video?match=%s" %
                            self.request.get("match_key"))

        if not self.request.get("match_key"):
            self.redirect("/", abort=True)

        match_future = Match.get_by_id_async(self.request.get("match_key"))
        event_future = Event.get_by_id_async(
            self.request.get("match_key").split("_")[0])
        match = match_future.get_result()
        event = event_future.get_result()

        if not match or not event:
            self.abort(404)

        self.template_values.update({
            "status": self.request.get("status"),
            "event": event,
            "match": match,
        })

        self.response.out.write(
            jinja2_engine.render('suggest_match_video.html',
                                 self.template_values))
    def get(self):
        team_key = self.request.get("team_key")
        year_str = self.request.get("year")

        self._require_registration()

        if not team_key or not year_str:
            self.redirect("/", abort=True)

        year = int(year_str)
        team_future = Team.get_by_id_async(self.request.get("team_key"))
        team = team_future.get_result()
        if not team:
            self.redirect("/", abort=True)

        media_key_futures = Media.query(Media.references == team.key, Media.year == year).fetch_async(500, keys_only=True)
        social_media_future = media_query.TeamSocialMediaQuery(team.key.id()).fetch_async()

        media_futures = ndb.get_multi_async(media_key_futures.get_result())
        medias = [media_future.get_result() for media_future in media_futures]
        medias_by_slugname = MediaHelper.group_by_slugname(medias)

        social_medias = sorted(social_media_future.get_result(), key=MediaHelper.social_media_sorter)
        social_medias = filter(lambda m: m.media_type_enum == MediaType.INSTAGRAM_PROFILE, social_medias)  # we only allow IG media, so only show IG profile

        self.template_values.update({
            "medias_by_slugname": medias_by_slugname,
            "social_medias": social_medias,
            "status": self.request.get("status"),
            "team": team,
            "year": year,
        })

        self.response.out.write(jinja2_engine.render('suggestions/suggest_team_media.html', self.template_values))
    def post(self):
        self._require_login()

        status, failures = SuggestionCreator.createOffseasonEventSuggestion(
            author_account_key=self.user_bundle.account.key,
            name=self.request.get("name", None),
            start_date=self.request.get("start_date", None),
            end_date=self.request.get("end_date", None),
            website=self.request.get("website", None),
            address=self.request.get("venue_address", None),
        )
        if status != 'success':
            # Don't completely wipe form data if validation fails
            self.template_values.update({
                'status': status,
                'failures': failures,
                'name': self.request.get('name', None),
                'start_date': self.request.get('start_date', None),
                'end_date': self.request.get('end_date', None),
                'website': self.request.get('website', None),
                'venue_address': self.request.get('venue_address', None),
            })
            self.response.out.write(
                jinja2_engine.render('suggest_offseason_event.html', self.template_values))
        else:
            self.redirect('/suggest/offseason?status=%s' % status)
    def _render(self, year=None, explicit_year=False):
        events = event_query.EventListQuery(year).fetch()
        EventHelper.sort_events(events)

        week_events = EventHelper.groupByWeek(events)

        district_enums = set()
        for event in events:
            if event.event_district_enum is not None and event.event_district_enum != DistrictType.NO_DISTRICT:
                district_enums.add(event.event_district_enum)

        districts = []  # a tuple of (district abbrev, district name)
        for district_enum in district_enums:
            districts.append((DistrictType.type_abbrevs[district_enum],
                              DistrictType.type_names[district_enum]))
        districts = sorted(districts, key=lambda d: d[1])

        self.template_values.update({
            "events": events,
            "explicit_year": explicit_year,
            "selected_year": year,
            "valid_years": self.VALID_YEARS,
            "week_events": week_events,
            "districts": districts,
        })

        return jinja2_engine.render('event_list.html', self.template_values)
Пример #8
0
    def _render(self, year):
        year = int(year)
        avatars = []
        shards = memcache.get_multi(['{}avatars_{}'.format(year, i) for i in xrange(10)])
        if len(shards) == 10:  # If missing a shard, must refetch all
            for _, shard in sorted(shards.items(), key=lambda kv: kv[0]):
                avatars += shard

        if not avatars:
            avatars_future = Media.query(Media.media_type_enum == MediaType.AVATAR, Media.year == year).fetch_async()
            avatars = sorted(avatars_future.get_result(), key=lambda a: int(a.references[0].id()[3:]))

            shards = {}
            size = len(avatars) / 10 + 1
            for i in xrange(10):
                start = i * size
                end = start + size
                shards['{}avatars_{}'.format(year, i)] = avatars[start:end]
            memcache.set_multi(shards, 60*60*24)

        self.template_values.update({
            'year': year,
            'avatars': avatars,
        })
        return jinja2_engine.render('avatars.html', self.template_values)
Пример #9
0
    def _render(self, *args, **kw):
        avatars = []
        shards = memcache.get_multi(
            ['2018avatars_{}'.format(i) for i in xrange(10)])
        if len(shards) == 10:  # If missing a shard, must refetch all
            for _, shard in sorted(shards.items(), key=lambda kv: kv[0]):
                avatars += shard

        if not avatars:
            avatars_future = Media.query(
                Media.media_type_enum == MediaType.AVATAR).fetch_async()
            avatars = sorted(avatars_future.get_result(),
                             key=lambda a: int(a.references[0].id()[3:]))

            shards = {}
            size = len(avatars) / 10 + 1
            for i in xrange(10):
                start = i * size
                end = start + size
                shards['2018avatars_{}'.format(i)] = avatars[start:end]
            memcache.set_multi(shards, 60 * 60 * 24)

        self.template_values.update({
            'avatars': avatars,
        })
        return jinja2_engine.render('avatars2018.html', self.template_values)
Пример #10
0
    def _render(self, *args, **kw):
        awards_future = Award.query(
            Award.award_type_enum == AwardType.CHAIRMANS,
            Award.event_type_enum == EventType.CMP_FINALS).fetch_async()

        teams_by_year = defaultdict(list)
        for award in awards_future.get_result():
            for team_key in award.team_list:
                teams_by_year[award.year].append((
                    team_key.get_async(),
                    award.event.get_async(),
                    award,
                    media_query.TeamTagMediasQuery(
                        team_key.id(), MediaTag.CHAIRMANS_VIDEO).fetch_async(),
                    media_query.TeamTagMediasQuery(
                        team_key.id(),
                        MediaTag.CHAIRMANS_PRESENTATION).fetch_async(),
                    media_query.TeamTagMediasQuery(
                        team_key.id(), MediaTag.CHAIRMANS_ESSAY).fetch_async(),
                ))

        teams_by_year = sorted(teams_by_year.items(), key=lambda (k, v): -k)
        for _, tea in teams_by_year:
            tea.sort(key=lambda x: x[1].get_result().start_date)

        self.template_values.update({
            'teams_by_year': teams_by_year,
        })

        return jinja2_engine.render('hof.html', self.template_values)
Пример #11
0
    def _render(self, event_key):
        event = Event.get_by_id(event_key)
        if not event:
            self.abort(404)
            return
        medias_future = media_query.EventTeamsPreferredMediasQuery(event_key).fetch_async()
        next_match = MatchHelper.upcomingMatches(event.matches, num=1)
        next_match = next_match[0] if next_match else None
        team_and_medias = []
        if next_match:
            # Organize medias by team
            teams = ndb.get_multi([ndb.Key(Team, team_key) for team_key in next_match.alliances['red']['teams'] + next_match.alliances['blue']['teams']])
            image_medias = MediaHelper.get_images([media for media in medias_future.get_result()])
            team_medias = defaultdict(list)
            for image_media in image_medias:
                for reference in image_media.references:
                    team_medias[reference].append(image_media)

            stations = ['Red 1', 'Red 2', 'Red 3', 'Blue 1', 'Blue 2', 'Blue 3']
            for i, team in enumerate(teams):
                team_and_medias.append((team, stations[i], team_medias.get(team.key, [])))

        self.template_values.update({
            'event': event,
            'next_match': next_match,
            'teams_and_media': team_and_medias,
        })
        return jinja2_engine.render('nextmatch.html', self.template_values)
    def get(self):
        suggestions = Suggestion.query().filter(
            Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
            Suggestion.target_model == "offseason-event")

        year = datetime.now().year
        year_events_future = EventListQuery(year).fetch_async()
        last_year_events_future = EventListQuery(year - 1).fetch_async()
        events_and_ids = [self._create_candidate_event(suggestion) for suggestion in suggestions]

        year_events = year_events_future.get_result()
        year_offseason_events = [e for e in year_events if e.event_type_enum == EventType.OFFSEASON]
        last_year_events = last_year_events_future.get_result()
        last_year_offseason_events = [e for e in last_year_events if e.event_type_enum == EventType.OFFSEASON]

        similar_events = [self._get_similar_events(event[1], year_offseason_events) for event in events_and_ids]
        similar_last_year = [self._get_similar_events(event[1], last_year_offseason_events) for event in events_and_ids]

        self.template_values.update({
            'success': self.request.get("success"),
            'event_key': self.request.get("event_key"),
            'events_and_ids': events_and_ids,
            'similar_events': similar_events,
            'similar_last_year': similar_last_year,
        })
        self.response.out.write(
            jinja2_engine.render('suggestions/suggest_offseason_event_review_list.html', self.template_values))
Пример #13
0
    def _render(self, page=''):
        page_labels = []
        for curPage in self.VALID_PAGES:
            if curPage == 1:
                label = '1-999'
            else:
                label = "{}'s".format((curPage - 1) * self.TEAMS_PER_PAGE)
            page_labels.append(label)
            if curPage == page:
                cur_page_label = label

        teams_1 = team_query.TeamListQuery(2 * (page - 1)).fetch_async()
        teams_2 = team_query.TeamListQuery(2 * (page - 1) + 1).fetch_async()
        teams = teams_1.get_result() + teams_2.get_result()

        num_teams = len(teams)
        middle_value = num_teams / 2
        if num_teams % 2 != 0:
            middle_value += 1
        teams_a, teams_b = teams[:middle_value], teams[middle_value:]

        self.template_values.update({
            "teams_a": teams_a,
            "teams_b": teams_b,
            "num_teams": num_teams,
            "page_labels": page_labels,
            "cur_page_label": cur_page_label,
            "current_page": page
        })

        return jinja2_engine.render('team_list.html', self.template_values)
    def get(self):
        super(SuggestSocialMediaReviewController, self).get()
        suggestions = Suggestion.query().filter(
            Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
                Suggestion.target_model == "social-media").fetch(limit=50)

        reference_keys = []
        for suggestion in suggestions:
            reference_key = suggestion.contents['reference_key']
            reference = Media.create_reference(
                suggestion.contents['reference_type'], reference_key)
            reference_keys.append(reference)

        reference_futures = ndb.get_multi_async(reference_keys)
        references = map(lambda r: r.get_result(), reference_futures)
        suggestions_and_references = zip(suggestions, references)

        self.template_values.update({
            "suggestions_and_references":
            suggestions_and_references,
        })

        self.response.out.write(
            jinja2_engine.render('suggestions/suggest_team_social_review.html',
                                 self.template_values))
 def get(self):
     self._require_registration()
     self.template_values.update({
         "status": self.request.get("status"),
     })
     self.response.out.write(
         jinja2_engine.render('suggest_offseason_event.html', self.template_values))
    def get(self):
        self._require_registration()

        if not self.request.get("event_key"):
            self.redirect("/", abort=True)

        event_future = Event.get_by_id_async(self.request.get("event_key"))
        event = event_future.get_result()

        if not event:
            self.abort(404)

        medias_future = EventMediasQuery(event.key_name).fetch_async()
        medias = medias_future.get_result()
        medias_by_slugname = MediaHelper.group_by_slugname(medias)

        self.template_values.update({
            "status": self.request.get("status"),
            "medias_by_slugname": medias_by_slugname,
            "event": event,
        })

        self.response.out.write(
            jinja2_engine.render('suggestions/suggest_event_media.html',
                                 self.template_values))
    def get(self):

        if self.request.get('action') and self.request.get('id'):
            # Fast-path review
            self._fastpath_review()

        suggestions = Suggestion.query().filter(
            Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
                Suggestion.target_model == "robot").fetch(limit=50)

        reference_keys = []
        for suggestion in suggestions:
            reference_key = suggestion.contents['reference_key']
            reference = Media.create_reference(
                suggestion.contents['reference_type'], reference_key)
            reference_keys.append(reference)

        reference_futures = ndb.get_multi_async(reference_keys)
        references = map(lambda r: r.get_result(), reference_futures)
        suggestions_and_references = zip(suggestions, references)

        self.template_values.update({
            "suggestions_and_references":
            suggestions_and_references,
        })

        self.response.out.write(
            jinja2_engine.render('suggestions/suggest_designs_review.html',
                                 self.template_values))
 def get(self):
     self._require_registration()
     self.template_values.update({
         "status": self.request.get("status"),
     })
     self.response.out.write(
         jinja2_engine.render('suggestions/suggest_offseason_event.html', self.template_values))
    def post(self):
        self._require_registration()

        status, failures = SuggestionCreator.createOffseasonEventSuggestion(
            author_account_key=self.user_bundle.account.key,
            name=self.request.get("name", None),
            start_date=self.request.get("start_date", None),
            end_date=self.request.get("end_date", None),
            website=self.request.get("website", None),
            address=self.request.get("venue_address", None),
        )
        if status != 'success':
            # Don't completely wipe form data if validation fails
            self.template_values.update({
                'status':
                status,
                'failures':
                failures,
                'name':
                self.request.get('name', None),
                'start_date':
                self.request.get('start_date', None),
                'end_date':
                self.request.get('end_date', None),
                'website':
                self.request.get('website', None),
                'venue_address':
                self.request.get('venue_address', None),
            })
            self.response.out.write(
                jinja2_engine.render('suggest_offseason_event.html',
                                     self.template_values))
        else:
            self.redirect('/suggest/offseason?status=%s' % status)
Пример #20
0
    def get(self):
        team_key = self.request.get("team_key")
        year_str = self.request.get("year")

        self._require_registration()

        if not team_key or not year_str:
            self.redirect("/", abort=True)

        year = int(year_str)
        team_future = Team.get_by_id_async(self.request.get("team_key"))
        team = team_future.get_result()
        if not team:
            self.redirect("/", abort=True)

        media_key_futures = Media.query(Media.references == team.key, Media.year == year).fetch_async(500, keys_only=True)
        media_futures = ndb.get_multi_async(media_key_futures.get_result())
        medias = [media_future.get_result() for media_future in media_futures]
        medias_by_slugname = MediaHelper.group_by_slugname(medias)

        self.template_values.update({
            "status": self.request.get("status"),
            "team": team,
            "year": year,
            "medias_by_slugname": medias_by_slugname,
        })

        self.response.out.write(jinja2_engine.render('suggestions/suggest_team_media.html', self.template_values))
Пример #21
0
    def get(self):
        suggestions = Suggestion.query().filter(
            Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
            Suggestion.target_model == "offseason-event")

        year = datetime.now().year
        year_events_future = EventListQuery(year).fetch_async()
        last_year_events_future = EventListQuery(year - 1).fetch_async()
        events_and_ids = [self._create_candidate_event(suggestion) for suggestion in suggestions]

        year_events = year_events_future.get_result()
        year_offseason_events = [e for e in year_events if e.event_type_enum == EventType.OFFSEASON]
        last_year_events = last_year_events_future.get_result()
        last_year_offseason_events = [e for e in last_year_events if e.event_type_enum == EventType.OFFSEASON]

        similar_events = [self._get_similar_events(event[1], year_offseason_events) for event in events_and_ids]
        similar_last_year = [self._get_similar_events(event[1], last_year_offseason_events) for event in events_and_ids]

        self.template_values.update({
            'success': self.request.get("success"),
            'event_key': self.request.get("event_key"),
            'events_and_ids': events_and_ids,
            'similar_events': similar_events,
            'similar_last_year': similar_last_year,
        })
        self.response.out.write(
            jinja2_engine.render('suggestions/suggest_offseason_event_review_list.html', self.template_values))
Пример #22
0
    def get(self):
        team_key = self.request.get("team_key")

        self._require_registration()

        if not team_key:
            self.redirect("/", abort=True)

        team_future = Team.get_by_id_async(self.request.get("team_key"))
        team = team_future.get_result()
        if not team:
            self.redirect("/", abort=True)

        media_key_futures = Media.query(Media.references == team.key,
                                        Media.year == None).fetch_async(
                                            500, keys_only=True)
        media_futures = ndb.get_multi_async(media_key_futures.get_result())
        medias = [media_future.get_result() for media_future in media_futures]
        social_medias = MediaHelper.get_socials(medias)

        self.template_values.update({
            "status": self.request.get("status"),
            "team": team,
            "social_medias": social_medias,
        })

        self.response.out.write(
            jinja2_engine.render('suggestions/suggest_team_social_media.html',
                                 self.template_values))
Пример #23
0
    def _render(self, page=''):
        page_labels = []
        for curPage in self.VALID_PAGES:
            if curPage == 1:
                label = '1-999'
            else:
                label = "{}'s".format((curPage - 1) * 1000)
            page_labels.append(label)
            if curPage == page:
                cur_page_label = label

        teams_1 = team_query.TeamListQuery(2 * (page - 1)).fetch_async()
        teams_2 = team_query.TeamListQuery(2 * (page - 1) + 1).fetch_async()
        teams = teams_1.get_result() + teams_2.get_result()

        num_teams = len(teams)
        middle_value = num_teams / 2
        if num_teams % 2 != 0:
            middle_value += 1
        teams_a, teams_b = teams[:middle_value], teams[middle_value:]

        self.template_values.update({
            "teams_a": teams_a,
            "teams_b": teams_b,
            "num_teams": num_teams,
            "page_labels": page_labels,
            "cur_page_label": cur_page_label,
            "current_page": page
        })

        return jinja2_engine.render('team_list.html', self.template_values)
Пример #24
0
    def get(self):
        team_key = self.request.get("team_key")

        self._require_registration()

        if not team_key:
            self.redirect("/", abort=True)

        team_future = Team.get_by_id_async(self.request.get("team_key"))
        team = team_future.get_result()
        if not team:
            self.redirect("/", abort=True)

        media_key_futures = Media.query(Media.references == team.key, Media.year == None).fetch_async(500, keys_only=True)
        media_futures = ndb.get_multi_async(media_key_futures.get_result())
        medias = [media_future.get_result() for media_future in media_futures]
        social_medias = MediaHelper.get_socials(medias)

        self.template_values.update({
            "status": self.request.get("status"),
            "team": team,
            "social_medias": social_medias,
        })

        self.response.out.write(jinja2_engine.render('suggestions/suggest_team_social_media.html', self.template_values))
    def get(self):
        team_key = self.request.get("team_key")
        year_str = self.request.get("year")

        self._require_login("/suggest/team/media?team_key=%s&year=%s" %
                            (team_key, year_str))

        if not team_key or not year_str:
            self.redirect("/", abort=True)

        year = int(year_str)
        team_future = Team.get_by_id_async(self.request.get("team_key"))
        team = team_future.get_result()
        media_key_futures = Media.query(Media.references == team.key,
                                        Media.year == year).fetch_async(
                                            500, keys_only=True)
        media_futures = ndb.get_multi_async(media_key_futures.get_result())
        medias_by_slugname = MediaHelper.group_by_slugname(
            [media_future.get_result() for media_future in media_futures])

        self.template_values.update({
            "status": self.request.get("status"),
            "team": team,
            "year": year,
            "medias_by_slugname": medias_by_slugname
        })

        self.response.out.write(
            jinja2_engine.render('suggest_team_media.html',
                                 self.template_values))
Пример #26
0
    def _render(self, *args, **kw):
        week_events = EventHelper.getWeekEvents()
        year = datetime.datetime.now().year
        special_webcasts = FirebasePusher.get_special_webcasts()
        self.template_values.update({
            "events":
            week_events,
            "year":
            year,
            "any_webcast_online":
            any(w.get('status') == 'online' for w in special_webcasts),
            "special_webcasts":
            special_webcasts,
        })

        insights = ndb.get_multi([
            ndb.Key(Insight, Insight.renderKeyName(year, insight_name))
            for insight_name in Insight.INSIGHT_NAMES.values()
        ])
        for insight in insights:
            if insight:
                self.template_values[insight.name] = insight

        return jinja2_engine.render('index/index_insights.html',
                                    self.template_values)
    def get(self, match_key):
        self._require_login()
        self._require_registration()

        match = Match.get_by_id(match_key)

        if not match:
            self.abort(404)

        user = self.user_bundle.account.key
        favorite = Favorite.query(Favorite.model_key==match_key, Favorite.model_type==ModelType.MATCH, ancestor=user).get()
        subscription = Subscription.query(Favorite.model_key==match_key, Favorite.model_type==ModelType.MATCH, ancestor=user).get()

        if not favorite and not subscription:  # New entry; default to being a favorite
            is_favorite = True
        else:
            is_favorite = favorite is not None

        enabled_notifications = [(en, NotificationType.render_names[en]) for en in NotificationType.enabled_match_notifications]

        self.template_values['match'] = match
        self.template_values['is_favorite'] = is_favorite
        self.template_values['subscription'] = subscription
        self.template_values['enabled_notifications'] = enabled_notifications

        self.response.out.write(jinja2_engine.render('mytba_match.html', self.template_values))
Пример #28
0
 def _render(self, *args, **kw):
     avatars_future = Media.query(Media.media_type_enum == MediaType.AVATAR).fetch_async()
     avatars = sorted(avatars_future.get_result(), key=lambda a: int(a.references[0].id()[3:]))
     self.template_values.update({
         'avatars': avatars,
     })
     return jinja2_engine.render('avatars2018.html', self.template_values)
Пример #29
0
    def get(self, match_key):
        self._require_registration()

        match = Match.get_by_id(match_key)

        if not match:
            self.abort(404)

        user = self.user_bundle.account.key
        favorite = Favorite.query(Favorite.model_key == match_key,
                                  Favorite.model_type == ModelType.MATCH,
                                  ancestor=user).get()
        subscription = Subscription.query(
            Favorite.model_key == match_key,
            Favorite.model_type == ModelType.MATCH,
            ancestor=user).get()

        if not favorite and not subscription:  # New entry; default to being a favorite
            is_favorite = True
        else:
            is_favorite = favorite is not None

        enabled_notifications = [
            (en, NotificationType.render_names[en])
            for en in NotificationType.enabled_match_notifications
        ]

        self.template_values['match'] = match
        self.template_values['is_favorite'] = is_favorite
        self.template_values['subscription'] = subscription
        self.template_values['enabled_notifications'] = enabled_notifications

        self.response.out.write(
            jinja2_engine.render('mytba_match.html', self.template_values))
    def post(self):
        self._require_registration()

        event_name = self.request.get("name", None)
        status, failures = SuggestionCreator.createOffseasonEventSuggestion(
            author_account_key=self.user_bundle.account.key,
            name=event_name,
            start_date=self.request.get("start_date", None),
            end_date=self.request.get("end_date", None),
            website=self.request.get("website", None),
            venue_name=self.request.get("venue_name", None),
            address=self.request.get("venue_address", None),
            city=self.request.get("venue_city", None),
            state=self.request.get("venue_state", None),
            country=self.request.get("venue_country", None)
        )
        if status != 'success':
            # Don't completely wipe form data if validation fails
            self.template_values.update({
                'status': status,
                'failures': failures,
                'name': self.request.get('name', None),
                'start_date': self.request.get('start_date', None),
                'end_date': self.request.get('end_date', None),
                'website': self.request.get('website', None),
                'venue_address': self.request.get('venue_address', None),
            })
            self.response.out.write(
                jinja2_engine.render('suggest_offseason_event.html', self.template_values))
        else:
            subject, body = self._gen_notification_email(event_name)
            SuggestionNotifier.send_admin_alert_email(subject, body)
            self.redirect('/suggest/offseason?status=%s' % status)
    def get(self, team_number):
        self._require_login()
        self._require_registration()

        team_key = 'frc{}'.format(team_number)
        team = Team.get_by_id(team_key)

        if not team:
            self.abort(404)

        user = self.user_bundle.account.key
        favorite = Favorite.query(Favorite.model_key==team_key, Favorite.model_type==ModelType.TEAM, ancestor=user).get()
        subscription = Subscription.query(Favorite.model_key==team_key, Favorite.model_type==ModelType.TEAM, ancestor=user).get()

        if not favorite and not subscription:  # New entry; default to being a favorite
            is_favorite = True
        else:
            is_favorite = favorite is not None

        enabled_notifications = [(en, NotificationType.render_names[en]) for en in NotificationType.enabled_team_notifications]

        self.template_values['team'] = team
        self.template_values['is_favorite'] = is_favorite
        self.template_values['subscription'] = subscription
        self.template_values['enabled_notifications'] = enabled_notifications

        self.response.out.write(jinja2_engine.render('mytba_team.html', self.template_values))
Пример #32
0
    def get(self):
        suggestions = Suggestion.query().filter(
            Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
            Suggestion.target_model == "event_media").fetch(limit=50)

        # Quick and dirty way to group images together
        suggestions = sorted(suggestions, key=lambda x: 0 if x.contents['media_type_enum'] in MediaType.image_types else 1)

        reference_keys = []
        for suggestion in suggestions:
            reference_key = suggestion.contents['reference_key']
            reference = Media.create_reference(
                suggestion.contents['reference_type'],
                reference_key)
            reference_keys.append(reference)

            if 'details_json' in suggestion.contents:
                suggestion.details = json.loads(suggestion.contents['details_json'])
                if 'image_partial' in suggestion.details:
                    suggestion.details['thumbnail'] = suggestion.details['image_partial'].replace('_l', '_m')

        reference_futures = ndb.get_multi_async(reference_keys)
        references = map(lambda r: r.get_result(), reference_futures)

        suggestions_and_references = zip(suggestions, references)

        self.template_values.update({
            "suggestions_and_references": suggestions_and_references,
        })

        self.response.out.write(jinja2_engine.render('suggestions/suggest_event_media_review_list.html', self.template_values))
Пример #33
0
    def _render(self, *args, **kw):
        year = datetime.datetime.now().year
        hou_event_keys_future = Event.query(
            Event.year == year,
            Event.event_type_enum.IN(EventType.CMP_EVENT_TYPES),
            Event.start_date <= datetime.datetime(2019, 4, 21)).fetch_async(
                keys_only=True)
        det_event_keys_future = Event.query(
            Event.year == year,
            Event.event_type_enum.IN(EventType.CMP_EVENT_TYPES),
            Event.start_date > datetime.datetime(2019, 4, 21)).fetch_async(
                keys_only=True)

        hou_events_futures = ndb.get_multi_async(
            hou_event_keys_future.get_result())
        det_events_futures = ndb.get_multi_async(
            det_event_keys_future.get_result())

        self.template_values.update({
            "hou_events": [e.get_result() for e in hou_events_futures],
            "det_events": [e.get_result() for e in det_events_futures],
            "year":
            year,
        })

        return jinja2_engine.render('index/index_champs.html',
                                    self.template_values)
Пример #34
0
    def _render(self, year):
        self.template_values.update({
            'valid_years': VALID_YEARS,
            'selected_year': year,
        })

        insights = ndb.get_multi([
            ndb.Key(Insight, Insight.renderKeyName(year, insight_name))
            for insight_name in Insight.INSIGHT_NAMES.values()
        ])
        last_updated = None
        for insight in insights:
            if insight:
                self.template_values[insight.name] = insight
                if last_updated is None:
                    last_updated = insight.updated
                else:
                    last_updated = max(last_updated, insight.updated)

        self.template_values[
            'year_specific_insights_template'] = 'event_partials/event_insights_{}.html'.format(
                year)
        self.template_values['last_updated'] = last_updated

        return jinja2_engine.render('insights_details.html',
                                    self.template_values)
    def post(self):
        self._require_registration()

        event_name = self.request.get("name", None)
        status, failures = SuggestionCreator.createOffseasonEventSuggestion(
            author_account_key=self.user_bundle.account.key,
            name=event_name,
            start_date=self.request.get("start_date", None),
            end_date=self.request.get("end_date", None),
            website=self.request.get("website", None),
            venue_name=self.request.get("venue_name", None),
            address=self.request.get("venue_address", None),
            city=self.request.get("venue_city", None),
            state=self.request.get("venue_state", None),
            country=self.request.get("venue_country", None)
        )
        if status != 'success':
            # Don't completely wipe form data if validation fails
            self.template_values.update({
                'status': status,
                'failures': failures,
                'name': self.request.get('name', None),
                'start_date': self.request.get('start_date', None),
                'end_date': self.request.get('end_date', None),
                'website': self.request.get('website', None),
                'venue_address': self.request.get('venue_address', None),
            })
            self.response.out.write(
                jinja2_engine.render('suggestions/suggest_offseason_event.html', self.template_values))
        else:
            subject, body = self._gen_notification_email(event_name)
            OutgoingNotificationHelper.send_admin_alert_email(subject, body)
            self.redirect('/suggest/offseason?status=%s' % status)
Пример #36
0
    def _render(self, *args, **kw):
        awards_future = Award.query(
            Award.award_type_enum==AwardType.CHAIRMANS,
            Award.event_type_enum==EventType.CMP_FINALS).fetch_async()

        teams_by_year = defaultdict(list)
        for award in awards_future.get_result():
            for team_key in award.team_list:
                teams_by_year[award.year].append((
                    team_key.get_async(),
                    award.event.get_async(),
                    award,
                    media_query.TeamTagMediasQuery(team_key.id(), MediaTag.CHAIRMANS_VIDEO).fetch_async(),
                    media_query.TeamTagMediasQuery(team_key.id(), MediaTag.CHAIRMANS_PRESENTATION).fetch_async(),
                    media_query.TeamTagMediasQuery(team_key.id(), MediaTag.CHAIRMANS_ESSAY).fetch_async(),
                ))

        teams_by_year = sorted(teams_by_year.items(), key=lambda (k, v): -k)
        for _, tea in teams_by_year:
            tea.sort(key=lambda x: x[1].get_result().start_date)

        self.template_values.update({
            'teams_by_year': teams_by_year,
        })

        return jinja2_engine.render('hof.html', self.template_values)
Пример #37
0
    def _render(self, year=None, explicit_year=False):
        events = event_query.EventListQuery(year).fetch()
        EventHelper.sort_events(events)

        week_events = EventHelper.groupByWeek(events)

        district_enums = set()
        for event in events:
            if event.event_district_enum is not None and event.event_district_enum != DistrictType.NO_DISTRICT:
                district_enums.add(event.event_district_enum)

        districts = []  # a tuple of (district abbrev, district name)
        for district_enum in district_enums:
            districts.append((DistrictType.type_abbrevs[district_enum],
                              DistrictType.type_names[district_enum]))
        districts = sorted(districts, key=lambda d: d[1])

        self.template_values.update({
            "events": events,
            "explicit_year": explicit_year,
            "selected_year": year,
            "valid_years": self.VALID_YEARS,
            "week_events": week_events,
            "districts": districts,
        })

        return jinja2_engine.render('event_list.html', self.template_values)
Пример #38
0
    def get(self, team_number):
        self._require_registration()

        team_key = 'frc{}'.format(team_number)
        team = Team.get_by_id(team_key)

        if not team:
            self.abort(404)

        user = self.user_bundle.account.key
        favorite = Favorite.query(Favorite.model_key == team_key,
                                  Favorite.model_type == ModelType.TEAM,
                                  ancestor=user).get()
        subscription = Subscription.query(
            Favorite.model_key == team_key,
            Favorite.model_type == ModelType.TEAM,
            ancestor=user).get()

        if not favorite and not subscription:  # New entry; default to being a favorite
            is_favorite = True
        else:
            is_favorite = favorite is not None

        enabled_notifications = [
            (en, NotificationType.render_names[en])
            for en in NotificationType.enabled_team_notifications
        ]

        self.template_values['team'] = team
        self.template_values['is_favorite'] = is_favorite
        self.template_values['subscription'] = subscription
        self.template_values['enabled_notifications'] = enabled_notifications

        self.response.out.write(
            jinja2_engine.render('mytba_team.html', self.template_values))
Пример #39
0
    def _render(self, event_key):
        event = Event.get_by_id(event_key)
        if not event:
            self.abort(404)
            return
        medias_future = media_query.EventTeamsPreferredMediasQuery(event_key).fetch_async()
        next_match = MatchHelper.upcomingMatches(event.matches, num=1)
        next_match = next_match[0] if next_match else None
        team_and_medias = []
        if next_match:
            # Organize medias by team
            teams = ndb.get_multi([ndb.Key(Team, team_key) for team_key in next_match.alliances['red']['teams'] + next_match.alliances['blue']['teams']])
            image_medias = MediaHelper.get_images([media for media in medias_future.get_result()])
            team_medias = defaultdict(list)
            for image_media in image_medias:
                for reference in image_media.references:
                    team_medias[reference].append(image_media)

            stations = ['Red 1', 'Red 2', 'Red 3', 'Blue 1', 'Blue 2', 'Blue 3']
            for i, team in enumerate(teams):
                team_and_medias.append((team, stations[i], team_medias.get(team.key, [])))

        self.template_values.update({
            'event': event,
            'next_match': next_match,
            'teams_and_media': team_and_medias,
        })
        return jinja2_engine.render('nextmatch.html', self.template_values)
Пример #40
0
    def render_team_history(cls, handler, team, is_canonical):
        award_futures = award_query.TeamAwardsQuery(team.key.id()).fetch_async()
        event_futures = event_query.TeamEventsQuery(team.key.id()).fetch_async()
        participation_future = team_query.TeamParticipationQuery(team.key.id()).fetch_async()
        social_media_future = media_query.TeamSocialMediaQuery(team.key.id()).fetch_async()

        awards_by_event = {}
        for award in award_futures.get_result():
            if award.event.id() not in awards_by_event:
                awards_by_event[award.event.id()] = [award]
            else:
                awards_by_event[award.event.id()].append(award)

        event_awards = []
        current_event = None
        matches_upcoming = None
        short_cache = False
        years = set()
        for event in event_futures.get_result():
            years.add(event.year)
            if event.now:
                current_event = event
                matches = match_query.TeamEventMatchesQuery(team.key.id(), event.key.id()).fetch()
                matches_upcoming = MatchHelper.upcomingMatches(matches)

            if event.within_a_day:
                short_cache = True

            if event.key_name in awards_by_event:
                sorted_awards = AwardHelper.organizeAwards(awards_by_event[event.key_name])
            else:
                sorted_awards = []
            event_awards.append((event, sorted_awards))
        event_awards = sorted(event_awards, key=lambda (e, _): e.start_date if e.start_date else datetime.datetime(e.year, 12, 31))

        last_competed = None
        participation_years = participation_future.get_result()
        if len(participation_years) > 0:
            last_competed = max(participation_years)
        current_year = datetime.date.today().year

        social_medias = sorted(social_media_future.get_result(), key=MediaHelper.social_media_sorter)

        handler.template_values.update({
            'is_canonical': is_canonical,
            'team': team,
            'event_awards': event_awards,
            'years': sorted(years),
            "social_medias": social_medias,
            'current_event': current_event,
            'matches_upcoming': matches_upcoming,
            'last_competed': last_competed,
            'current_year': current_year
        })

        if short_cache:
            handler._cache_expiration = handler.SHORT_CACHE_EXPIRATION

        return jinja2_engine.render('team_history.html', handler.template_values)
    def get(self):
        super(SuggestTeamMediaReviewController, self).get()
        suggestions = Suggestion.query().filter(
            Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
                Suggestion.target_model == "media").fetch(limit=50)

        # Quick and dirty way to group images together
        suggestions = sorted(
            suggestions,
            key=lambda x: 0
            if x.contents['media_type_enum'] in MediaType.image_types else 1)

        reference_keys = []
        existing_preferred_keys_futures = []
        for suggestion in suggestions:
            reference_key = suggestion.contents['reference_key']
            reference = Media.create_reference(
                suggestion.contents['reference_type'], reference_key)
            reference_keys.append(reference)

            if 'details_json' in suggestion.contents:
                suggestion.details = json.loads(
                    suggestion.contents['details_json'])
                if 'image_partial' in suggestion.details:
                    suggestion.details['thumbnail'] = suggestion.details[
                        'image_partial'].replace('_l', '_m')

            # Find existing preferred images
            existing_preferred_keys_futures.append(
                Media.query(
                    Media.media_type_enum.IN(MediaType.image_types),
                    Media.references == reference,
                    Media.preferred_references == reference,
                    Media.year == suggestion.contents['year'],
                ).fetch_async(keys_only=True))

        reference_futures = ndb.get_multi_async(reference_keys)
        existing_preferred_futures = map(
            lambda x: ndb.get_multi_async(x.get_result()),
            existing_preferred_keys_futures)

        references = map(lambda r: r.get_result(), reference_futures)
        existing_preferred = map(lambda l: map(lambda x: x.get_result(), l),
                                 existing_preferred_futures)

        suggestions_and_references_and_preferred = zip(suggestions, references,
                                                       existing_preferred)

        self.template_values.update({
            "suggestions_and_references_and_preferred":
            suggestions_and_references_and_preferred,
            "max_preferred":
            Media.MAX_PREFERRED,
        })

        self.response.out.write(
            jinja2_engine.render(
                'suggestions/suggest_team_media_review_list.html',
                self.template_values))
    def get(self):
        self._require_registration()

        current_events = filter(lambda e: e.now, EventHelper.getEventsWithinADay())
        popular_teams_events = TeamHelper.getPopularTeamsEvents(current_events)

        popular_team_keys = set()
        for team, _ in popular_teams_events:
            popular_team_keys.add(team.key.id())

        for event in current_events:
            event.prep_details()
            event.prep_matches()

        finished_matches = []
        current_matches = []
        upcoming_matches = []
        ranks = {}
        alliances = {}
        for event in current_events:
            if not event.details:
                continue
            finished_matches += MatchHelper.recentMatches(event.matches, num=1)
            for i, match in enumerate(MatchHelper.upcomingMatches(event.matches, num=3)):
                if not match.time:
                    continue

                if not event.details.predictions or match.key.id() not in event.details.predictions['match_predictions']['qual' if match.comp_level == 'qm' else 'playoff']:
                    match.prediction = defaultdict(lambda: defaultdict(float))
                    match.bluezone_score = 0
                else:
                    match.prediction = event.details.predictions['match_predictions']['qual' if match.comp_level == 'qm' else 'playoff'][match.key.id()]
                    match.bluezone_score = self.get_qual_bluezone_score(match.prediction) if match.comp_level == 'qm' else self.get_elim_bluezone_score(match.prediction)
                if i == 0:
                    current_matches.append(match)
                else:
                    upcoming_matches.append(match)
            if event.details.rankings2:
                for rank in event.details.rankings2:
                    ranks[rank['team_key']] = rank['rank']
            if event.alliance_selections:
                for i, alliance in enumerate(event.alliance_selections):
                    for pick in alliance['picks']:
                        alliances[pick] = i + 1

        finished_matches = sorted(finished_matches, key=lambda m: m.actual_time if m.actual_time else m.time)
        current_matches = sorted(current_matches, key=lambda m: m.predicted_time if m.predicted_time else m.time)
        upcoming_matches = sorted(upcoming_matches, key=lambda m: m.predicted_time if m.predicted_time else m.time)

        self.template_values.update({
            'finished_matches': finished_matches,
            'current_matches': current_matches,
            'upcoming_matches': upcoming_matches,
            'ranks': ranks,
            'alliances': alliances,
            'popular_team_keys': popular_team_keys,
        })

        self.response.out.write(jinja2_engine.render('match_suggestion.html', self.template_values))
 def _add_admin_bar(self, html):
     if self._is_admin:
         self.template_values["cache_key"] = self.cache_key
         self.template_values["user_bundle"] = self._user_bundle
         admin_bar = jinja2_engine.render('admin_bar.html', self.template_values)
         return html.replace('<!-- Admin Bar -->', admin_bar.encode('utf8'))
     else:
         return html
Пример #44
0
 def _render(self, *args, **kw):
     team_a = Team.get_by_id(self._team_key_a) if self._team_key_a else None
     team_b = Team.get_by_id(self._team_key_b) if self._team_key_b else None
     self.template_values.update({
         'team_a': team_a,
         'team_b': team_b,
     })
     return jinja2_engine.render('2champs.html', self.template_values)
Пример #45
0
    def get(self):
        self._require_login('/account/register')
        # Redirects to account overview page if already registered
        if self.user_bundle.account.registered:
            self.redirect('/account')
            return None

        self.response.out.write(jinja2_engine.render('account_register.html', self.template_values))
 def get(self):
     self._require_login()
     self.template_values.update({
         "status": self.request.get("status"),
         "auth_types": AuthType.type_names,
     })
     self.response.out.write(
         jinja2_engine.render('suggest_apiwrite.html', self.template_values))
Пример #47
0
 def _render(self, *args, **kw):
     team_a = Team.get_by_id(self._team_key_a) if self._team_key_a else None
     team_b = Team.get_by_id(self._team_key_b) if self._team_key_b else None
     self.template_values.update({
         'team_a': team_a,
         'team_b': team_b,
     })
     return jinja2_engine.render('2champs.html', self.template_values)
Пример #48
0
 def get(self):
     self._require_login()
     self.template_values.update({
         "status": self.request.get("status"),
         "auth_types": AuthType.type_names,
     })
     self.response.out.write(
         jinja2_engine.render('suggestions/suggest_apiwrite.html',
                              self.template_values))
Пример #49
0
 def _add_admin_bar(self, html):
     if self._is_admin:
         self.template_values["cache_key"] = self.cache_key
         self.template_values["user_bundle"] = self._user_bundle
         admin_bar = jinja2_engine.render('admin_bar.html',
                                          self.template_values)
         return html.replace('<!-- Admin Bar -->', admin_bar.encode('utf8'))
     else:
         return html
 def _render(self, *args, **kw):
     avatars_future = Media.query(
         Media.media_type_enum == MediaType.AVATAR).fetch_async()
     avatars = sorted(avatars_future.get_result(),
                      key=lambda a: int(a.references[0].id()[3:]))
     self.template_values.update({
         'avatars': avatars,
     })
     return jinja2_engine.render('avatars2018.html', self.template_values)
Пример #51
0
def render_static(page):
    memcache_key = "main_%s" % page
    html = memcache.get(memcache_key)

    if html is None:
        html = jinja2_engine.render('%s.html' % page, {})
        if tba_config.CONFIG["memcache"]:
            memcache.set(memcache_key, html, 86400)

    return html
    def get(self):
        self._require_login('/account/register')
        # Redirects to account overview page if already registered
        if self.user_bundle.account.registered:
            self.redirect('/account')
            return None

        self.response.out.write(
            jinja2_engine.render('account_register.html',
                                 self.template_values))
    def get(self):
        self._require_registration()

        current_events = filter(lambda e: e.now, EventHelper.getEventsWithinADay())

        self.template_values.update({
            'event_keys_json': json.dumps([e.key.id() for e in current_events]),
        })

        self.response.out.write(jinja2_engine.render('match_timeline.html', self.template_values))
    def _render(self):
        self.template_values.update({
            'valid_years': VALID_YEARS,
        })

        insights = ndb.get_multi([ndb.Key(Insight, Insight.renderKeyName(0, insight_name)) for insight_name in Insight.INSIGHT_NAMES.values()])
        for insight in insights:
            if insight:
                self.template_values[insight.name] = insight

        return jinja2_engine.render('insights.html', self.template_values)
Пример #55
0
 def _add_admin_bar(self, html):
     if self._is_admin and self.SHOULD_ADD_ADMIN_BAR:
         from template_engine import jinja2_engine
         self.template_values["cache_key"] = self.cache_key
         self.template_values["return_url"] = self.request.path
         self.template_values["flushed"] = self.request.get("flushed")
         self.template_values["user_bundle"] = self._user_bundle
         admin_bar = jinja2_engine.render('admin_bar.html', self.template_values)
         return html.replace('<!-- Admin Bar -->', admin_bar.encode('utf8'))
     else:
         return html
    def get(self):
        suggestions = (
            Suggestion.query()
            .filter(Suggestion.review_state == Suggestion.REVIEW_PENDING)
            .filter(Suggestion.target_model == "media")
            .fetch(limit=50)
        )

        # Quick and dirty way to group images together
        suggestions = sorted(
            suggestions, key=lambda x: 0 if x.contents["media_type_enum"] in MediaType.image_types else 1
        )

        reference_keys = []
        existing_preferred_keys_futures = []
        for suggestion in suggestions:
            reference_key = suggestion.contents["reference_key"]
            reference = Media.create_reference(suggestion.contents["reference_type"], reference_key)
            reference_keys.append(reference)

            if "details_json" in suggestion.contents:
                suggestion.details = json.loads(suggestion.contents["details_json"])
                if "image_partial" in suggestion.details:
                    suggestion.details["thumbnail"] = suggestion.details["image_partial"].replace("_l", "_m")

            # Find existing preferred images
            existing_preferred_keys_futures.append(
                Media.query(
                    Media.media_type_enum.IN(MediaType.image_types),
                    Media.references == reference,
                    Media.preferred_references == reference,
                    Media.year == suggestion.contents["year"],
                ).fetch_async(keys_only=True)
            )

        reference_futures = ndb.get_multi_async(reference_keys)
        existing_preferred_futures = map(lambda x: ndb.get_multi_async(x.get_result()), existing_preferred_keys_futures)

        references = map(lambda r: r.get_result(), reference_futures)
        existing_preferred = map(lambda l: map(lambda x: x.get_result(), l), existing_preferred_futures)

        suggestions_and_references_and_preferred = zip(suggestions, references, existing_preferred)

        self.template_values.update(
            {
                "suggestions_and_references_and_preferred": suggestions_and_references_and_preferred,
                "max_preferred": Media.MAX_PREFERRED,
            }
        )

        self.response.out.write(
            jinja2_engine.render("suggestions/suggest_team_media_review_list.html", self.template_values)
        )
    def get(self):
        suggestions = Suggestion.query().filter(
            Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
            Suggestion.target_model == "api_auth_access").fetch()
        suggestions = [self._ids_and_events(suggestion) for suggestion in suggestions]

        self.template_values.update({
            'success': self.request.get("success"),
            'suggestions': suggestions,
            'auth_names': AuthType.type_names,
        })
        self.response.out.write(
            jinja2_engine.render('suggest_apiwrite_review_list.html', self.template_values))
    def get(self):
        self._require_login()

        # Redirects if already registered
        redirect = self.request.get('redirect')
        if self.user_bundle.account.registered:
            if redirect:
                self.redirect(redirect, abort=True)
            else:
                self.redirect('/account', abort=True)

        self.template_values['redirect'] = redirect
        self.response.out.write(jinja2_engine.render('account_register.html', self.template_values))