def get(self, competition_id):
    if not self.user:
      template = JINJA_ENVIRONMENT.get_template('error.html')
      self.response.write(template.render({
          'c': common.Common(self),
          'error_message': 'Please log in.',
      }))
      return

    if not self.request.get('code'):
      self.redirect('/authenticate?' + urllib.urlencode({
          'callback': self.request.url,
      }))
      return

    OAuthBaseHandler.GetTokenFromCode(self)
    if not self.auth_token:
      return

    response = self.GetWcaApi('/api/v0/competitions/%s/wcif' % competition_id)
    response_json = json.loads(response)

    template = JINJA_ENVIRONMENT.get_template('edit_competition_data.html')
    self.response.write(template.render({
        'c': common.Common(self),
        'competition_id': competition_id,
        'schedule_data': json.dumps(response_json['schedule'], indent=2, sort_keys=True),
        'persons_data': json.dumps(response_json['persons'], indent=2, sort_keys=True),
        'events_data': json.dumps(response_json['events'], indent=2, sort_keys=True),
    }))
示例#2
0
  def get(self, region_or_state, year):
    # We should call RegionalsId or StateChampionshipId here, but we don't know
    # yet what kind of championship this is.
    championship_id = '%s_%s' % (region_or_state, year)

    championship = Championship.get_by_id(championship_id)
    if not championship:
      template = JINJA_ENVIRONMENT.get_template('error.html')
      self.response.write(template.render({
          'c': common.Common(self),
          'error': 'Sorry!  We don\'t know about that championship yet.',
      }))
      return
    competition = championship.competition.get()

    event_keys = set()
    # This query is ugly because we have two separate representations of
    # competitions in the datastore: ScheduleCompetition (competitions using the
    # scheduling system) and Competition (competitions from the WCA DB export).
    for competitor in SchedulePerson.query(
                          SchedulePerson.competition ==
                          ndb.Key(ScheduleCompetition, championship.competition.id())).iter():
      for event in competitor.registered_events:
        event_keys.add(event)
    events = sorted(ndb.get_multi(event_keys), key=lambda e: e.rank)
    deadline_without_timezone = (championship.residency_deadline or
                                 datetime.datetime.combine(competition.start_date,
                                                           datetime.time(0, 0, 0)))
    deadline = timezones.ToLocalizedTime(deadline_without_timezone,
                                         championship.residency_timezone or 'America/Los_Angeles')

    states = ndb.get_multi(championship.GetEligibleStateKeys())
    if championship.region:
      championship_title = championship.region.get().championship_name
      state_names = [state.name for state in State.query(State.region == championship.region).iter()]
      state_list = ' and '.join([', '.join(state_names[:-1]), state_names[-1]])
    elif championship.state:
      championship_title = championship.state.get().name + ' State'
      state_list = championship.state.get().name

    template = JINJA_ENVIRONMENT.get_template('championship_psych.html')
    self.response.write(template.render({
        'c': common.Common(self),
        'championship': championship,
        'competition': competition,
        'championship_title': championship_title,
        'championship_id': championship_id,
        'state_list': state_list,
        'events': events,
        'deadline': deadline,
        'deadline_passed': deadline_without_timezone < datetime.datetime.now(),
    }))
