Exemple #1
0
def result_to_institution(r):
    inst = Institution(r["institution_uuid"], r["institution_name"],
                       r["institution_country_code"])
    inst.load_contacts()
    inst.load_ip_ranges()
    inst.load_dates()
    inst.load_relations()
    return inst
Exemple #2
0
def populate():
    transformer = GridTransformer(schema)
    for doc in get_jsons():
        try:
            transformed = transformer.transform(doc, load=False)
            #logger.info('Adding {0}.'.format(transformed['name']))

            inst = Institution(**transformed)
            inst.save()
        except UnicodeDecodeError:
            pass
Exemple #3
0
def populate():
    with open(IPEDS_FILE) as f:
        reader = csv.reader(f)

        transformer = IpedsTransformer(schema, next(reader))

        for row in reader:
            transformed = transformer.transform(row)
            logger.info('Adding {0}.'.format(transformed['name']))
            
            inst = Institution(country='United States', **transformed)
            inst.save()
Exemple #4
0
def initModels(cls):
    """Init the models."""
    # new User user
    cls.user = User()
    cls.user.name = 'user'
    cls.user.state = "active"
    cls.user.email = ['*****@*****.**']
    cls.user.institutions = []
    cls.user.follows = []
    cls.user.institutions_admin = []
    cls.user.posts = []
    cls.user.put()
    # new User second_user
    cls.second_user = User()
    cls.second_user.name = 'second_user'
    cls.second_user.email = ['*****@*****.**']
    cls.second_user.state = "active"
    cls.second_user.institutions = []
    cls.second_user.follows = []
    cls.second_user.institutions_admin = []
    cls.second_user.posts = []
    cls.second_user.put()
    # new Institution institution
    cls.institution = Institution()
    cls.institution.name = 'institution'
    cls.institution.state = "active"
    cls.institution.email = '*****@*****.**'
    cls.institution.members = [cls.user.key]
    cls.institution.followers = [cls.user.key, cls.second_user.key]
    cls.institution.posts = []
    cls.institution.admin = cls.user.key
    cls.institution.put()
    # another institution
    cls.other_institution = Institution()
    cls.other_institution.name = 'other_institution'
    cls.other_institution.state = 'active'
    cls.other_institution.email = '*****@*****.**'
    cls.other_institution.members = [cls.user.key]
    cls.other_institution.followers = [cls.user.key]
    cls.other_institution.posts = []
    cls.other_institution.admin = cls.user.key
    cls.other_institution.put()

    cls.user.institutions = [cls.institution.key, cls.other_institution.key]
    cls.user.institutions_admin = [
        cls.institution.key, cls.other_institution.key
    ]
    cls.user.follows = [cls.other_institution.key, cls.institution.key]
    cls.user.put()
    cls.second_user.follows = [cls.institution.key]
    cls.second_user.put()
Exemple #5
0
    def test_has_connection_between(self):
        #  create hierarchy
        # institution -> child_a -> child_b -> child_c
        child_a = mocks.generate_child_to_parent(self.institution)
        child_b = mocks.generate_child_to_parent(child_a)
        child_c = mocks.generate_child_to_parent(child_b)
        independent_instituion = mocks.create_institution()

        # update institution
        self.institution = self.institution.key.get()

        # verifies the hierarchy
        self.assertEquals(self.institution.parent_institution, None,
                          "institution should not have a parent")
        self.assertEquals(child_a.parent_institution, self.institution.key,
                          "institution should be parent of child_a")
        self.assertEquals(child_b.parent_institution, child_a.key,
                          "child_a should be parent of child_b")
        self.assertEquals(child_c.parent_institution, child_b.key,
                          "child_b should be parent of child_c")
        self.assertEquals(independent_instituion.parent_institution, None,
                          "independent_institution should not have a parent")
        self.assertEquals(independent_instituion.children_institutions, [],
                          "independent_institution should not have children")

        # verifies the connections
        # Case 1: institutions directly connected
        self.assertTrue(
            Institution.has_connection_between(child_a.key,
                                               self.institution.key),
            "The connection between child_a and institution should be true")
        # Case 2: institutions indirectly connected
        self.assertTrue(
            Institution.has_connection_between(child_b.key,
                                               self.institution.key),
            "The connection between child_b and institution should be true")
        self.assertTrue(
            Institution.has_connection_between(child_c.key,
                                               self.institution.key),
            "The connection between child_c and institution should be true")
        # Case 3: institutions disconnected
        self.assertFalse(
            Institution.has_connection_between(independent_instituion.key,
                                               self.institution.key),
            "The connection between independent_instituion and institution should be false"
        )
        self.assertFalse(
            Institution.has_connection_between(self.institution.key,
                                               independent_instituion.key),
            "The connection between institution and independent_instituion should be false"
        )
