def parse(self, response):
        """
        Parse team info from FMSAPI
        Returns a tuple of: list of models (Team, DistrictTeam, Robot),
        and a Boolean indicating if there are more pages to be fetched
        """

        # Get team json
        # don't need to null check, if error, HTTP code != 200, so we wont' get here
        current_page = response['pageCurrent']
        total_pages = response['pageTotal']
        teams = response['teams']
        ret_models = []

        for teamData in teams:
            # Fix issue where FIRST's API returns dummy website for all teams
            if teamData['website'] is not None and 'www.firstinspires.org' in teamData['website']:
                website = None
            else:
                website = WebsiteHelper.format_url(teamData.get('website', None))

            team = Team(
                id="frc{}".format(teamData['teamNumber']),
                team_number=teamData['teamNumber'],
                name=teamData['nameFull'],
                nickname=teamData['nameShort'],
                school_name=teamData.get('schoolName'),
                home_cmp=teamData.get('homeCMP').lower() if teamData.get('homeCMP') else None,
                city=teamData['city'],
                state_prov=teamData['stateProv'],
                country=teamData['country'],
                website=website,
                rookie_year=teamData['rookieYear']
            )

            districtTeam = None
            if teamData['districtCode']:
                districtAbbrev = DistrictType.abbrevs[teamData['districtCode'].lower()]
                districtTeam = DistrictTeam(
                    id=DistrictTeam.renderKeyName(self.year, districtAbbrev, team.key_name),
                    team=ndb.Key(Team, team.key_name),
                    year=self.year,
                    district=districtAbbrev,
                    district_key=ndb.Key(District, District.renderKeyName(self.year, teamData['districtCode'].lower())),
                )

            robot = None
            if teamData['robotName']:
                robot = Robot(
                    id=Robot.renderKeyName(team.key_name, self.year),
                    team=ndb.Key(Team, team.key_name),
                    year=self.year,
                    robot_name=teamData['robotName'].strip()
                )

            ret_models.append((team, districtTeam, robot))

        return (ret_models, (current_page < total_pages))
    def parse(self, response):
        """
        Parse team info from FMSAPI
        Returns a tuple of: list of models (Team, DistrictTeam, Robot),
        and a Boolean indicating if there are more pages to be fetched
        """

        # Get team json
        # don't need to null check, if error, HTTP code != 200, so we wont' get here
        current_page = response['pageCurrent']
        total_pages = response['pageTotal']
        teams = response['teams']
        ret_models = []

        for teamData in teams:
            # Fix issue where FIRST's API returns dummy website for all teams
            if teamData[
                    'website'] is not None and 'www.firstinspires.org' in teamData[
                        'website']:
                website = None
            else:
                raw_website = teamData.get('website', None)
                website = urlparse.urlparse(
                    raw_website, 'http').geturl() if raw_website else None

                # Fix oddity with urlparse having three slashes after the scheme (#1635)
                website = website.replace('///', '//') if website else None

            team = Team(id="frc{}".format(teamData['teamNumber']),
                        team_number=teamData['teamNumber'],
                        name=teamData['nameFull'],
                        nickname=teamData['nameShort'],
                        city=teamData['city'],
                        state_prov=teamData['stateProv'],
                        country=teamData['country'],
                        website=website,
                        rookie_year=teamData['rookieYear'])

            districtTeam = None
            if teamData['districtCode']:
                districtAbbrev = DistrictType.abbrevs[
                    teamData['districtCode'].lower()]
                districtTeam = DistrictTeam(id=DistrictTeam.renderKeyName(
                    self.year, districtAbbrev, team.key_name),
                                            team=ndb.Key(Team, team.key_name),
                                            year=self.year,
                                            district=districtAbbrev)

            robot = None
            if teamData['robotName']:
                robot = Robot(id=Robot.renderKeyName(team.key_name, self.year),
                              team=ndb.Key(Team, team.key_name),
                              year=self.year,
                              robot_name=teamData['robotName'].strip())

            ret_models.append((team, districtTeam, robot))

        return (ret_models, (current_page < total_pages))