示例#3
0
    def ImportWcif(self, wcif_data, data_to_import, deletion_confirmed=False):
        out = ImportOutput()
        if 'events' in data_to_import:
            ImportEvents(wcif_data, self.schedule.key, out)
        if 'schedule' in data_to_import:
            ImportSchedule(wcif_data, self.schedule, out)

        if out.errors:
            template = JINJA_ENVIRONMENT.get_template(
                'scheduling/import_error.html')
            self.response.write(
                template.render({
                    'c': common.Common(self),
                    'errors': out.errors
                }))
        elif out.entities_to_delete and not deletion_confirmed:
            template = JINJA_ENVIRONMENT.get_template(
                'scheduling/confirm_deletion.html')
            self.response.write(
                template.render({
                    'c':
                    common.Common(self),
                    'entities_to_delete':
                    out.entities_to_delete,
                    'entity_to_string':
                    EntityToString,
                    'wcif_data':
                    json.dumps(wcif_data),
                    'target_uri':
                    webapp2.uri_for('confirm_deletion',
                                    schedule_version=self.schedule.key.id()),
                    'data_to_import':
                    data_to_import,
                }))
        else:
            self.schedule.last_update_time = datetime.datetime.now()
            out.entities_to_put.append(self.schedule)
            ndb.put_multi(out.entities_to_put)
            ndb.delete_multi([e.key for e in out.entities_to_delete])
            template = JINJA_ENVIRONMENT.get_template('success.html')
            self.response.write(
                template.render({
                    'c':
                    common.Common(self),
                    'target_uri':
                    webapp2.uri_for('edit_schedule',
                                    competition_id=self.competition.key.id(),
                                    schedule_version=self.schedule.key.id())
                }))
 def get(self, event_id, championship_type, championship_region):
     template = JINJA_ENVIRONMENT.get_template('champions_by_year.html')
     all_champions = []
     if championship_type == 'national':
         all_champions = [
             c for c in Champion.query(
                 Champion.national_champion == True).iter()
         ]
     elif championship_type == 'regional':
         all_champions = [
             c for c in Champion.query(Champion.region == ndb.Key(
                 Region, championship_region)).iter()
         ]
     elif championship_type == 'state':
         all_champions = [
             c for c in Champion.query(Champion.state == ndb.Key(
                 State, championship_region)).iter()
         ]
     all_champions = sorted([
         c
         for c in all_champions if c.event == ndb.Key(Event, str(event_id))
     ],
                            key=lambda c: c.championship.id(),
                            reverse=True)
     self.response.write(
         template.render({
             'c': common.Common(self),
             'champions': all_champions,
         }))
示例#5
0
    def get(self):
        # The year we want to display championships for.  We should update this
        # once we're ready to start announcing the next year's championships.
        year = 2019

        championships = Championship.query(
            ndb.AND(Championship.year == year,
                    Championship.region != None)).fetch()
        competitions = ndb.get_multi([c.competition for c in championships])

        states = State.query().fetch()
        regions = Region.query().order(Region.name).fetch()

        championships.sort(
            key=lambda championship: championship.competition.get().start_date)
        championship_regions = [
            championship.region for championship in championships
        ]
        regions_missing_championships = [
            region for region in regions
            if region.key not in championship_regions
        ]

        template = JINJA_ENVIRONMENT.get_template('regional.html')
        self.response.write(
            template.render({
                'c':
                common.Common(self),
                'year':
                year,
                'championships':
                championships,
                'regions_missing_championships':
                regions_missing_championships,
            }))
示例#6
0
    def get(self):
        OAuthBaseHandler.GetTokenFromCode(self)
        if not self.auth_token:
            return

        competition_id_to_name = {}
        # List upcoming competitions that this person can manage.
        response = self.GetWcaApi(
            '/api/v0/competitions?managed_by_me=true&start=%s' %
            (datetime.datetime.now() -
             datetime.timedelta(days=30)).isoformat())

        if response.status != 200:
            self.redirect(webapp2.uri_for('index', unknown=1))
            return
        response_json = json.loads(response.read())
        for competition in response_json:
            competition_id_to_name[competition['id']] = competition['name']

        # TODO: Also list all competitions that this person has edit access to,
        # including all competitions for webmasters.

        template = JINJA_ENVIRONMENT.get_template('scheduling/index.html')
        self.response.write(
            template.render({
                'c': common.Common(self),
                'competition_id_to_name': competition_id_to_name,
            }))