Exemple #6
0
    def GET(self, name):
        """ Get institutions."""
        logger.debug("Query: %s" % (web.input()))

        institution_uuid   = web.input().get('institution_uuid')
        if institution_uuid:
            results = Institution.get_institution(institution_uuid)
        else:
            results = Institution.get_all()

        if not results:
            raise Error(NORESULT)
        data = results_to_institutions(results)
        return data
Exemple #7
0
def create_institution(name=None):
    """Create institution function."""
    institution = Institution()
    inst_hash = getHash(institution)
    institution.name = name or "Inst %s" % inst_hash
    institution.address = create_address()
    institution.description = "description"
    institution.institutional_email = "*****@*****.**" % inst_hash
    institution.state = "active"
    institution.put()
    return institution
Exemple #8
0
def _save_institution(cd):
    institution = Institution()
    institution.id = cd['id'] or None
    institution.observation = cd['observation']
    institution.name = cd['name']
    institution.country = cd['country']
    institution.save()
    return institution
Exemple #9
0
    def test_make(self):
        """Test make method."""
        user = mocks.create_user()
        parent_inst = mocks.create_institution()
        parent_inst.admin = user.key
        user.add_institution_admin(parent_inst.key)
        user.put()
        parent_inst.put()
        second_user = mocks.create_user()

        data = {
            'institution_key': parent_inst.key.urlsafe(),
            'admin_key': user.key.urlsafe(),
            'invitee': second_user.email[0],
            'suggestion_institution_name': 'test'
        }

        invite = InviteInstitutionChildren.create(data)
        invite.put()

        institution = parent_inst.make(InviteInstitutionChildren.INST_PROPS_TO_MAKE)
        expected_json = {
            'admin_name': invite.admin_key.get().name,
            'sender_name': invite.sender_name,
            'key': invite.key.urlsafe(),
            'institution_admin': parent_inst.make(['name']),
            'institution': institution,
            'invitee': invite.invitee,
            'suggestion_institution_name': invite.suggestion_institution_name,
            'stub_institution': Institution.make(invite.stub_institution_key.get(), ['name', 'key', 'state']),
            'type_of_invite': 'INSTITUTION_CHILDREN',
            'status': 'sent'
        }

        self.assertEquals(expected_json, invite.make())
def initModels(cls):
    """Init the models."""
    # new User Raoni
    cls.user = User()
    cls.user.name = 'Raoni Smaneoto'
    cls.user.email = ['*****@*****.**']
    cls.user.institutions = []
    cls.user.put()
    # new Institution CERTBIO
    cls.certbio = Institution()
    cls.certbio.name = 'CERTBIO'
    cls.certbio.members = [cls.user.key]
    cls.certbio.followers = [cls.user.key]
    cls.certbio.put()
    cls.user.institutions.append(cls.certbio.key)
    cls.certbio_profile = InstitutionProfile()
    cls.certbio_profile.phone = '(74) 99937-357'
    cls.certbio_profile.email = '*****@*****.**'
    cls.certbio_profile.institution_key = cls.certbio.key.urlsafe()
    cls.certbio_profile.office = "developer"
    cls.certbio_profile.name = cls.certbio.name
    cls.certbio_profile.photo_url = 'photourl'
    cls.certbio_profile.color = 'green'
    cls.user.institution_profiles.append(cls.certbio_profile)
    cls.user.put()
