Esempio n. 1
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
Esempio n. 2
0
    def validate(self, doc, allowRename=False):
        """
        Validate the name and description of the folder, ensure that it is
        associated with a valid parent and that it has a unique name.

        :param doc: the folder document to validate.
        :param allowRename: if True and a folder or item exists with the same
                            name, rename the folder so that it is unique.
        :returns: `the validated folder document`
        """
        from girderformindlogger.models.item import Item

        doc['name'] = doc['name'].strip()
        doc['lowerName'] = doc['name'].lower()
        doc['description'] = doc['description'].strip()

        if not doc['name']:
            raise ValidationException('Folder name must not be empty.', 'name')

        if not doc['parentCollection'] in ('folder', 'user', 'collection'):
            # Internal error; this shouldn't happen
            raise GirderException('Invalid folder parent type: %s.' %
                                  doc['parentCollection'],
                                  'girderformindlogger.models.folder.invalid-parent-type')
        name = doc['name']
        # If the folder already exists with the current name, don't check.
        # Although we don't want duplicate names, they can occur when there are
        # simultaneous uploads, and also because Mongo has no guaranteed
        # multi-collection uniqueness constraints.  If this occurs, and we are
        # changing a non-name property, don't validate the name (since that may
        # fail).  If the name is being changed, validate that it is probably
        # unique.
        checkName = '_id' not in doc or not self.findOne({'_id': doc['_id'], 'name': name})
        n = 0
        itemModel = Item()
        while checkName:
            q = {
                'parentId': doc['parentId'],
                'name': name,
                'parentCollection': doc['parentCollection']
            }
            if '_id' in doc:
                q['_id'] = {'$ne': doc['_id']}
            dupFolder = self.findOne(q, fields=['_id'])
            if doc['parentCollection'] == 'folder':
                q = {
                    'folderId': doc['parentId'],
                    'name': name
                }
                dupItem = itemModel.findOne(q, fields=['_id'])
            else:
                dupItem = None
            if dupItem is None and dupFolder is None:
                doc['name'] = name
                break
            if not allowRename:
                if dupFolder:
                    raise ValidationException('A folder with that name '
                                              'already exists here.', 'name')
                raise ValidationException('An item with that name already '
                                          'exists here.', 'name')
            n += 1
            name = '%s (%d)' % (doc['name'], n)
        return doc