示例#7
0
 def post(self, schedule_version):
     if not self.SetSchedule(int(schedule_version)):
         return
     if self.request.get('source') == 'wca':
         # WCA import, pre-redirect
         if not self.GetToken(handler_data={
                 'data_to_import':
                 self.request.POST.getall('data_to_import'),
         }):
             return
         self.ImportWcifFromWca(self.request.POST.getall('data_to_import'))
     elif 'sched_' in self.request.get('source'):
         schedule_to_import = int(
             self.request.get('source')[len('sched_'):])
         wcif_to_import = CompetitionToWcif(
             self.competition, Schedule.get_by_id(schedule_to_import))
         self.ImportWcif(
             wcif_to_import,
             data_to_import=self.request.POST.getall('data_to_import'))
     elif self.request.get('source') == 'custom':
         result = urlfetch.fetch(self.request.get('custom_uri'))
         if result.status_code != 200:
             template = JINJA_ENVIRONMENT.get_template('error.html')
             self.response.write(
                 template.render({
                     'c':
                     common.Common(self),
                     'error':
                     'Error fetching %s' % self.request.get('custom_uri')
                 }))
             return
         self.ImportWcif(
             json.loads(result.content),
             data_to_import=self.request.POST.getall('data_to_import'))
示例#8
0
    def get(self):
        is_admin = auth.CanUploadDocuments(self.user)

        template = JINJA_ENVIRONMENT.get_template('documents.html')
        documents_by_section = collections.defaultdict(list)

        for document in Document.query().iter():
            if not document.deletion_time or is_admin:
                documents_by_section[document.section].append(document)
        for documents in documents_by_section.values():
            documents.sort(key=lambda x: x.upload_time, reverse=True)

        template_dict = {
            'c':
            common.Common(self),
            'documents_by_section':
            sorted(documents_by_section.items(), key=lambda x: x[0]),
            'admin_page':
            is_admin,
            'just_uploaded':
            self.request.get('success') == '1',
        }

        if is_admin:
            template_dict['upload_url'] = blobstore.create_upload_url(
                webapp2.uri_for('upload_document'))

        self.response.write(template.render(template_dict))
示例#9
0
 def get(self):
     template = JINJA_ENVIRONMENT.get_template('admin/app_settings.html')
     self.response.write(
         template.render({
             'c': common.Common(self),
             'settings': AppSettings.Get(),
         }))
示例#10
0
 def post(self):
     template = JINJA_ENVIRONMENT.get_template(template_path)
     app_settings = AppSettings.Get()
     if app_settings.recaptcha_secret_key:
         payload = {
             'secret': app_settings.recaptcha_secret_key,
             'response': self.request.get('g-recaptcha-response'),
             'remoteip': self.request.remote_addr,
         }
         fetch = urlfetch.fetch(
             url='https://www.google.com/recaptcha/api/siteverify',
             payload=urllib.urlencode(payload),
             method=urlfetch.POST)
         result = json.loads(fetch.content)
         if not result['success']:
             self.response.write(
                 template.render({
                     'c': common.Common(self),
                     'result': 'failure',
                 }))
             return
     subject = '[%s] Contact form -- %s' % (subject_prefix,
                                            self.request.get('name'))
     if self.request.get('wcaid'):
         body = 'WCA ID: %s\n%s' % (self.request.get('wcaid'),
                                    self.request.get('contact-message'))
     else:
         body = self.request.get('contact-message')
     mail.send_mail(sender=contact_email,
                    to=contact_email,
                    cc=self.request.get('from-address'),
                    subject=subject,
                    body=body)
     self.redirect(self.request.url + '?success=1')