Exemple #11
0
def initModels(cls):
    """Init the models."""
    # new User user
    cls.user = User()
    cls.user.name = 'user name'
    cls.user.photo_url = 'urlphoto'
    cls.user.cpf = '089.675.908-90'
    cls.user.email = ['*****@*****.**']
    cls.user.put()
    # new Institution CERTBIO
    cls.certbio = Institution()
    cls.certbio.name = 'CERTBIO'
    cls.certbio.photo_url = 'urlphoto'
    cls.certbio.members = [cls.user.key]
    cls.certbio.followers = [cls.user.key]
    cls.certbio.admin = cls.user.key
    cls.certbio.put()
    """ Update User."""
    cls.user.add_institution(cls.certbio.key)
    cls.user.follows = [cls.certbio.key]
    cls.user.put()

    # Events
    cls.event = Event()
    cls.event.title = "New Event"
    cls.event.author_key = cls.user.key
    cls.event.author_name = cls.user.name
    cls.event.author_photo = cls.user.photo_url
    cls.event.institution_key = cls.certbio.key
    cls.event.institution_name = cls.certbio.name
    cls.event.institution_image = cls.certbio.photo_url
    cls.event.start_time = datetime.datetime.now()
    cls.event.end_time = datetime.datetime.now()
    cls.event.local = "Event location"
    cls.event.put()
Exemple #12
0
def initModels(cls):
    """Init the models."""
    # new Institution
    cls.institution = Institution()
    cls.institution.name = 'Test institution'
    cls.institution.put()
    # new User
    cls.user = User()
    cls.user.name = "Test user"
    cls.user.state = "active"
    cls.user.email = ['*****@*****.**']
    cls.user.put()
    # new second_user
    cls.second_user = User()
    cls.second_user.name = 'Second User Test'
    cls.second_user.state = "active"
    cls.second_user.email = ['*****@*****.**']
    cls.second_user.put()
    # new Post
    cls.post = Post()
    cls.post.subscribers = [cls.second_user.key]
    cls.post.author = cls.second_user.key
    cls.post.institution = cls.institution.key
    cls.post.state = 'published'
    cls.post.put()
Exemple #13
0
def initModels(cls):
    """Init the models."""
    # new User user
    cls.user = User()
    cls.user.name = 'user'
    cls.user.email = ['*****@*****.**']
    cls.user.put()

    # new Institution
    cls.institution = Institution()
    cls.institution.name = 'institution'
    cls.institution.members = [cls.user.key]
    cls.institution.followers = [cls.user.key]
    cls.institution.admin = cls.user.key
    cls.institution.put()

    # POST of user To institution
    cls.post_user = {
        'title': "Novo edital do institution",
        'text': "At vero eos et accusamus et iusto odio",
        'institution': cls.institution.key.urlsafe()
    }
    cls.post_aux = {
        'title': "Post Auxiliar",
        'text': "At vero eos et accusamus et iusto",
        'institution': cls.institution.key.urlsafe()
    }
    cls.user.follows = [cls.institution.key]
    cls.user.put()

    cls.user.add_institution(cls.institution.key)
    def post(self, user, institution_urlsafe):
        """Handler of post requests. This method is called when an
        institution requests to be parent of other institution."""
        user.check_permission('send_link_inst_request',
                              'User is not allowed to send request',
                              institution_urlsafe)

        data = json.loads(self.request.body)
        host = self.request.host
        inst_children_request_type = 'REQUEST_INSTITUTION_CHILDREN'

        type_of_invite = data.get('type_of_invite')

        Utils._assert(type_of_invite != inst_children_request_type,
                      "The type must be REQUEST_INSTITUTION_CHILDREN",
                      EntityException)

        parent_key = ndb.Key(urlsafe=institution_urlsafe)
        requested_inst_key = data.get('institution_requested_key')
        requested_inst_key = ndb.Key(urlsafe=requested_inst_key)

        Utils._assert(
            Institution.has_connection_between(parent_key, requested_inst_key),
            "Circular hierarchy not allowed", EntityException)

        request = InviteFactory.create(data, type_of_invite)
        request.put()

        institution_parent = parent_key.get()
        institution_parent.add_child(requested_inst_key)

        request.send_invite(host, user.current_institution)

        self.response.write(json.dumps(request.make()))
