示例#1
0
 def __init__(self):
     super(ResponseItem, self).__init__()
     self.resourceName = 'response'
     self._model = ResponseItemModel()
     self.route('GET', (), self.getResponses)
     self.route('GET', ('last7Days', ':applet'), self.getLast7Days)
     self.route('POST', (':applet', ':activity'), self.createResponseItem)
def getDataForApplet(user, appletObject):
    """
    get the data for an applet (as a manager or reviewer)

    inputs
    ------
    user: admin user object
    appletObject: appletObject
    """
    currentUser = authenticate(user)
    appletId = appletObject['_id']
    appletInfo = AppletModel().findOne({'_id': appletId})
    reviewerGroupOfApplet = appletInfo['roles']['reviewer']['groups']
    assert len(reviewerGroupOfApplet) == 1, \
    'there should be only 1 group for an applet, for now.'
    reviewerGroupOfApplet = reviewerGroupOfApplet[0]['id']
    isAReviewer = list(
        filter(lambda x: x == reviewerGroupOfApplet, currentUser['groups']))
    assert len(isAReviewer) == 1, 'the current user is not a reviewer'
    props = {
        "applet": [
            list(
                itertools.chain.from_iterable([
                    string_or_ObjectID(s) for s in listFromString(appletId)
                ])), "meta.applet.@id"
        ]
    }
    q = {
        props[prop][1]: {
            "$in": props[prop][0]
        }
        for prop in props if len(props[prop][0])
    }
    allResponses = list(ResponseItemModel().find(query=q,
                                                 user=currentUser,
                                                 sort=[("created", DESCENDING)
                                                       ]))
    outputResponse = [
        formatResponse(response)['thisResponse'] for response in allResponses
    ]
    formattedOutputResponse = []

    for response in outputResponse:
        tmp = {
            'schema:startDate': response['schema:startDate'],
            'schema:endDate': response['schema:endDate'],
            'userId': response['userId'],
        }
        for key, value in response['responses'].items():
            tmp['itemURI'] = jsonld_expander.reprolibPrefix(key)
            tmp['value'] = value
            formattedOutputResponse.append(tmp)

    return formattedOutputResponse
示例#3
0
    def getResponses(
        self,
        informant=[],
        subject=[],
        applet=[],
        # activity=[],
        # screen=[]
    ):
        assert applet,  'you need to specify an applet'

        # grab the current user
        reviewer = self.getCurrentUser()

        # check that they are a reviewer for the applet.

        # get the applet information
        appletInfo = AppletModel().findOne({'_id': ObjectId(applet)})

        # TODO: for now, an applet only has one group
        reviewerGroupOfApplet = appletInfo['roles']['reviewer']['groups']

        assert len(reviewerGroupOfApplet) == 1, 'there should be only 1 group for an applet, for now.'
        reviewerGroupOfApplet = reviewerGroupOfApplet[0]['id']


        # check that the current user's userId is in the list of reveiwersOfApplet
        isAReviewer = list(filter(lambda x: x == reviewerGroupOfApplet, reviewer['groups']))

        # TODO: for now, if the user is not a reviewer, then fail.
        assert len(isAReviewer) == 1, 'the current user is not a reviewer'


        # Build a query to get all the data.
        # TODO: enable the query to filter by subjects, informants, and activities.

        props = {
            # "informant": [
            #     list(itertools.chain.from_iterable(
            #         [string_or_ObjectID(s) for s in listFromString(informant)]
            #     )),
            #     "baseParentId"
            # ],
            # "subject": [
            #     list(itertools.chain.from_iterable(
            #         [string_or_ObjectID(s) for s in listFromString(subject)]
            #     )),
            #     "meta.subject.@id"
            # ],
            "applet": [
                list(itertools.chain.from_iterable(
                    [string_or_ObjectID(s) for s in listFromString(applet)]
                )),
                "meta.applet.@id"
            ],
            # "activity": [
            # list(itertools.chain.from_iterable(
            #         [string_or_ObjectID(s) for s in listFromString(activity)]
            #     )),
            #     "meta.activity.@id"
            # ] # TODO: Add screen
        }

        # if not(len(props["informant"][0])):
        #     props["informant"][0] = [reviewer.get('_id')] # TODO: allow getting all available

        q = {
            props[prop][1]: {
                "$in": props[prop][0]
            } for prop in props if len(
                props[prop][0]
            )
        }

        allResponses = list(ResponseItemModel().find(
            query=q,
            user=reviewer,
            sort=[("created", DESCENDING)]
        ))

        # TODO: for now, an applet only has one group
        # get the manager group and make sure there is just 1:
        managerGroupOfApplet = appletInfo['roles']['manager']['groups']
        assert len(managerGroupOfApplet) == 1, 'there should be only 1 group '
        'for an applet, for now.'
        managerGroupOfApplet = managerGroupOfApplet[0]['id']

        # check to see if the current user is a manager too.
        isAManager = len(list(filter(
            lambda x: x == managerGroupOfApplet,
            reviewer['groups']
        )))

        # Format the output response.
        # else, get the userCipher and use that for the userId.
        outputResponse = []
        for response in allResponses:
            userId = response['baseParentId']

            # encode the userId below:
            # TODO: create a user cipher, which is the hash of
            # an appletid concatenated with the user id
            appletIdUserId = applet + str(userId)
            # hash it:
            hash_object = hashlib.md5(appletIdUserId.encode())
            encodedId = hash_object.hexdigest()

            # format the response and add the userId
            formattedResponse = formatResponse(response)['thisResponse']
            formattedResponse['userId'] = encodedId
            outputResponse.append(formattedResponse)

        # lets format the output response in tidy format.
        # a list of objects, with columns:
        # ['itemURI', 'value', 'userId', 'schema:startDate', 'schema:endDate']

        formattedOutputResponse = []

        for response in outputResponse:
            tmp = {
                'schema:startDate': response['schema:startDate'],
                'schema:endDate': response['schema:endDate'],
                'userId': response['userId'],
            }
            for key, value in response['responses'].items():
                tmp['itemURI'] = key
                tmp['value'] = value
                formattedOutputResponse.append(tmp)

        return formattedOutputResponse
