Ejemplo n.º 1
0
    def _createConferenceObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException(
                "Conference 'name' field required")

        # copy ConferenceForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data['websafeKey']
        del data['organizerDisplayName']

        # add default values for those missing (both data model & outbound Message)
        for df in DEFAULTS:
            if data[df] in (None, []):
                data[df] = DEFAULTS[df]
                setattr(request, df, DEFAULTS[df])

        # convert dates from strings to Date objects; set month based on start_date
        if data['startDate']:
            data['startDate'] = datetime.strptime(data['startDate'][:10],
                                                  "%Y-%m-%d").date()
            data['month'] = data['startDate'].month
        else:
            data['month'] = 0
        if data['endDate']:
            data['endDate'] = datetime.strptime(data['endDate'][:10],
                                                "%Y-%m-%d").date()

        # set seatsAvailable to be same as maxAttendees on creation
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
        # generate Profile Key based on user ID and Conference
        # ID based on Profile key get Conference key from ID
        p_key = ndb.Key(Profile, user_id)
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = request.organizerUserId = user_id

        # create Conference, send email to organizer confirming
        # creation of Conference & return (modified) ConferenceForm
        Conference(**data).put()
        # TODO 2: add confirmation email sending task to queue
        Conference(**data).put()
        taskqueue.add(params={
            'email': user.email(),
            'conferenceInfo': repr(request)
        },
                      url='/tasks/send_confirmation_email')
        return request
def create_conferences(df):
    n_nodes = 0
    for _, row in df.drop_duplicates(subset=["conference"]).iterrows():
        conference = Conference(name=row["conference"])
        conference.save()
        n_nodes += 1
    print("created {} nodes".format(n_nodes))
Ejemplo n.º 3
0
    def _createConferenceObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException(
                "Conference 'name' field required")

        # copy ConferenceForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data['websafeKey']
        del data['organizerDisplayName']

        # add default values for those missing (both data model & outbound
        # Message)
        for df in DEFAULTS:
            if data[df] in (None, []):
                data[df] = DEFAULTS[df]
                setattr(request, df, DEFAULTS[df])

        # convert dates from strings to Date objects; set month based on
        # start_date
        if data['startDate']:
            data['startDate'] = datetime.strptime(data['startDate'][:10],
                                                  "%Y-%m-%d").date()
            data['month'] = data['startDate'].month
        else:
            data['month'] = 0
        if data['endDate']:
            data['endDate'] = datetime.strptime(data['endDate'][:10],
                                                "%Y-%m-%d").date()

        # set seatsAvailable to be same as maxAttendees on creation
        # both for data model & outbound Message
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

        # make Profile Key from user ID
        p_key = ndb.Key(Profile, user_id)
        # allocate new Conference ID with Profile key as parent
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
        # make Conference key from ID
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = request.organizerUserId = user_id

        # create Conference & return (modified) ConferenceForm
        Conference(**data).put()

        return request
Ejemplo n.º 4
0
 def _createConferenceObject(self, request):
     """Create or update a conference, returning ConferenceForm/request."""
     # Preload necessary data items
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException('Authorization required')
     user_id = user.email()
     if not request.name:
         raise endpoints.BadRequestException(
             "Conference 'name' field required")
     # Copy ConferenceForm/ProtoRPC Message into dict
     data = {
         field.name: getattr(request, field.name)
         for field in request.all_fields()
     }
     del data['websafeKey']
     del data['organizerDisplayName']
     # Add default values for those missing (both data model and
     # outbound Message)
     for df in CONF_DEFAULTS:
         if data[df] in (None, []):
             data[df] = CONF_DEFAULTS[df]
             setattr(request, df, CONF_DEFAULTS[df])
     # Convert dates from strings to Date objects; set month based
     # on start_date
     if data['startDate']:
         data['startDate'] = datetime.strptime(data['startDate'][:10],
                                               "%Y-%m-%d").date()
         data['month'] = data['startDate'].month
     else:
         data['month'] = 0
     if data['endDate']:
         data['endDate'] = datetime.strptime(data['endDate'][:10],
                                             "%Y-%m-%d").date()
     # Set seatsAvailable to be same as maxAttendees on creation
     if data["maxAttendees"] > 0:
         data["seatsAvailable"] = data["maxAttendees"]
     # Get the user profile key, then set the conference's parent
     # to that value.
     # NOTE: The original code made a call to allocate_ids in order to
     #       generate an ID for the conference. Since the profiles utilize
     #       strings (email addresses) for their IDs, resulting in no risk
     #       of colliding with NDB's auto-generated numeric IDs, I decided
     #       to let NDB generate the conference ID automatically.
     # https://cloud.google.com/appengine/docs/python/ndb/entities?hl=en#numeric_keys
     p_key = ndb.Key(Profile, user_id)
     data['parent'] = p_key
     data['organizerUserId'] = request.organizerUserId = user_id
     # Create Conference, send email to organizer confirming
     # creation of Conference and return (modified) ConferenceForm
     Conference(**data).put()
     taskqueue.add(params={
         'email': user.email(),
         'conferenceInfo': repr(request)
     },
                   url='/tasks/send_confirmation_email')
     return request