Exemple #15
0
 def DELETE(self, name):
     """Deletes institution using institution uuid."""
     institution_uuid = web.input().get('institution_uuid')
     try:
         assert institution_uuid
     except AssertionError as error:
         logger.debug(error)
         raise Error(BADPARAMS)
     try:
         result = Institution.get_institution(institution_uuid)[0]
     except:
         raise Error(NOTFOUND,msg="The institution provided does not exist.")
     institution = Institution(result['institution_uuid'],
                 result['institution_name'],result['institution_country_code'])
     institution.delete()
     return [institution.__dict__]
    def get(self, user):
        """Get all institutions."""
        INSTITUTION_ATTRIBUTES = [
            'name', 'key', 'acronym', 'address', 'photo_url', 'description',
            'admin', 'cover_photo', 'institutional_email'
        ]
        ACTIVE_STATE = "active"

        page = to_int(
            self.request.get('page', Utils.DEFAULT_PAGINATION_OFFSET),
            QueryException, "Query param page must be an integer")
        limit = to_int(
            self.request.get('limit', Utils.DEFAULT_PAGINATION_LIMIT),
            QueryException, "Query param limit must be an integer")

        queryInstitutions = Institution.query(
            Institution.state == ACTIVE_STATE)

        queryInstitutions, more = offset_pagination(page, limit,
                                                    queryInstitutions)

        array = [
            institution.make(INSTITUTION_ATTRIBUTES)
            for institution in queryInstitutions
        ]

        data = {'institutions': array, 'next': more}

        self.response.write(json.dumps(data))
Exemple #17
0
    def get(self):

        self.templateVars["institutions"] = Institution.query().fetch()
        self.templateVars["authors"] = Author.query().fetch()
        self.templateVars["conferences"] = Conference.query().fetch()
        self.templateVars["publications"] = Publication.query().fetch()
        self.templateVars["contents"] = Content.query().fetch()
        return self.render("admin.html")
Exemple #18
0
def parentToJson(obj):
    """Return json with parent institution."""
    if(obj.parent_institution):
        parent_institution = obj.parent_institution.get()
        institution_parent_json = Institution.make(parent_institution, [
            'name', 'key', 'state', 'invite', 'photo_url', 'acronym'])
        institution_parent_json['children_institutions'] = childrenToJson(parent_institution)
        return institution_parent_json
    def post(self, user, institution_urlsafe):
        """Handle POST requests.
        It sends a request to the requested_institution
        to be parent of child_inst, whose key representation
        is institution_urlsafe. It can only be done if the user
        has permission to send the request, if the child_institution
        has no parent and if the two institutions are not linked yet.
        """
        user.check_permission('send_link_inst_request',
                              'User is not allowed to send request',
                              institution_urlsafe)

        data = json.loads(self.request.body)
        host = self.request.host
        inst_parent_request_type = 'REQUEST_INSTITUTION_PARENT'

        type_of_invite = data.get('type_of_invite')

        Utils._assert(type_of_invite != inst_parent_request_type,
                      "The type must be REQUEST_INSTITUTION_PARENT",
                      EntityException)

        child_key = ndb.Key(urlsafe=institution_urlsafe)
        requested_inst_key = data.get('institution_requested_key')
        requested_inst_key = ndb.Key(urlsafe=requested_inst_key)

        child_institution = child_key.get()
        Utils._assert(child_institution.parent_institution != None,
                      "The institution's already have a parent",
                      NotAuthorizedException)

        Utils._assert(
            Institution.has_connection_between(requested_inst_key, child_key),
            "Circular hierarchy not allowed", EntityException)

        request = InviteFactory.create(data, type_of_invite)

        @ndb.transactional(retries=10, xg=True)
        def main_operations(request, requested_inst_key, child_institution,
                            user, host):

            child_institution.parent_institution = requested_inst_key
            child_institution.put()

            if child_institution.key in requested_inst_key.get(
            ).children_institutions:
                remake_link(request, requested_inst_key, child_institution,
                            user)
            else:
                request.put()
                request.send_invite(host, user.current_institution)

            return request

        request = main_operations(request, requested_inst_key,
                                  child_institution, user, host)

        self.response.write(json.dumps(request.make()))
