예제 #1
0
def RemoveOldConferenceRooms(run_id):
    """Delete old access points that aren't available through rooms info service.

  Args:
    run_id: The room collection process run id for which this removal process
        step belongs to.
  """
    # If the run_id is no longer active just return success.
    config_value = _GetConferenceRoomRunConfigValue()
    if config_value['run_id'] != run_id:
        logging.info('Expired run_id? run=%s,datastore=%s', run_id,
                     config_value['run_id'])
        return

    run_start_time = config_value['run_start_time']

    query = models.AccessPoint.all()
    utils.AddFilter(query, 'last_modified <', run_start_time)
    utils.AddFilter(query, 'type =', utils.AccessPointType.ROOM)
    utils.AddFilter(query, 'deleted =', 0)

    # TODO(user): Lets be more careful in deleting access points.
    # We might have to send emails warning the deletion of the rooms.

    for access_point in query:
        access_point.Delete()

    # Make sure eventually we load this information into the access points info.
    deferred.defer(UpdateAccessPointsInfo, utils.AccessPointType.ROOM)
예제 #2
0
    def ActiveQuery(program=None,
                    activity=None,
                    user=None,
                    query=None,
                    keys_only=False):
        """Constructs query for active UserRegistrations with additional filters.

    Args:
      program: If not None the query will filter for registrations related to
          the given program.  Can be a db.Key or Program instance.
      activity: If not None the query will filter for registrations related to
          the given activity. Can be a db.Key or Activity instance.
      user: If not None the query will filter for registrations related to the
          given user.User.
      query: A valid query on the UserRegistration class that is modified to
          return active registrations. If None new query is created.
      keys_only: Boolean if only keys should be returned by the query.

    Returns:
      A query that can be used to access active registrations.
    """

        if query is None:
            query = UserRegistration.all(keys_only=keys_only)

        utils.AddFilter(query, 'active =', _Active.ACTIVE)

        if activity is not None:
            utils.AddFilter(query, 'activity =', activity)
        elif program is not None:
            utils.AddFilter(query, 'program =', program)
        if user is not None:
            utils.AddFilter(query, 'user =', user)

        return query
예제 #3
0
    def GetSearchableProgramsQuery():
        """Query programs that can be searched."""
        program_query = Program.all()
        utils.AddFilter(program_query, 'visible =', 1)
        utils.AddFilter(program_query, 'deleted =', 0)

        return program_query
예제 #4
0
def UpdateAccessPointsInfo(access_point_type):
    """Builds and stores access points info in a models.Configuration object.

  Args:
    access_point_type: utils.AccessPointType type of access points to load.

  Returns:
    Dict with keys 'keys', 'uris', 'timezone_names'. Values are arrays of string
    keys, uris and timezone names. For example: return_value['uris'][5],
    return_value['key'][5] are the uri and key of the same access point.
  """
    logging.info('Entering UpdateAccessPointsInfo')

    last_uri = None
    batch_query_size = 1000
    retrieved_count = batch_query_size
    access_points = []

    while retrieved_count == batch_query_size:
        logging.info(
            'Querying for access points with uri > %s, batch size = %d',
            last_uri, batch_query_size)

        query = db.Query(models.AccessPoint)
        utils.AddFilter(query, 'type =', access_point_type)
        if last_uri:
            utils.AddFilter(query, 'uri >', last_uri)
        query.order('uri')

        query_fetch = query.fetch(batch_query_size)
        retrieved_count = len(query_fetch)
        if query_fetch: last_uri = query_fetch[-1].uri
        access_points.extend(query_fetch)

    access_points_info = {
        'keys': [str(ap.key()) for ap in access_points],
        'uris': [ap.uri for ap in access_points],
        'timezone_names': [ap.timezone.name for ap in access_points],
        'tags': [ap.tags for ap in access_points],
    }

    # Store access points info in datastore config.
    key_name = _GetAccessPointInfoConfigKeyName(access_point_type)

    config_entity = models.Configuration(key_name=key_name,
                                         config_key='',
                                         config_value='',
                                         config_binary_value=pickle.dumps(
                                             access_points_info, 2))

    config_entity.put()

    logging.info('Exiting UpdateAccessPointsInfo. %s access points loaded',
                 len(access_points))
    return access_points_info
예제 #5
0
    def GetPendingApprovalsQuery(manager_user):
        """Returns query for pending manager approval requests for a manager.

    Args:
      manager_user: users.User object of the manager for whom the pending
          approval list should be queried.

    Returns:
      db.Query that can be queried to retrieve all the pending approvals.
    """
        pending_approvals = ManagerApproval.all()
        utils.AddFilter(pending_approvals, 'manager =', manager_user)
        utils.AddFilter(pending_approvals, 'manager_decision =', False)
        pending_approvals.order('queue_time')
        return pending_approvals
예제 #6
0
    def ActiveSchedulesQuery():
        """Build query to get all schedules that aren't deleted."""

        query = db.Query(ActivitySchedule)
        utils.AddFilter(query, 'deleted =', 0)

        return query
예제 #7
0
    def WaitlistRankForUser(activity, user):
        """Get the user's waitlist rank for a max capacity constrained course.

    Args:
      activity: Activity or db.Key of an Activity for which a user's waitlist
          rank is required.
      user: users.User for whom we need to find the waitlist rank.

    Returns:
      A integer waitlist rank starting from 1. If the waitlist cannot be found
      or the user not available in it, it returns 0.
    """

        query = UserRegistration.ActiveQuery(activity=activity)
        UserRegistration.AddRegisterOrder(query)
        utils.AddFilter(query, 'status =', utils.RegistrationStatus.WAITLISTED)
        queue_rank = 1

        for registration in query:
            if registration.user == user:
                break
            if registration.OnlyWaitingForMaxPeopleActivity():
                queue_rank += 1
        else:
            queue_rank = 0

        return queue_rank