Ejemplo n.º 5
0
    def _createConferenceObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request."""
        
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException("Conference 'name' field required")

        # build out conference object
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        del data['websafeKey']
        del data['organizerDisplayName']

        # set defaults if needed
        for df in DEFAULTS:
            if data[df] in (None, []):
                data[df] = DEFAULTS[df]
                setattr(request, df, DEFAULTS[df])

        # format dates
        if data['startDate']:
            data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
            data['month'] = data['startDate'].month
        else:
            data['month'] = 0
        if data['endDate']:
            data['endDate'] = datetime.strptime(data['endDate'][:10], "%Y-%m-%d").date()

     
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

      
        p_key = ndb.Key(Profile, user_id)
       
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
     
     
        c_key = ndb.Key(Conference, c_id, parent=p_key)
  
        data['key'] = c_key
        data['organizerUserId'] = request.organizerUserId = user_id

        # create conference and create send email task
        Conference(**data).put()
        taskqueue.add(params={'email': user.email(),
            'conferenceInfo': repr(request)},
            url='/tasks/send_confirmation_email'
        )

        return request
Ejemplo n.º 6
0
def get_active_waiting_room(schedule):
    dateSchedule = as_date(schedule)
    # Refreshing database
    flush_transaction()
    try:
        allWaitingRooms = Conference.objects.filter(
            datecreated=dateSchedule, maxcapacity=WAITING_ROOM_MAX)
        logger.debug("All waiting rooms: " + str(allWaitingRooms))

        # Find free waiting room
        for waiting in allWaitingRooms:
            if waiting.available():
                logger.debug("Waiting room chosen: " + str(waiting.pk))
                return waiting

    # No free waiting rooms so create one
    except Conference.DoesNotExist:
        pass  # None found, so create one

    waiting = Conference()
    waiting.datecreated = dateSchedule
    waiting.maxcapacity = WAITING_ROOM_MAX
    waiting.save()
    return waiting
    def _createConferenceObject(self, request):
        """ Create or update Conference object, returning ConferenceForm/request. """
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user, id_type="oauth")

        # check wether the 'name' field is filled by user
        if not request.name:
            raise endpoints.BadRequestException(
                "Conference 'name' field required")

        # copy ConferenceForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data["websafeKey"]
        del data["organizerDisplayName"]

        # add default values for those missing (both data model & outbound Message)
        for df in DEFAULTS:
            if data[df] in (None, []):
                data[df] = DEFAULTS[df]
                setattr(request, df, DEFAULTS[df])

        # convert dates from strings to Date objects; set month based on start_date
        if data["startDate"]:  # start date
            data["startDate"] = datetime.strptime(data["startDate"][:10],
                                                  "%Y-%m-%d").date()
            data["month"] = data["startDate"].month
        else:
            data["month"] = 0
        if data["endDate"]:  # end date
            data["endDate"] = datetime.strptime(data["endDate"][:10],
                                                "%Y-%m-%d").date()

        # set seatsAvailable to be same as maxAttendees on creation
        # both for data model & outbound Message
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

        # make Profile Key from user ID
        p_key = ndb.Key(Profile, user_id)

        # allocate new Conference ID with Profile key as parent
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]

        # make Conference key from ID
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data["key"] = c_key
        data["organizerUserId"] = request.organizerUserId = user_id

        # creates the conference object and put onto the cloud datastore
        Conference(**data).put()

        # send confirmation email
        taskqueue.add(params={
            "email": user.email(),
            "conferenceInfo": repr(request)
        },
                      url="/tasks/send_confirmation_email")

        # return the (updated) ConferenceForm
        return request
Ejemplo n.º 8
0
    def _createConferenceObject(self, request):
        """Create a Conference object, returning ConferenceForm/request."""
        
        # Getting and Verifying current user
        user = getUser()

        # get the user_id (email) 
        user_id = getUserId(user)

        # Checking if the name field is filled out. 
        checkFieldValue(request.name)

        # copy ConferenceForm/ProtoRPC Message into dict
        data = ({field.name: getattr(request, field.name)
                for field in request.all_fields()})
        
        # Getting deleted because they are not part of the ndb model
        del data['websafeKey']
        
        del data['organizerDisplayName']
        
        # add default values for those missing
        for df in CONFERENCE_DEFAULTS:
            
            if data[df] in (None, []):
            
                data[df] = CONFERENCE_DEFAULTS[df]
            
                setattr(request, df, CONFERENCE_DEFAULTS[df])
        
        # convert dates TO strings using the Date objects
        if data['startDate']:
            
            data['startDate'] = datetime.strptime(
                                    data['startDate'][:10], "%Y-%m-%d").date()
            
            data['month'] = data['startDate'].month
        
        else:
            
            data['month'] = 0
        
        if data['endDate']:
        
            data['endDate'] = datetime.strptime(
                data['endDate'][:10], "%Y-%m-%d").date()

        # set seatsAvailable to be same as maxAttendees on creation
        if data["maxAttendees"] > 0:
        
            data["seatsAvailable"] = data["maxAttendees"]

        #---- Generate a Profile Key based on user ID and Conference ----
        
        # Profile key
        p_key = ndb.Key(Profile, user_id)

        # allocate new Conference ID with Profile key as parent
        c_id  = Conference.allocate_ids(size=1, parent=p_key)[0]

        # make Conference key using p_key and c_id 
        c_key = ndb.Key(Conference, c_id, parent=p_key)

        # Update stored conference with profile and conference key
        data['key'] = c_key
        
        data['organizerUserId'] = request.organizerUserId = user_id
        
        # create Conference, send email to organizer confirming
        # creation of Conference & return (modified) ConferenceForm
        Conference(**data).put()
        
        # cron job
        taskqueue.add(
            
            params = {
                'email'   : user.email(),
                'subject' : 'You Created a New Conference!',
                'body'    : 'Here are the details for your conference:',
                'info'    : repr(request)},
            
            url    = '/tasks/send_confirmation_email')    
        
        return request
Ejemplo n.º 9
0
    def _createConferenceObject(self, request):
        """Create or update Conference object, returning ConferenceForm/request.
        """

        # Fetch current user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException(
                'Authorization required')
        user_id = getUserId(user)

        # Test for Conference name in request
        if not request.name:
            raise endpoints.BadRequestException(
                "Conference 'name' field required")

        # Copy ConferenceForm/ProtoRPC Message into dict.
        data = {field.name: getattr(request, field.name) \
            for field in request.all_fields()}
        del data['websafeKey']
        del data['organizerDisplayName']

        # Add default values for those missing 
        # (both data model & outbound Message)
        for df in DEFAULTS:
            if data[df] in (None, []):
                data[df] = DEFAULTS[df]
                setattr(request, df, DEFAULTS[df])

        # Convert dates from strings to Date objects.
        # Set month based on start_date.
        if data['startDate']:
            data['startDate'] = datetime.strptime(
                data['startDate'][:10], "%Y-%m-%d").date()
            data['month'] = data['startDate'].month
        else:
            data['month'] = 0
        if data['endDate']:
            data['endDate'] = datetime.strptime(
                data['endDate'][:10], "%Y-%m-%d").date()

        # Set seatsAvailable to be same as maxAttendees on creation, 
        # both for data model & outbound Message
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])

        # Make Profile Key from user ID as p_key
        p_key = ndb.Key(Profile, user_id)

        # Allocate new c_id with p_key as parent
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]

        # Make Conference key from ID, uses p_key to define parent 
        # and c_id as unique id
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = request.organizerUserId = user_id

        # Create Conference
        Conference(**data).put()

        # Send email to organizer confirming creation of Conference
        taskqueue.add(
            params={'email': user.email(), 
            'conferenceInfo': repr(request)}, 
            url='/tasks/send_confirmation_email')

        # Return (modified) ConferenceForm
        return request
Ejemplo n.º 10
0
import teams
from models import Conference

Asia = Conference(name='Asia',
                  max_teams=1,
                  teams=(
                      teams.Australia,
                      teams.Japan,
                      teams.SouthKorea,
                      teams.SaudiArabia,
                      teams.Iran,
                  ))
Africa = Conference(name='Africa',
                    max_teams=1,
                    teams=(
                        teams.Tunisia,
                        teams.Egypt,
                        teams.Senegal,
                        teams.Nigeria,
                        teams.Morocco,
                    ))
SouthAmerica = Conference(name='South America',
                          max_teams=1,
                          teams=(
                              teams.Brazil,
                              teams.Argentina,
                              teams.Uruguay,
                              teams.Peru,
                              teams.Colombia,
                          ))
Europe = Conference(name='Europe',
Ejemplo n.º 11
0
def init():
    db.drop_all()
    db.create_all()

    # Create roles
    user_datastore.create_role(name='admin',
                               description='System administrator')
    user_datastore.create_role(name='user', description='Conference user')
    admin = user_datastore.create_user(
        username='******', password=utils.encrypt_password('admin'))
    user = user_datastore.create_user(username='******',
                                      password=utils.encrypt_password('user'))
    user_datastore.add_role_to_user(admin, 'admin')
    user_datastore.add_role_to_user(user, 'user')

    contacts = [
        ('1010', gettext('John Smith')),
        ('1020', gettext('Sam Brown')),
    ]
    for c in contacts:
        rec = Contact(phone=c[0], name=c[1], user=admin)
        db.session.add(rec)

    guest_user_profile = ParticipantProfile(name=gettext('Guest'),
                                            startmuted=True)
    db.session.add(guest_user_profile)
    marked_user_profile = ParticipantProfile(name=gettext('Marker'),
                                             marked=True)
    db.session.add(marked_user_profile)
    admin_user_profile = ParticipantProfile(name=gettext('Administrator'),
                                            admin=True)
    db.session.add(admin_user_profile)

    conf_profile = ConferenceProfile(name=gettext('Default'))
    db.session.add(conf_profile)

    conf = Conference(
        number=100,
        name=gettext('Test Conference'),
        conference_profile=conf_profile,
        public_participant_profile=guest_user_profile,
        is_public=True,
        user=admin,
    )
    db.session.add(conf)

    p1 = Participant(conference=conf,
                     profile=admin_user_profile,
                     phone='1001',
                     user=admin)
    p2 = Participant(conference=conf,
                     profile=guest_user_profile,
                     phone='1002',
                     user=admin)
    p3 = Participant(conference=conf,
                     profile=marked_user_profile,
                     phone='1003',
                     user=admin)
    db.session.add(p1)
    db.session.add(p2)
    db.session.add(p3)

    db.session.commit()
Ejemplo n.º 12
0
def match_or_send_to_waiting_room(call, schedule):

    # Refreshing database object
    flush_transaction()
    call.reload()

    if call.matched:
        other = call.conference.call_set.exclude(pk=call.pk)[0]
        data = send_to_conference_room(call, schedule, other, initial=False)

        if data: return data

    matchcall = find_match(schedule, call)
    if matchcall:
        conf = Conference()
        conf.maxcapacity = 2
        conf.datecreated = as_date(schedule)
        conf.save()

        call.conference = conf
        call.matched = True
        call.save()

        matchcall.conference = conf
        matchcall.matched = True
        matchcall.save()

        data = send_to_conference_room(call, schedule, matchcall, initial=True)
        if data: return data

    if call.user.profile.any_match:
        call.user.profile.any_match = False
        call.user.profile.save()

        return render_to_response(
            "twilioresponse.xml", {
                'say':
                "We are very sorry - We could not find you a match today, but tomorrow we'll do our best to compensate it! We wish you an awesome day!",
                'hangup': True
            })
    #Check if we have exceeded the waiting redirect limits
    elif call.retries >= REDIRECT_LIMIT:
        # The user has reached the limit of redials, so hang up
        logger.debug("LIMIT RETRIES - Ask to try to match with any person")
        any_match = "We could not find any matches. If you'd like us to try to match you with Anyone please press any number now."
        goodbye = "We wish you an Amazing day! Good bye!"
        return render_to_response(
            "twilioresponse.xml", {
                'any_match': any_match,
                'schedule': schedule,
                'hangup': True,
                'goodbye': goodbye
            })

    call.retries = call.retries + 1
    call.save()

    # Send user to private conference (Conferencename=Username) or send them to the waiting room they were at
    return send_to_waiting_room(
        HOLD_LIMIT, schedule, call.user.username, False,
        "Please bare with us - we'll find the best match for you!")