def childrenToJson(obj):
    """Return the array with json from institution that are obj children."""
    json = [
        Institution.make(institution.get(), [
            'name', 'photo_url', 'key', 'state', 'invite',
            'parent_institution', 'acronym'
        ]) for institution in obj.children_institutions
    ]
    return json
Exemple #21
0
 def PUT(self, name):
     """Checks if entry exists using uuid, then modifies it."""
     data = json.loads(web.data())
     institution_uuid = data.get('institution_uuid')
     name = data.get('institution_name')
     country_code = data.get('country_code')
     try:
         assert institution_uuid and name and country_code
     except AssertionError as error:
         logger.debug(error)
         raise Error(BADPARAMS)
     try:
         assert Institution.get_institution(institution_uuid)[0]
     except:
         raise Error(NOTFOUND,msg="The institution provided does not exist.")
     institution = Institution(institution_uuid,name,country_code)
     institution.update()
     return [institution.__dict__]
Exemple #22
0
def add_institution():
    if request.method == 'POST':
        info = Institution(college_name=request.data['college_name'],
                           college_short=request.data['college_short'])
        session.add(info)
        session.commit()
        return {'status': 'successfully added institution'}
    else:
        return {'status': 'running'}
Exemple #23
0
def generate_child_to_parent(parent, child_admin=None):
    """Create a child for the parent."""
    admin = create_user() if child_admin is None else child_admin
    child = create_institution()
    child.add_member(admin)
    child.set_admin(admin.key)
    admin.add_permissions(DEFAULT_ADMIN_PERMISSIONS, child.key.urlsafe())
    data = {
        'sender_key': admin.key.urlsafe(),
        'institution_requested_key': parent.key.urlsafe(),
        'admin_key': admin.key.urlsafe(),
        'institution_key': child.key.urlsafe()
    }
    parent_invite = RequestInstitutionParent.create(data)
    # link child_a to institution
    Institution.create_parent_connection(parent, parent_invite)
    #  update child
    child = child.key.get()
    return child
Exemple #24
0
def add_institution():
    info = Institution(name = request.data['college_name'], short = request.data['college_short'])
    session.add(info)
    try:
        session.commit()
    except:
        session.rollback()
        flash(config.UNEXPECTED_ERROR)
    finally:
        session.close()
    return redirect('/dashboard')
Exemple #25
0
 def POST(self, name):
     """Inserts new institution."""
     data = json.loads(web.data())
     institution_name = data.get('institution_name')
     country_code = data.get('country_code')
     country_name = data.get('country_name')
     institution_notes = data.get('institution_notes')
     contacts = data.get('contacts')
     ip_ranges = data.get('ip_ranges')
     parent_of = data.get('parent_of')
     child_of = data.get('child_of')
     try:
         assert institution_name
     except AssertionError as error:
         logger.debug(error)
         raise Error(BADPARAMS)
     try:
         country = ""
         if country_name and not country_code:
             country = country_name
             country_code = Country.get_from_name(country_name).first()['country_code']
         elif country_code and not country_name:
             country = country_code
             country_name = Country(country_code).get_names().first()['country_name']
         else:
             raise Error(BADPARAMS,msg="No country provided.")
     except:
         raise Error(BADPARAMS,msg="Country '%s' does not exist." %(country))
     institution_uuid = generate_uuid()
     institution = Institution(institution_uuid,institution_name,
                                                 country_code,
                                                 institution_notes,
                                                 contacts,
                                                 ip_ranges,
                                                 parent_of,
                                                 child_of)
     institution.save()
     return [institution.__dict__]