示例#11
0
    def GetImpl(handler, schedule, event):
        rounds = ScheduleRound.query(
            ndb.AND(ScheduleRound.schedule == schedule.key,
                    ScheduleRound.event == event.key)).order(
                        ScheduleRound.number).fetch()
        time_blocks_by_round = collections.defaultdict(list)
        for time_block in (ScheduleTimeBlock.query(
                ScheduleTimeBlock.schedule == schedule.key).order(
                    ScheduleTimeBlock.start_time).iter()):
            time_blocks_by_round[time_block.round].append(time_block)

        stages = (ScheduleStage.query(
            ScheduleStage.schedule == schedule.key).order(
                ScheduleStage.number).fetch())
        competition_days = []
        current_date = schedule.start_date
        while current_date <= schedule.end_date:
            competition_days.append(current_date)
            current_date += datetime.timedelta(days=1)

        template = JINJA_ENVIRONMENT.get_template(
            'scheduling/event_details.html')
        return template.render({
            'c': common.Common(handler),
            'rounds': rounds,
            'event': event,
            'time_blocks': time_blocks_by_round,
            'new_ids': {
                r.key: '%s_%d' % (r.key.id(), random.randint(2**4, 2**32))
                for r in rounds
            },
            'stages': stages,
            'competition_days': competition_days,
        })
示例#12
0
    def get(self):
        all_us_competitions = (Competition.query(
            Competition.country == ndb.Key(Country, 'USA')).order(
                Competition.name).fetch())

        national_championships = (Championship.query(
            Championship.national_championship == True).order(
                -Championship.year).fetch())
        regional_championships = (Championship.query(
            Championship.region != None).order(
                Championship.region).order(-Championship.year).fetch())
        state_championships = (Championship.query(
            Championship.state != None).order(
                Championship.state).order(-Championship.year).fetch())
        print len(national_championships), len(regional_championships), len(
            state_championships)

        states = State.query().fetch()
        regions = Region.query().fetch()

        template = JINJA_ENVIRONMENT.get_template(
            'admin/edit_championships.html')
        self.response.write(
            template.render({
                'c': common.Common(self),
                'all_us_competitions': all_us_competitions,
                'national_championships': national_championships,
                'regional_championships': regional_championships,
                'state_championships': state_championships,
                'states': states,
                'regions': regions,
            }))
示例#13
0
 def get(self, competition_id, schedule_version=-1):
     if not self.SetSchedule(int(schedule_version)):
         return
     template = JINJA_ENVIRONMENT.get_template(
         'scheduling/groups_display.html')
     groups_by_day_and_stage = collections.defaultdict(
         lambda: collections.defaultdict(list))
     all_days = set()
     for group in ScheduleGroup.query(
             ScheduleGroup.schedule == self.schedule.key).iter():
         groups_by_day_and_stage[group.start_time.date()][
             group.stage].append(group)
         all_days.add(group.start_time.date())
     for groups_set in groups_by_day_and_stage.itervalues():
         for groups in groups_set.itervalues():
             groups.sort(key=lambda g: g.start_time)
     all_days = sorted(all_days)
     all_stages = (ScheduleStage.query(
         ScheduleStage.schedule == self.schedule.key).order(
             ScheduleStage.number).fetch())
     self.response.write(
         template.render({
             'c': common.Common(self),
             'timezones': timezones,
             'competition': self.competition,
             'groups_by_day_and_stage': groups_by_day_and_stage,
             'all_stages': all_stages,
             'all_days': all_days,
         }))
示例#14
0
 def return_error(self, error):
     template = JINJA_ENVIRONMENT.get_template('error.html')
     self.response.write(
         template.render({
             'c': common.Common(self),
             'error': error,
         }))
示例#15
0
 def get(self, schedule_version):
     if not self.SetSchedule(int(schedule_version)):
         return
     template = JINJA_ENVIRONMENT.get_template(
         'scheduling/edit_schedule.html')
     event_keys = set([
         r.event for r in ScheduleRound.query(
             ScheduleRound.schedule == self.schedule.key).iter()
     ])
     events = [
         e.get() for e in sorted(event_keys, key=lambda e: e.get().rank)
     ]
     stages = (ScheduleStage.query(
         ScheduleRound.schedule == self.schedule.key).order(
             ScheduleRound.number).fetch())
     self.response.write(
         template.render({
             'c': common.Common(self),
             'competition': self.competition,
             'schedule': self.schedule,
             'events': events,
             'stages': stages,
             'new_stage_id': random.randint(2**4, 2**10),
             'colors': sorted(Colors.keys()),
         }))