Пример #3
0
    def parse(self, response):
        """
        Parse team info from FMSAPI
        Returns a tuple of: list of models (Team, DistrictTeam, Robot),
        and a Boolean indicating if there are more pages to be fetched
        """

        # Get team json
        # don't need to null check, if error, HTTP code != 200, so we wont' get here
        current_page = response['pageCurrent']
        total_pages = response['pageTotal']
        teams = response['teams']
        ret_models = []

        for teamData in teams:
            # Fix issue where FIRST's API returns dummy website for all teams
            if teamData[
                    'website'] is not None and 'www.firstinspires.org' in teamData[
                        'website']:
                website = None
            else:
                website = WebsiteHelper.format_url(
                    teamData.get('website', None))

            team = Team(id="frc{}".format(teamData['teamNumber']),
                        team_number=teamData['teamNumber'],
                        name=teamData['nameFull'],
                        nickname=teamData['nameShort'],
                        school_name=teamData.get('schoolName'),
                        home_cmp=teamData.get('homeCMP').lower()
                        if teamData.get('homeCMP') else None,
                        city=teamData['city'],
                        state_prov=teamData['stateProv'],
                        country=teamData['country'],
                        website=website,
                        rookie_year=teamData['rookieYear'])

            districtTeam = None
            if teamData['districtCode']:
                districtKey = District.renderKeyName(
                    self.year, teamData['districtCode'].lower())
                districtTeam = DistrictTeam(
                    id=DistrictTeam.renderKeyName(districtKey, team.key_name),
                    team=ndb.Key(Team, team.key_name),
                    year=self.year,
                    district_key=ndb.Key(District, districtKey),
                )

            robot = None
            if teamData['robotName']:
                robot = Robot(id=Robot.renderKeyName(team.key_name, self.year),
                              team=ndb.Key(Team, team.key_name),
                              year=self.year,
                              robot_name=teamData['robotName'].strip())

            ret_models.append((team, districtTeam, robot))

        return (ret_models, (current_page < total_pages))
Пример #4
0
    def test_delete_robot_name(self):
        self.loginUser()
        self.giveTeamAdminAccess()

        Robot(
            id=Robot.renderKeyName(self.team.key_name, self.now.year),
            team=self.team.key,
            year=self.now.year,
            robot_name='First Robot Name',
        ).put()

        form = self.getTeamInfoForm(1124)
        self.assertEqual(form['robot_name'].value, 'First Robot Name')
        form['robot_name'] = ''
        response = form.submit().follow()
        self.assertEqual(response.status_int, 301)

        robot = Robot.get_by_id(Robot.renderKeyName('frc1124', self.now.year))
        self.assertIsNone(robot)