Exemple #26
0
def initModels(cls):
    """Initialize the models."""
    # admin
    cls.admin = User()
    cls.admin.name = "admin"
    cls.admin.email = ["admin@email"]
    cls.admin.put()

    # user
    cls.user = User()
    cls.user.name = "user"
    cls.user.email = ["user@email"]
    cls.user.put()

    # New institution
    cls.institution = Institution()
    cls.institution.name = "institution"
    cls.institution.admin = cls.admin.key
    cls.institution.members = [cls.admin.key]
    cls.institution.followers = [cls.admin.key]
    cls.institution.put()

    # update admin
    cls.admin.institutions_admin = [cls.institution.key]
    cls.admin.put()

    # New invite
    cls.invite = Invite()
    cls.invite.invitee = cls.user.email[0]
    cls.invite.admin_key = cls.admin.key
    cls.invite.sender_key = cls.admin.key
    cls.invite.sender_name = cls.admin.name
    cls.invite.status = "sent"
    cls.invite.institution_key = cls.institution.key
    cls.invite.put()

    cls.data = {
        "admin_key": cls.admin.key.urlsafe(),
        "is_request": False,
        "institution_key": cls.institution.key.urlsafe(),
        "sender_key": cls.admin.key.urlsafe(),
        "sender_name": cls.admin.name
    }

    cls.expected_invite = Invite()
    cls.expected_invite.admin_key = cls.admin.key
    cls.expected_invite.is_request = False
    cls.expected_invite.institution_key = cls.institution.key
    cls.expected_invite.sender_key = cls.admin.key
    cls.expected_invite.sender_name = cls.admin.name
Exemple #27
0
def initModels(cls):
    """Init the models."""
    # new User
    cls.user = User()
    cls.user.name = 'User'
    cls.user.email = ['*****@*****.**']
    cls.user.institutions = []
    cls.user.posts = []
    cls.user.put()

    # new Institution inst test
    cls.institution = Institution()
    cls.institution.name = 'inst test'
    cls.institution.members = [cls.user.key]
    cls.institution.admin = cls.user.key
    cls.institution.put()

    cls.user.institutions = [cls.institution.key]
    cls.user.put()

    cls.options = [
        {'id': 0,
         'text': 'frist option',
         'number_votes': 0,
         'voters': []
         },
        {'id': 1,
         'text': 'second option',
         'number_votes': 0,
         'voters': []
         }]

    cls.data_binary = {
        'title': 'Survey with Binary choice',
        'type_survey': 'binary',
        'deadline': '2020-07-25T12:30:15',
        'options': cls.options
    }

    cls.data_multiple = {
        'title': 'Survey with Multiple choice',
        'type_survey': 'multiple_choice',
        'deadline': '2020-07-25T12:30:15',
        'options': cls.options
    }

    cls.voter = {'name': cls.user.name,
                 'photo_url': cls.user.photo_url,
                 'key': cls.user.key.urlsafe()}
def add_institution():
    if request.method == 'POST':
        info = Institution(name=request.data['college_name'],
                           short=request.data['college_short'])
        session.add(info)
        session.commit()
        return {
            'status': 'OK',
            'message': 'SUCCESS',
        }, 200
    else:
        return {
            'status': 'OK',
            'message': 'RUNNING',
        }, 200