示例#16
0
  def get(self):
    if not self.SetCompetition('CubingUSANationals2019',
                               login_required=False, edit_access_needed=False):
      return

    template = JINJA_ENVIRONMENT.get_template('nationals/2019/events.html')
    competition_details = CompetitionDetails(self.user, self.competition)

    competition_details.SetQualifyingTime('333', 4000, is_average=True)
    competition_details.SetQualifyingTime('222', 1100, is_average=True)
    competition_details.SetQualifyingTime('444', 6000, is_average=True)
    competition_details.SetQualifyingTime('555', 10000, is_average=True)
    competition_details.SetQualifyingTime('666', 18500, is_average=True)
    competition_details.SetQualifyingTime('777', 25500, is_average=True)
    competition_details.SetQualifyingTime('333oh', 3000, is_average=True)
    competition_details.SetQualifyingTime('333fm', 3800, is_average=True)
    competition_details.SetQualifyingTime('minx', 9000, is_average=True)
    competition_details.SetQualifyingTime('pyram', 1100, is_average=True)
    competition_details.SetQualifyingTime('skewb', 1100, is_average=True)
    competition_details.SetQualifyingTime('clock', 1300, is_average=True)
    competition_details.SetQualifyingTime('sq1', 3000, is_average=True)
    competition_details.SetQualifyingNumber('333ft', 50)
    competition_details.SetQualifyingTime('333bf', 18000, is_average=False)
    competition_details.SetQualifyingTime('444bf', 60000, is_average=False)
    competition_details.SetQualifyingTime('555bf', 120000, is_average=False)
    # Multi blind qualifying standard is 7 points.  Format is documented here:
    # https://www.worldcubeassociation.org/results/misc/export.html
    competition_details.SetQualifyingTime('333mbf', 929999999, is_average=False)
    
    self.response.write(template.render({
        'c': common.Common(self),
        'competition': self.competition,
        'competition_details': competition_details,
    }))
示例#17
0
    def get(self, event_id, state_id, use_average):
        template = JINJA_ENVIRONMENT.get_template('state_rankings_table.html')
        ranking_class = RankAverage if use_average == '1' else RankSingle
        state = State.get_by_id(state_id)
        if not state:
            self.response.write('Unrecognized state %s' % state_id)
            return
        event = Event.get_by_id(event_id)
        if not event:
            self.response.write('Unrecognized event %s' % event_id)
            return
        rankings = (ranking_class.query(
            ndb.AND(ranking_class.event == event.key,
                    ranking_class.state == state.key)).order(
                        ranking_class.best).fetch(100))

        people = ndb.get_multi([ranking.person for ranking in rankings])
        people_by_id = {person.key.id(): person for person in people}

        self.response.write(
            template.render({
                'c': common.Common(self),
                'is_average': use_average == '1',
                'rankings': rankings,
                'people_by_id': people_by_id,
            }))