def postResponse(user, actURI, itemURI, appletObject, password="******"):
    """

    post a response as a user

    inputs
    ------
    user: user object
    actURI: activity uri
    itemURI: item URI
    appletObject: appletObject
    password (optional): defaults to password
    """
    currentUser = authenticate(user, password)
    appletId = appletObject['_id']

    expandedApplet = jsonld_expander.formatLdObject(appletObject, 'applet',
                                                    currentUser)

    a = expandedApplet['activities'][jsonld_expander.reprolibPrefix(actURI)]
    activityId = a['_id'].split('/')[1]

    response = {}
    response[jsonld_expander.reprolibPrefix(itemURI)] = np.random.randint(2)
    metadata = {
        'responses': response,
        'subject': {
            '@id': currentUser.get('_id')
        }
    }
    applet = appletObject
    activity = ActivityModel().load(activityId,
                                    user=currentUser,
                                    level=AccessType.READ)
    if activity is None:
        activity = ActivityModel().getFromUrl(actURI,
                                              modelType='activity',
                                              user=currentUser)[0]
    metadata['applet'] = {
        "@id":
        applet.get('_id'),
        "name":
        AppletModel().preferredName(applet),
        "url":
        applet.get('url',
                   applet.get('meta', {}).get('applet', {}).get('url'))
    }
    metadata['activity'] = {
        "@id":
        activity.get('_id'),
        "name":
        ActivityModel().preferredName(activity),
        "url":
        activity.get('url',
                     activity.get('meta', {}).get('activity', {}).get('url'))
    }
    now = datetime.now(tzlocal.get_localzone())
    appletName = metadata['applet']['name']
    UserResponsesFolder = ResponseFolderModel().load(user=currentUser,
                                                     reviewer=currentUser,
                                                     force=True)
    UserAppletResponsesFolder = Folder().createFolder(
        parent=UserResponsesFolder,
        parentType='folder',
        name=appletName,
        reuseExisting=True,
        public=False)
    AppletSubjectResponsesFolder = Folder().createFolder(
        parent=UserAppletResponsesFolder,
        parentType='folder',
        name=str(currentUser['_id']),
        reuseExisting=True,
        public=False)
    resp = ResponseItemModel().createResponseItem(
        folder=AppletSubjectResponsesFolder,
        name=now.strftime("%Y-%m-%d-%H-%M-%S-%Z"),
        creator=currentUser,
        description="{} response on {} at {}".format(
            metadata['activity']['name'], now.strftime("%Y-%m-%d"),
            now.strftime("%H:%M:%S %Z")),
        reuseExisting=False)
    resp = ResponseItemModel().setMetadata(resp, metadata)
    assert resp['_id'], 'response is weird and does not have an id'
    assert 'activity' in resp['meta'].keys(
    ), 'response does not have an activity'
    assert 'applet' in resp['meta'].keys(), 'response does not have an applet'
    assert 'responses' in resp['meta'].keys(
    ), 'response does not have an response'
    return resp