Пример #1
0
def addApplet(new_user, protocolUrl):
    """
    adds an applet for the user, where the user becomes a manager for it.

    inputs
    ------

    new_user: a user oject (from testCreateUser)
    protocolURL: String, a valid URL to an activity set.

    returns
    -------
    applet response object

    """

    currentUser = authenticate(new_user)

    # TODO: create an activity-set that JUST for testing.
    # make sure it has all the weird qualities that can break

    userAppletsToStart = AppletModel().getAppletsForUser('manager',
                                                         currentUser,
                                                         active=True)

    userApplets = userAppletsToStart.copy()

    # for now, lets do the mindlogger demo
    protocol = ProtocolModel().getFromUrl(protocolUrl, 'protocol',
                                          currentUser)[0]
    randomAS = np.random.randint(1000000)
    ar = AppletModel().createAppletFromUrl(
        name="testProtocol{}".format(randomAS),
        protocolUrl=protocolUrl,
        user=currentUser,
        sendEmail=False)

    while len(userApplets) == len(userAppletsToStart):
        nightyNight(sleepInterval)
        userApplets = AppletModel().getAppletsForUser('manager',
                                                      currentUser,
                                                      active=True)

    ar = jsonld_expander.loadCache(userApplets[-1]['cached'])

    assert jsonld_expander.reprolibCanonize(
        ar['protocol']['url']
    ) == jsonld_expander.reprolibCanonize(protocolUrl), \
        'the URLS do not match! {} {}'.format(
            ar['protocol']['url'],
            protocolUrl
        )

    assert ar['applet']['_id'], 'there is no ID!'

    assert getAppletById(new_user,
                         ar) is not None, 'something wrong with getAppletById'
    return ar
Пример #2
0
 def unexpanded(self, applet):
     from girderformindlogger.utility.jsonld_expander import loadCache
     return ({
         **(loadCache(applet.get('cached', {})).get('applet') if isinstance(
                applet, dict) and 'cached' in applet else {
                '_id': "applet/{}".format(str(applet.get('_id'))),
                **applet.get('meta', {}).get('applet', {})
            })
     })
Пример #3
0
def smartImport(IRI, user=None, refreshCache=False, modelType=None):
    from girderformindlogger.constants import MODELS
    from girderformindlogger.utility.jsonld_expander import loadCache,         \
        reprolibCanonize

    MODELS = MODELS()
    mt1 = "screen" if modelType in [None, "external JSON-LD document"
                                    ] else modelType
    model, modelType = MODELS[mt1]().getFromUrl(IRI,
                                                user=user,
                                                refreshCache=refreshCache,
                                                thread=False)
    return ((modelType, loadCache(model.get('cached',
                                            model)), reprolibCanonize(IRI)))
Пример #4
0
 def getGroupInvites(self):
     pending = self.getCurrentUser().get("groupInvites")
     output = []
     userfields = ['firstName', '_id', 'email', 'gravatar_baseUrl', 'login']
     for p in pending:
         groupId = p.get('groupId')
         applets = list(AppletModel().find(
             query={"roles.user.groups.id": groupId},
             fields=[
                 'cached.applet.skos:prefLabel',
                 'cached.applet.schema:description',
                 'cached.applet.schema:image', 'roles'
             ]))
         for applet in applets:
             for role in ['manager', 'reviewer']:
                 applet[''.join([role, 's'])] = [{
                     ('image' if userKey == 'gravatar_baseUrl' else
                      userKey): user.get(userKey)
                     for userKey in user.keys()
                 } for user in list(UserModel().find(query={
                     "groups": {
                         "$in": [
                             group.get('id')
                             for group in applet.get('roles', {}).get(
                                 role, {}).get('groups', [])
                         ]
                     }
                 },
                                                     fields=userfields))]
             appletC = jsonld_expander.loadCache(
                 applet.get('cached')) if 'cached' in applet else applet
             output.append({
                 '_id':
                 groupId,
                 'applets': [{
                     'name':
                     appletC.get('applet', {}).get('skos:prefLabel', ''),
                     'image':
                     appletC.get('applet', {}).get('schema:image', ''),
                     'description':
                     appletC.get('applet', {}).get('schema:description',
                                                   ''),
                     'managers':
                     applet.get('managers'),
                     'reviewers':
                     applet.get('reviewers')
                 } for applet in applets]
             })
     return (output)
Пример #5
0
    def updateRelationship(self, applet, relationship):
        """
        :param applet: Applet to update
        :type applet: dict
        :param relationship: Relationship to apply
        :type relationship: str
        :returns: updated Applet
        """
        from bson.json_util import dumps
        from girderformindlogger.utility.jsonld_expander import loadCache

        if not isinstance(relationship, str):
            raise TypeError("Applet relationship must be defined as a string.")
        if 'meta' not in applet:
            applet['meta'] = {'applet': {}}
        if 'applet' not in applet['meta']:
            applet['meta']['applet'] = {}
        applet['meta']['applet']['informantRelationship'] = relationship
        if 'cached' in applet:
            applet['cached'] = loadCache(applet['cached'])
        if 'applet' in applet['cached']:
            applet['cached']['applet']['informantRelationship'] = relationship
        applet['cached'] = dumps(applet['cached'])
        return (self.save(applet, validate=False))
Пример #6
0
    def getHistoryDataFromItemIRIs(self, protocolId, IRIGroup):
        from girderformindlogger.models.item import Item as ItemModel
        from girderformindlogger.utility import jsonld_expander

        protocol = self.load(protocolId, force=True)

        items = {}
        activities = {}
        itemReferences = {}
        result = {
            'items': items,
            'activities': activities,
            'itemReferences': itemReferences
        }

        if 'historyId' not in protocol.get('meta', {}):
            return result

        historyFolder = FolderModel().load(protocol['meta']['historyId'],
                                           force=True)
        if 'referenceId' not in historyFolder.get('meta', {}):
            return result

        referencesFolder = FolderModel().load(
            historyFolder['meta']['referenceId'], force=True)
        itemModel = ItemModel()

        for IRI in IRIGroup:
            reference = itemModel.findOne({
                'folderId': referencesFolder['_id'],
                'meta.identifier': IRI
            })
            if not reference:
                continue

            history = reference['meta']['history']

            for version in IRIGroup[IRI]:
                if version not in itemReferences:
                    itemReferences[version] = {}

                inserted = False
                for i in range(0, len(history)):
                    if self.compareVersions(version,
                                            history[i]['version']) <= 0:
                        if not history[i].get('reference', None):
                            continue

                        if history[i]['reference'] not in items:
                            (modelType,
                             referenceId) = history[i]['reference'].split('/')
                            model = MODELS()[modelType]().findOne(
                                {'_id': ObjectId(referenceId)})
                            items[history[i]
                                  ['reference']] = jsonld_expander.loadCache(
                                      model['cached'])

                            activityId = str(model['meta']['activityId'])

                            if activityId not in activities:
                                activities[
                                    activityId] = jsonld_expander.loadCache(
                                        FolderModel().load(
                                            activityId, force=True)['cached'])
                        if history[i]['reference']:
                            itemReferences[version][IRI] = history[i][
                                'reference']
                        inserted = True

                        break

                if not inserted:
                    itemReferences[version][
                        IRI] = None  # this is same as latest version

        return result