Пример #5
0
    def test_set_robot_name(self):
        self.loginUser()
        self.giveTeamAdminAccess()

        # There is no Robot models that exists yet for this team
        form = self.getTeamInfoForm(1124)
        form['robot_name'] = 'Test Robot Name'
        response = form.submit().follow()
        self.assertEqual(response.status_int, 301)

        robot = Robot.get_by_id(Robot.renderKeyName('frc1124', self.now.year))
        self.assertIsNotNone(robot)
        self.assertEqual(robot.robot_name, 'Test Robot Name')
    def parse(self, response):
        """
        Parse team info from FMSAPI
        Returns a tuple of: list of models (Team, DistrictTeam, Robot),
        and a Boolean indicating if there are more pages to be fetched
        """

        # Get team json
        # don't need to null check, if error, HTTP code != 200, so we wont' get here
        current_page = response['pageCurrent']
        total_pages = response['pageTotal']
        teams = response['teams']
        ret_models = []

        for teamData in teams:
            # concat city/state/country to get address
            address = u"{}, {}, {}".format(teamData['city'], teamData['stateProv'], teamData['country'])

            team = Team(
                id="frc{}".format(teamData['teamNumber']),
                team_number=teamData['teamNumber'],
                name=teamData['nameFull'],
                nickname=teamData['nameShort'],
                address=address,
                website=teamData['website'],
                rookie_year=teamData['rookieYear']
            )

            districtTeam = None
            if teamData['districtCode']:
                districtAbbrev = DistrictType.abbrevs[teamData['districtCode'].lower()]
                districtTeam = DistrictTeam(
                    id=DistrictTeam.renderKeyName(self.year, districtAbbrev, team.key_name),
                    team=ndb.Key(Team, team.key_name),
                    year=self.year,
                    district=districtAbbrev
                )

            robot = None
            if teamData['robotName']:
                robot = Robot(
                    id=Robot.renderKeyName(team.key_name, self.year),
                    team=ndb.Key(Team, team.key_name),
                    year=self.year,
                    robot_name=teamData['robotName'].strip()
                )

            ret_models.append((team, districtTeam, robot))

        return (ret_models, (current_page < total_pages))
Пример #7
0
    def parse(self, response):
        """
        Parse team info from FMSAPI
        Returns a tuple of: list of models (Team, DistrictTeam, Robot),
        and a Boolean indicating if there are more pages to be fetched
        """

        # Get team json
        # don't need to null check, if error, HTTP code != 200, so we wont' get here
        current_page = response['pageCurrent']
        total_pages = response['pageTotal']
        teams = response['teams']
        ret_models = []

        for teamData in teams:
            # concat city/state/country to get address
            address = u"{}, {}, {}".format(teamData['city'],
                                           teamData['stateProv'],
                                           teamData['country'])

            team = Team(id="frc{}".format(teamData['teamNumber']),
                        team_number=teamData['teamNumber'],
                        name=teamData['nameFull'],
                        nickname=teamData['nameShort'],
                        address=address,
                        website=teamData['website'],
                        rookie_year=teamData['rookieYear'])

            districtTeam = None
            if teamData['districtCode']:
                districtAbbrev = DistrictType.abbrevs[
                    teamData['districtCode'].lower()]
                districtTeam = DistrictTeam(id=DistrictTeam.renderKeyName(
                    self.year, districtAbbrev, team.key_name),
                                            team=ndb.Key(Team, team.key_name),
                                            year=self.year,
                                            district=districtAbbrev)

            robot = None
            if teamData['robotName']:
                robot = Robot(id=Robot.renderKeyName(team.key_name, self.year),
                              team=ndb.Key(Team, team.key_name),
                              year=self.year,
                              robot_name=teamData['robotName'].strip())

            ret_models.append((team, districtTeam, robot))

        return (ret_models, (current_page < total_pages))