def createInstitution(user, data):
    """Cretate a new institution stub."""
    inst_stub = Institution()

    for property in data:
        if property != 'admin':
            setattr(inst_stub, property, data[property])

    if (data.get("photo_url") is None):
        inst_stub.photo_url = "app/images/institution.png"

    inst_stub.address = Address.create(data.get('address'))
    inst_stub.state = 'pending'
    inst_stub.put()

    return inst_stub
    def get(self, user, url_string):
        """Handle GET Requests."""
        obj_key = ndb.Key(urlsafe=url_string)
        obj = obj_key.get()
        Utils._assert(obj.state == 'inactive',
                      "The institution has been deleted",
                      NotAuthorizedException)
        assert type(obj) is Institution, "Key is not an Institution"
        institution_json = Utils.toJson(obj, host=self.request.host)
        if (obj.admin):
            institution_json['admin'] = adminToJson(obj.admin.get())
        if (obj.invite):
            institution_json['invite'] = Institution.make(obj, ["invite"])
        institution_json['sent_invitations'] = getSentInvitations(obj.key)
        institution_json['parent_institution'] = parentToJson(obj)
        institution_json['children_institutions'] = childrenToJson(obj)
        institution_json['cover_photo'] = obj.cover_photo

        self.response.write(json.dumps(institution_json))
Exemple #31
0
def clear_data_store():
    # Clean the Datastore
    users = User.query().fetch(keys_only=True)
    ndb.delete_multi(users)

    posts = Post.query().fetch(keys_only=True)
    ndb.delete_multi(posts)

    institutions = Institution.query().fetch(keys_only=True)
    ndb.delete_multi(institutions)

    invites = Invite.query().fetch(keys_only=True)
    ndb.delete_multi(invites)

    events = Event.query().fetch(keys_only=True)
    ndb.delete_multi(events)

    index_institution = search.Index(name=INDEX_INSTITUTION)
    delete_all_in_index(index_institution)
    index_user = search.Index(name=INDEX_USER)
    delete_all_in_index(index_user)
 def POST(self, name):
     """Inserts new contact."""
     data = json.loads(web.data())
     institution_uuid = data.get('institution_uuid')
     name = data.get('contact_name')
     email_address = data.get('contact_email_address')
     notes = data.get('contact_notes')
     try:
         assert institution_uuid and name
     except AssertionError as error:
         logger.debug(error)
         raise Error(BADPARAMS)
     try:
         assert Institution.get_institution(institution_uuid)[0]
     except:
         raise Error(NOTFOUND,
                     msg="The institution provided does not exist.")
     contact_uuid = generate_uuid()
     contact = Contact(contact_uuid, institution_uuid, name, email_address,
                       notes)
     contact.save()
     return [contact.__dict__]
Exemple #33
0
def initModels(cls):
    """Init the models."""
    # new User User
    cls.user = User()
    cls.user.name = 'User'
    cls.user.email = ['*****@*****.**']
    cls.user.put()
    # new Institution SPLAB
    cls.institution = Institution()
    cls.institution.name = 'SPLAB'
    cls.institution.email = '*****@*****.**'
    cls.institution.members = [cls.user.key]
    cls.institution.followers = [cls.user.key]
    cls.institution.admin = cls.user.key
    cls.institution.state = 'active'
    cls.institution.put()
    # Survey post of User To SPLAB
    cls.user_post = SurveyPost()
    cls.user_post.author = cls.user.key
    cls.user_post.institution = cls.institution.key
    cls.user_post.type_survey = 'binary'
    cls.user_post.title = 'Survey with Multiple choice'
    cls.user_post.text = 'Description of survey'
    cls.user_post.number_votes = 0
    cls.user_post.last_modified_by = cls.user.key
    cls.user_post.deadline = datetime.datetime(2020, 07, 25, 12, 30, 15)
    cls.user_post.options = [{
        'id': 0,
        'text': 'first option',
        'number_votes': 0,
        'voters': []
    }, {
        'id': 1,
        'text': 'second option',
        'number_votes': 0,
        'voters': []
    }]
    cls.user_post.put()