示例#18
0
  def get(self):
    if not self.SetCompetition('CubingUSANationals2018', edit_access_needed=True):
      return

    template = JINJA_ENVIRONMENT.get_template('nationals/2018/events.html')
    competition_details = CompetitionDetails(self.user, self.competition)

    competition_details.SetQualifyingTime('333', 3000, is_average=True)
    competition_details.SetQualifyingTime('222', 1200, is_average=True)
    competition_details.SetQualifyingTime('444', 7000, is_average=True)
    competition_details.SetQualifyingTime('555', 11000, is_average=True)
    competition_details.SetQualifyingTime('666', 21000, is_average=True)
    competition_details.SetQualifyingTime('777', 28500, is_average=True)
    competition_details.SetQualifyingTime('333oh', 3500, is_average=True)
    competition_details.SetQualifyingTime('333fm', 4500, is_average=True)
    competition_details.SetQualifyingTime('minx', 10500, is_average=True)
    competition_details.SetQualifyingTime('pyram', 1200, is_average=True)
    competition_details.SetQualifyingTime('skewb', 1200, is_average=True)
    competition_details.SetQualifyingTime('clock', 1500, is_average=True)
    competition_details.SetQualifyingTime('sq1', 3500, is_average=True)
    competition_details.SetQualifyingTime('333ft', 7500, is_average=True)
    competition_details.SetQualifyingTime('333bf', 24000, is_average=False)
    competition_details.SetQualifyingTime('444bf', 60000, is_average=False)
    competition_details.SetQualifyingTime('555bf', 120000, is_average=False)
    competition_details.SetQualifyingTime('333mbf', 930000000, is_average=False)
    
    self.response.write(template.render({
        'c': common.Common(self),
        'competition': self.competition,
        'competition_details': competition_details,
    }))
示例#19
0
 def RespondWithError(self, error_string):
     template = JINJA_ENVIRONMENT.get_template('error.html')
     self.response.write(
         template.render({
             'c': common.Common(self),
             'error': error_string,
         }))
     self.response.status = 500
示例#20
0
    def get(self, competition_id):
        admin_override = False
        # This verifies intra-appengine requests.  See comment above FetchUrl for
        # explanation.
        if self.request.get('token'):
            token = RefreshToken.get_by_id(competition_id)
            if token and token.token == self.request.get('token'):
                admin_override = True
            else:
                self.response.set_status(400)
                self.response.write('mismatched token')
                return
        if not self.SetCompetition(competition_id,
                                   fail_if_not_found=False,
                                   edit_access_needed=(not admin_override),
                                   login_required=(not admin_override)):
            return
        if not self.GetToken():
            return

        response = self.GetWcaApi('/api/v0/competitions/%s/wcif' %
                                  competition_id)
        if response.status != 200:
            self.redirect(webapp2.uri_for('index', unknown=1))
            return
        response_json = json.loads(response.read())
        self.competition.name = response_json['name']
        self.competition.wca_competition = ndb.Key(Competition, competition_id)

        people = SchedulePerson.query(
            SchedulePerson.competition == self.competition.key).fetch()
        country_iso2s = set(person_data['countryIso2']
                            for person_data in response_json['persons'])
        countries = {
            country.iso2: country.key.id()
            for country in Country.query(Country.iso2.IN(country_iso2s))
        }
        out = ImportOutput()
        out.entities_to_put.append(self.competition)

        for person_data in response_json['persons']:
            ImportPerson(person_data, self.competition, out, people, countries)
        if out.errors:
            template = JINJA_ENVIRONMENT.get_template(
                'scheduling/import_error.html')
            self.response.write(
                template.render({
                    'c': common.Common(self),
                    'errors': out.errors
                }))
            return
        ndb.put_multi(out.entities_to_put)
        ndb.delete_multi(out.entities_to_delete)
        if not admin_override:
            self.redirect(
                webapp2.uri_for('edit_competition',
                                competition_id=competition_id))
示例#21
0
 def get(self, competition_id):
   if not self.SetCompetition(competition_id, edit_access_needed=False, login_required=False):
     return
   template = JINJA_ENVIRONMENT.get_template('scheduling/event_display.html')
   self.response.write(template.render({
       'c': common.Common(self),
       'competition': self.competition,
       'competition_details': CompetitionDetails(self.user, self.competition),
   }))
示例#22
0
 def get(self):
     template = JINJA_ENVIRONMENT.get_template(template_path)
     self.response.write(
         template.render({
             'c':
             common.Common(self),
             'result':
             'success' if self.request.get('success') else '',
         }))