Пример #8
0
    def post(self):
        team_number = self.request.get("team_number")
        if not team_number:
            self.abort(400)
        team_number = int(team_number)
        team = Team.get_by_id("frc{}".format(team_number))
        if not team:
            self.abort(400)
        self._require_team_admin_access(team_number)

        action = self.request.get('action')
        if action == "remove_media_reference":
            media, team_ref = self.get_media_and_team_ref(team_number)
            if team_ref in media.references:
                media.references.remove(team_ref)
            if team_ref in media.preferred_references:
                media.preferred_references.remove(team_ref)
            MediaManipulator.createOrUpdate(media, auto_union=False)
        elif action == "remove_media_preferred":
            media, team_ref = self.get_media_and_team_ref(team_number)
            if team_ref in media.preferred_references:
                media.preferred_references.remove(team_ref)
            MediaManipulator.createOrUpdate(media, auto_union=False)
        elif action == "add_media_preferred":
            media, team_ref = self.get_media_and_team_ref(team_number)
            if team_ref not in media.preferred_references:
                media.preferred_references.append(team_ref)
            MediaManipulator.createOrUpdate(media, auto_union=False)
        elif action == "set_team_info":
            robot_name = self.request.get("robot_name").strip()
            current_year = datetime.datetime.now().year
            robot_key = Robot.renderKeyName(team.key_name, current_year)
            if robot_name:
                robot = Robot(
                    id=robot_key,
                    team=team.key,
                    year=current_year,
                    robot_name=robot_name,
                )
                RobotManipulator.createOrUpdate(robot)
            else:
                RobotManipulator.delete_keys([ndb.Key(Robot, robot_key)])
        else:
            self.abort(400)

        self.redirect('/mod/')
    def post(self):
        team_number = self.request.get("team_number")
        if not team_number:
            self.abort(400)
        team_number = int(team_number)
        team = Team.get_by_id("frc{}".format(team_number))
        if not team:
            self.abort(400)
        self._require_team_admin_access(team_number)

        action = self.request.get('action')
        if action == "remove_media_reference":
            media, team_ref = self.get_media_and_team_ref(team_number)
            if team_ref in media.references:
                media.references.remove(team_ref)
            if team_ref in media.preferred_references:
                media.preferred_references.remove(team_ref)
            MediaManipulator.createOrUpdate(media, auto_union=False)
        elif action == "remove_media_preferred":
            media, team_ref = self.get_media_and_team_ref(team_number)
            if team_ref in media.preferred_references:
                media.preferred_references.remove(team_ref)
            MediaManipulator.createOrUpdate(media, auto_union=False)
        elif action == "add_media_preferred":
            media, team_ref = self.get_media_and_team_ref(team_number)
            if team_ref not in media.preferred_references:
                media.preferred_references.append(team_ref)
            MediaManipulator.createOrUpdate(media, auto_union=False)
        elif action == "set_team_info":
            robot_name = self.request.get("robot_name").strip()
            current_year = datetime.datetime.now().year
            robot_key = Robot.renderKeyName(team.key_name, current_year)
            if robot_name:
                robot = Robot(
                    id=robot_key,
                    team=team.key,
                    year=current_year,
                    robot_name=robot_name,
                )
                RobotManipulator.createOrUpdate(robot)
            else:
                RobotManipulator.delete_keys([ndb.Key(Robot, robot_key)])
        else:
            self.abort(400)

        self.redirect('/mod/')
    def parse(self, response):
        """
        Parse team info from FMSAPI
        Returns a tuple of models (Team, DistrictTeam, Robot)
        """

        # Get team json
        # don't need to null check, if error, HTTP code != 200, so we wont' get here
        teams = response["teams"]
        teamData = teams[0]

        # concat city/state/country to get address
        address = u"{}, {}, {}".format(teamData["city"], teamData["stateProv"], teamData["country"])

        team = Team(
            team_number=teamData["teamNumber"],
            name=teamData["nameFull"],
            nickname=teamData["nameShort"],
            address=address,
            rookie_year=teamData["rookieYear"],
        )

        districtTeam = None
        if teamData["districtCode"]:
            districtAbbrev = DistrictType.abbrevs[teamData["districtCode"].lower()]
            districtTeam = DistrictTeam(
                id=DistrictTeam.renderKeyName(self.year, districtAbbrev, team.key_name),
                team=ndb.Key(Team, team.key_name),
                year=self.year,
                district=districtAbbrev,
            )

        robot = None
        if teamData["robotName"]:
            robot = Robot(
                id=Robot.renderKeyName(team.key_name, self.year),
                team=ndb.Key(Team, team.key_name),
                year=self.year,
                robot_name=teamData["robotName"].strip(),
            )

        return (team, districtTeam, robot)
    def post(self):
        self._require_admin()

        team_key = self.request.get('team_key')
        year = int(self.request.get('robot_year'))
        name = self.request.get('robot_name')

        team = Team.get_by_id(team_key)
        if not team:
            self.abort(404)

        if not year or not name:
            self.abort(400)

        robot = Robot(id=Robot.renderKeyName(team_key, year),
                      team=team.key,
                      year=year,
                      robot_name=name.strip())
        RobotManipulator.createOrUpdate(robot)
        self.redirect('/admin/team/{}'.format(team.team_number))
    def post(self):
        self._require_admin()

        team_key = self.request.get('team_key')
        year = int(self.request.get('robot_year'))
        name = self.request.get('robot_name')

        team = Team.get_by_id(team_key)
        if not team:
            self.abort(404)

        if not year or not name:
            self.abort(400)

        robot = Robot(
            id=Robot.renderKeyName(team_key, year),
            team=team.key,
            year=year,
            robot_name=name.strip()
        )
        RobotManipulator.createOrUpdate(robot)
        self.redirect('/admin/team/{}'.format(team.team_number))