Exemple #34
0
    def post(self):
        if not self.user.administrator:
            return webapp2.redirect("/")

        mode = self.request.POST["mode"]

        if mode == "0":
            # Institution
            institution = Institution(name=self.request.POST["name"], website=self.request.POST["website"])
            institution.put()
        elif mode == "1":
            thumbnail_url = self.request.POST["thumbnail"]
            try:
                content = urllib2.urlopen(thumbnail_url)
                image = content.read()
            except urllib2.HTTPError:
                logging.warning("URL: " + thumbnail_url + "was not found.")
                image = ""

            institution = ndb.Key(urlsafe=self.request.POST["institution"])

            author = Author(
                name=self.request.POST["name"],
                website=self.request.POST["website"],
                thumbnail=image,
                institution=institution,
            )
            author.put()
        elif mode == "2":
            # Conference
            conference = Conference(name=self.request.POST["name"], acronym=self.request.POST["acronym"])
            conference.put()
            pass
        elif mode == "3":
            # Publication
            date = datetime.strptime(self.request.POST["date"], "%Y-%m-%d")

            # A bit messy, does author order
            authors = self.request.params.getall("authors")
            idx = 0
            author_order = [int(order_idx) for order_idx in self.request.POST["order"].split(",")]
            ordered_authors = []
            for author_idx in range(len(authors)):
                ordered_authors.append(ndb.Key(urlsafe=authors[author_order[author_idx] - 1]))

            conference = ndb.Key(urlsafe=self.request.POST["conference"])

            pdf_image_url = self.request.POST["pdfimage"]
            image = ""
            if pdf_image_url:
                try:
                    content = urllib2.urlopen(pdf_image_url)
                    image = content.read()
                except urllib2.HTTPError:
                    logging.warning("URL: " + pdf_image_url + "was not found.")

            publication = Publication(
                title=self.request.POST["title"],
                abstract=self.request.POST["abstract"],
                date=date,
                authors=ordered_authors,
                citation=self.request.POST["citation"],
                conference=conference,
                pdf=self.request.POST["pdf"],
                pdf_image=image,
                arxiv_link=self.request.POST["arxiv"],
                project_page=self.request.POST["projectpage"],
            )
            publication.put()
        elif mode == "4":
            # Content
            content = Content(name=self.request.POST["name"], content=self.request.POST["content"])
            content.put()
        elif mode == "5":
            # Project
            authors = []
            for author in self.request.params.getall("authors"):
                authors.append(ndb.Key(urlsafe=author))

            image_url = self.request.POST["image"]
            if image_url:
                try:
                    content = urllib2.urlopen(image_url)
                    image = content.read()
                except urllib2.HTTPError:
                    logging.warning("URL: " + image_url + "was not found.")
                    image = ""
            else:
                image = ""

            publications = []
            for publication in self.request.params.getall("publications"):
                publications.append(ndb.Key(urlsafe=publication))

            contents = []
            for content in self.request.params.getall("contents"):
                contents.append(ndb.Key(urlsafe=content))

            tags = []
            for tag in self.request.POST["tags"].split(","):
                # Try to find tag.
                stripped_tag = tag.strip()
                query = Tag.query(Tag.name == stripped_tag)
                if query.count() == 1:
                    query_tag = query.get(keys_only=True)
                    tags.append(query_tag)
                elif query.count() == 0:
                    query_tag = Tag(name=stripped_tag)
                    tags.append(query_tag.put())
                else:
                    logging.error("Tag count > 1 | < 0 (%s)." % stripped_tag)

            project = Project(
                title=self.request.POST["title"],
                description=self.request.POST["description"],
                authors=authors,
                image=image,
                publications=publications,
                extra_content=contents,
                tags=tags,
            )
            project.put()
        return self.get()
Exemple #35
0
def main():
    Institution.init()