示例#23
0
    def get(self, schedule_version, event_id):
        if not self.SetSchedule(int(schedule_version)):
            return
        event = Event.get_by_id(event_id)
        if not event:
            self.response.set_code(400)
            return
        rounds = ScheduleRound.query(
            ndb.AND(ScheduleRound.schedule == self.schedule.key,
                    ScheduleRound.event == event.key)).order(
                        ScheduleRound.number).fetch()
        time_blocks_by_round = collections.defaultdict(list)
        for time_block in (ScheduleTimeBlock.query(
                ScheduleTimeBlock.schedule == self.schedule.key).order(
                    ScheduleTimeBlock.start_time).iter()):
            time_blocks_by_round[time_block.round].append(time_block)
        # Immediately after adding a TimeBlock, it may not have propagated to the datastore.
        # So we force retrieval of the just-added TimeBlock.
        if 'include_time_block' in self.request.GET:
            time_block = ScheduleTimeBlock.get_by_id(
                self.request.GET['include_time_block'])
            found = False
            for old_time_block in time_blocks_by_round[time_block.round]:
                if old_time_block.key == time_block.key:
                    found = True
            if not found:
                time_blocks_by_round[time_block.round].append(time_block)
                time_blocks_by_round[time_block.round].sort(
                    key=lambda tb: tb.GetStartTime())

        stages = (ScheduleStage.query(
            ScheduleStage.schedule == self.schedule.key).order(
                ScheduleStage.number).fetch())
        competition_days = []
        current_date = self.schedule.start_date
        while current_date <= self.schedule.end_date:
            competition_days.append(current_date)
            current_date += datetime.timedelta(days=1)

        template = JINJA_ENVIRONMENT.get_template(
            'scheduling/event_details.html')
        self.response.write(
            template.render({
                'c': common.Common(self),
                'rounds': rounds,
                'event': event,
                'time_blocks': time_blocks_by_round,
                'new_ids': {
                    r.key: '%s_%d' % (r.key.id(), random.randint(2**4, 2**32))
                    for r in rounds
                },
                'stages': stages,
                'competition_days': competition_days,
            }))
示例#24
0
  def get(self):
    template = JINJA_ENVIRONMENT.get_template('my_competitions.html')
    if not self.user:
      self.response.write(template.render({
          'c': common.Common(self),
      }))
      return

    if not self.request.get('code'):
      self.redirect('/authenticate?' + urllib.urlencode({
          'callback': webapp2.uri_for('my_competitions', _full=True),
      }))
      return

    OAuthBaseHandler.GetTokenFromCode(self)
    if not self.auth_token:
      return

    response = self.GetWcaApi(
        '/api/v0/competitions?managed_by_me=true&start=%s' %
            (datetime.datetime.now() - datetime.timedelta(days=30)).isoformat())
    response_json = json.loads(response)

    my_registrations = Registration.query(Registration.user == self.user.key).fetch()
    my_competitions = ndb.get_multi([reg.competition for reg in my_registrations])
    my_competitions_by_id = {competition.key.id() : competition
                             for competition in my_competitions}

    managed_competitions = []
    for competition_dict in response_json:
      competition = my_competitions_by_id.get(competition_dict['id'], None)
      if not competition:
        competition = Competition.FromCompetitionSearch(competition_dict)
      managed_competitions.append(competition)

    self.response.write(template.render({
        'c': common.Common(self),
        'managed_competitions': managed_competitions,
        'my_competitions': my_competitions,
    }))
    return
示例#25
0
  def get(self):
    if not self.SetCompetition('CubingUSANationals2018', edit_access_needed=True):
      return

    template = JINJA_ENVIRONMENT.get_template('nationals/2018/schedule.html')
    competition_details = CompetitionDetails(self.user, self.competition)

    self.response.write(template.render({
        'c': common.Common(self),
        'competition': self.competition,
        'competition_details': competition_details,
    }))