Пример #13
0
    def get(self):
        self._require_registration()
        user = self.user_bundle.account.key

        now = datetime.datetime.now()
        existing_access = TeamAdminAccess.query(
            TeamAdminAccess.account == user,
            TeamAdminAccess.expiration > now).fetch()

        # If the current user is an admin, allow them to view this page for any
        # team/year combination
        forced_team = self.request.get("team")
        forced_year = self.request.get("year")
        if self.user_bundle.is_current_user_admin and forced_team and forced_year:
            existing_access.append(
                TeamAdminAccess(
                    team_number=int(forced_team),
                    year=int(forced_year),
                ))

        team_keys = [
            ndb.Key(Team, "frc{}".format(access.team_number))
            for access in existing_access
        ]
        if not team_keys:
            self.redirect('/mod/redeem')
            return
        years = set([access.year for access in existing_access])
        teams_future = ndb.get_multi_async(team_keys)
        robot_keys = [
            ndb.Key(Robot, Robot.renderKeyName(team.id(), now.year))
            for team in team_keys
        ]
        robots_future = ndb.get_multi_async(robot_keys)
        social_media_futures = [
            media_query.TeamSocialMediaQuery(team_key.id()).fetch_async()
            for team_key in team_keys
        ]
        team_medias_future = Media.query(Media.references.IN(team_keys),
                                         Media.year.IN(years)).fetch_async(50)
        suggestions_future = Suggestion.query(
            Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
                Suggestion.target_model.IN(
                    self.ALLOWED_SUGGESTION_TYPES)).filter(
                        Suggestion.target_key.IN([k.id() for k in team_keys
                                                  ])).fetch_async(limit=50)

        team_num_to_team = {
            team.get_result().team_number: team.get_result()
            for team in teams_future
        }
        team_num_to_robot_name = {
            int(robot.get_result().team.id()[3:]):
            robot.get_result().robot_name
            for robot in robots_future if robot.get_result() is not None
        }
        team_medias = defaultdict(lambda: defaultdict(list))
        for media in team_medias_future.get_result():
            for reference in media.references:
                if reference in team_keys:
                    team_num = reference.id()[3:]
                    team_medias[int(team_num)][media.year].append(media)

        team_social_medias = defaultdict(list)
        for team_social_media_future in social_media_futures:
            social_medias = team_social_media_future.get_result()
            for media in social_medias:
                for reference in media.references:
                    if reference in team_keys:
                        team_num = reference.id()[3:]
                        team_social_medias[int(team_num)].append(media)

        suggestions_by_team = defaultdict(lambda: defaultdict(list))
        for suggestion in suggestions_future.get_result():
            if not suggestion.target_key:
                continue
            # Assume all the keys are team keys
            team_num = suggestion.target_key[3:]
            suggestions_by_team[int(team_num)][suggestion.target_model].append(
                suggestion)

        self.template_values.update({
            "existing_access":
            existing_access,
            "teams":
            team_num_to_team,
            "robot_names_by_team":
            team_num_to_robot_name,
            "team_medias":
            team_medias,
            "team_social_medias":
            team_social_medias,
            "suggestions_by_team":
            suggestions_by_team,
            "suggestion_names":
            self.SUGGESTION_NAMES,
            "suggestion_review_urls":
            self.SUGGESTION_REVIEW_URL,
        })

        self.response.out.write(
            jinja2_engine.render('team_admin_dashboard.html',
                                 self.template_values))
    def get(self):
        self._require_registration()
        user = self.user_bundle.account.key

        now = datetime.datetime.now()
        existing_access = TeamAdminAccess.query(
            TeamAdminAccess.account == user,
            TeamAdminAccess.expiration > now).fetch()

        # If the current user is an admin, allow them to view this page for any
        # team/year combination
        forced_team = self.request.get("team")
        forced_year = self.request.get("year")
        if self.user_bundle.is_current_user_admin and forced_team and forced_year:
            existing_access.append(
                TeamAdminAccess(
                    team_number=int(forced_team),
                    year=int(forced_year),
                )
            )

        team_keys = [
            ndb.Key(Team, "frc{}".format(access.team_number))
            for access in existing_access
        ]
        if not team_keys:
            self.redirect('/mod/redeem')
            return
        years = set([access.year for access in existing_access])
        teams_future = ndb.get_multi_async(team_keys)
        robot_keys = [
            ndb.Key(Robot, Robot.renderKeyName(team.id(), now.year)) for team in team_keys
        ]
        robots_future = ndb.get_multi_async(robot_keys)
        social_media_futures = [
            media_query.TeamSocialMediaQuery(team_key.id()).fetch_async()
            for team_key in team_keys
        ]
        team_medias_future = Media.query(
            Media.references.IN(team_keys),
            Media.year.IN(years)).fetch_async(50)
        suggestions_future = Suggestion.query(
            Suggestion.review_state == Suggestion.REVIEW_PENDING).filter(
                Suggestion.target_model.IN(
                    self.ALLOWED_SUGGESTION_TYPES)).filter(
                        Suggestion.target_key.IN([k.id() for k in team_keys
                                                  ])).fetch_async(limit=50)

        team_num_to_team = {
            team.get_result().team_number: team.get_result()
            for team in teams_future
        }
        team_num_to_robot_name = {
            int(robot.get_result().team.id()[3:]): robot.get_result().robot_name
            for robot in robots_future if robot.get_result() is not None
        }
        team_medias = defaultdict(lambda: defaultdict(list))
        for media in team_medias_future.get_result():
            for reference in media.references:
                if reference in team_keys:
                    team_num = reference.id()[3:]
                    team_medias[int(team_num)][media.year].append(media)

        team_social_medias = defaultdict(list)
        for team_social_media_future in social_media_futures:
            social_medias = team_social_media_future.get_result()
            for media in social_medias:
                for reference in media.references:
                    if reference in team_keys:
                        team_num = reference.id()[3:]
                        team_social_medias[int(team_num)].append(media)

        suggestions_by_team = defaultdict(lambda: defaultdict(list))
        for suggestion in suggestions_future.get_result():
            if not suggestion.target_key:
                continue
            # Assume all the keys are team keys
            team_num = suggestion.target_key[3:]
            suggestions_by_team[int(team_num)][suggestion.target_model].append(
                suggestion)

        self.template_values.update({
            "existing_access": existing_access,
            "teams": team_num_to_team,
            "robot_names_by_team": team_num_to_robot_name,
            "team_medias": team_medias,
            "team_social_medias": team_social_medias,
            "suggestions_by_team": suggestions_by_team,
            "suggestion_names": self.SUGGESTION_NAMES,
            "suggestion_review_urls": self.SUGGESTION_REVIEW_URL,
        })

        self.response.out.write(
            jinja2_engine.render('team_admin_dashboard.html',
                                 self.template_values))