예제 #8
0
    def ActivitySchedulesQuery(self):
        """Build query to get activity schedules under the program."""

        query = db.Query(ActivitySchedule)
        query.ancestor(self)
        utils.AddFilter(query, 'deleted =', 0)

        return query
예제 #9
0
    def SchedulesQueryFromActivityKey(cls, activity_key):
        """Build query to get the schedules under an activity given activity_key."""
        query = db.Query(ActivitySchedule)
        if isinstance(activity_key, basestring):
            activity_key = db.Key(activity_key)
        query.ancestor(activity_key)
        utils.AddFilter(query, 'deleted =', 0)

        return query
예제 #10
0
def SyncRegistrationForScheduleUnsafe(user, schedule_key):
  """Updates a schedule's calendar with the current user register status."""
  # Not run mutually exclusive with _SyncScheduleCalendarEventUnsafe. Activity
  # details and or calendars that this function is trying to modify can change
  # during the execution of this function.
  # Activity changes can be ignored since they will be proceesed later on in
  # _SyncScheduleCalendarEventUnsafe, and calendar updates collision will just
  # fail the calendar update since we always do a (read+update).
  schedule = utils.GetCachedOr404(schedule_key, active_only=False)

  if schedule.deleted or not schedule.calendar_edit_href:
    return  # Dont have to sync.

  # Check if there is an active and confirmed registration for the user.
  reg_query = models.UserRegistration.ActiveQuery(
      activity=schedule.parent_key(), user=user, keys_only=True)
  utils.AddFilter(reg_query, 'status =', utils.RegistrationStatus.ENROLLED)
  utils.AddFilter(reg_query, 'confirmed =', utils.RegistrationConfirm.PROCESSED)

  add_to_guest_list = reg_query.get() is not None

  # Get current event.
  calendar_event = _GetCalendarEvents(
      [schedule.calendar_edit_href], check_failures=True)[0]

  def AddAttendeeToEvent(event):
    """Function that updates given event by adding the user to who list."""
    event.who = [who for who in event.who if who.email != user.email()]
    new_who = calendar.Who(
        email=user.email(),
        attendee_status=_ACCEPTED_STATUS, attendee_type=_REQUIRED_TYPE,
    )
    event.who.append(new_who)

  def RemoveAttendeeFromEvent(event):
    """Function that updates given event by removing the user from who list."""
    event.who = [who for who in event.who if who.email != user.email()]

  if add_to_guest_list:
    update_func = AddAttendeeToEvent
  else:
    update_func = RemoveAttendeeFromEvent
  _UpdateCalendarEvents([calendar_event], update_func, check_failures=True)
예제 #11
0
def _GetScheduleEmailsForCalendar(schedule):
  """Get the emails relevant to a schedule to send calendar invites to.

  Get the email addresses of instructors and access point resource calendar
  email ids.

  Args:
    schedule: models.ActivitySchedule for which we need the invite email ids.

  Returns:
    Array of str email ids.
  """
  logging.debug('Entering _GetScheduleEmailsForCalendar')
  if schedule is None: return []

  email_set = set()

  # Add instructors to who list.
  for instructor in schedule.primary_instructors:
    email_set.add(instructor.email())

  activity = utils.GetCachedOr404(schedule.parent_key())
  if activity.reserve_rooms:
    # Add rooms if we have calendar names.
    access_point_key_list = (schedule.access_points +
                             schedule.access_points_secondary)
    access_points = request_cache.GetEntitiesFromKeys(access_point_key_list)
    for access_point in access_points:
      if access_point and access_point.calendar_email:
        email_set.add(access_point.calendar_email)

  # Add users who are registered and confirmed ofline.
  reg_query = models.UserRegistration.ActiveQuery(activity=activity)
  utils.AddFilter(reg_query, 'status =', utils.RegistrationStatus.ENROLLED)
  utils.AddFilter(reg_query, 'confirmed =', utils.RegistrationConfirm.PROCESSED)
  reg_query = utils.QueryIterator(reg_query, models.UserRegistration,
                                  prefetch_count=1000, next_count=1000)
  for reg in reg_query:
    email_set.add(reg.user.email())

  logging.debug('Exiting _GetScheduleEmailsForCalendar')
  return list(email_set)
예제 #12
0
    def ActivitiesQueryFromKey(program_key, keys_only=False):
        """Build query to get activities under the program.

    Args:
      program_key: Program db.Key to query activities under.
      keys_only: Boolean if only keys should be returned by the query.

    Returns:
      Query object that provides the requested Activities or db.Keys.
    """

        query = db.Query(Activity, keys_only=keys_only)
        query.ancestor(program_key)
        utils.AddFilter(query, 'deleted =', 0)

        return query
예제 #13
0
    def RegistrationsQuery(self):
        """Build query to get registrations for activities of a program."""

        query = db.Query(UserRegistration)
        utils.AddFilter(query, 'program =', self)
        return query
예제 #14
0
 def FromAppengineUsers(cls, appengine_users):
     """Query the appropriate GlearnUser given a user.User."""
     query = db.Query(cls)
     utils.AddFilter(query, 'user in', appengine_users)
     return query