示例#26
0
  def get(self):
    editable_competitions = [
        staff.competition.get() for staff in ScheduleStaff.query(
                                                 ScheduleStaff.user == self.user.key).iter()
        if StaffRoles.EDITOR in staff.roles]

    template = JINJA_ENVIRONMENT.get_template('scheduling/index.html')
    self.response.write(template.render({
        'c': common.Common(self),
        'editable_competitions': editable_competitions,
        'unknown_competition': self.request.get('unknown'),
    }))
示例#27
0
  def get(self, competition_id):
    if not self.user:
      template = JINJA_ENVIRONMENT.get_template('error.html')
      self.response.write(template.render({
          'c': common.Common(self),
          'error_message': 'Please log in.',
      }))
      return

    if not self.request.get('code'):
      self.redirect('/authenticate?' + urllib.urlencode({
          'callback': self.request.url,
      }))
      return

    OAuthBaseHandler.GetTokenFromCode(self)
    if not self.auth_token:
      return

    response = self.GetWcaApi('/api/v0/competitions/%s/wcif' % competition_id)
    response_json = json.loads(response)

    competition = Competition.FromWcifJson(response)
    competition.put()
    proto = competition.Proto()

    AddFakeAssignments(proto)

    new_competitors = {person['wcaUserId'] : person for person in response_json['persons']}
    old_competitors = {registration.user.id() : registration for registration in
                       Registration.query(Registration.competition == competition.key).iter()}

    to_put = []
    for competitor_id, competitor_dict in new_competitors.iteritems():
      competitor = (old_competitors.pop(competitor_id, None) or
                    Registration(id=Registration.Id(competition_id, competitor_id)))
      competitor.competition = competition.key
      competitor.user = ndb.Key(User, competitor_id)
      competitor.name = competitor_dict['name']
      competitor.is_admin = (competitor_dict.get('delegatesCompetition', False) or
                             competitor_dict.get('organizesCompetition', False) or
                             'delegate' in competitor_dict['registration'].get('roles', []) or
                             'organizer' in competitor_dict['registration'].get('roles', []))
      to_put.append(competitor)
    ndb.put_multi(to_put)

    ndb.delete_multi([ndb.Key(Registration, Registration.Id(competition_id, competitor_id))
                      for competitor_id in old_competitors.iterkeys()])

    self.redirect_to('my_competitions')
    return
示例#28
0
 def get(self):
     if not self.user:
         template = JINJA_ENVIRONMENT.get_template('scheduling/index.html')
         self.response.write(
             template.render({
                 'c': common.Common(self),
                 'logged_out': True,
             }))
         return
     self.redirect('/authenticate?' + urllib.urlencode(
         {
             'scope': 'public email manage_competitions',
             'callback': webapp2.uri_for('index_callback', _full=True),
         }))
示例#29
0
 def ImportWcifFromWca(self, data_to_import):
     response = self.GetWcaApi('/api/v0/competitions/%s/wcif' %
                               self.competition.key.id())
     if response.status != 200:
         template = JINJA_ENVIRONMENT.get_template(
             'scheduling/import_error.html')
         self.response.write(
             template.render({
                 'c': common.Common(self),
                 'errors': ['Error fetching WCA import']
             }))
         return
     response_json = json.loads(response.read())
     self.ImportWcif(response_json, data_to_import=data_to_import)
示例#30
0
 def TemplateDict(self, user):
     return {
         'c':
         common.Common(self),
         'user':
         user,
         'all_roles':
         Roles.AllRoles(),
         'editing_location_enabled':
         auth.CanEditLocation(user=user, editor=self.user),
         'can_view_roles':
         auth.CanViewRoles(user=user, viewer=self.user),
         'editable_roles':
         auth.EditableRoles(user=user, editor=self.user),
     }