def decipherUser(appletSpecificId): thisUser = getCurrentUser() try: ciphered = FolderModel().load(appletSpecificId, level=AccessType.NONE, user=thisUser) userId = list(FolderModel().find( query={ 'parentId': ciphered['_id'], 'parentCollection': 'folder', 'name': 'userID' })) except: return (None) try: cUser = str(userId[0]['meta']['user']['@id']) if len(userId) and type( userId[0]) == dict and userId[0].get('meta').get('user').get( '@id') else None FolderModel().setUserAccess(doc=ciphered, user=UserModel().load(id=cUser, user=cUser), level=AccessType.READ, save=True, currentUser=thisUser, force=True) return (cUser) except: return (None)
def getContext(self): """ Get a list of folders with given search parameters. Currently accepted search modes are: 1. Searching by parentId and parentType, with optional additional filtering by the name field (exact match) or using full text search within a single parent folder. Pass a "name" parameter or "text" parameter to invoke these additional filters. 2. Searching with full text search across all folders in the system. Simply pass a "text" parameter for this mode. """ context = FolderModel().findOne({ 'name': 'JSON-LD', 'parentCollection': 'collection', 'parentId': CollectionModel().findOne({ 'name': 'Context' }).get('_id') }) if context: return (context.get('meta', {})) user = self.getCurrentUser() context = FolderModel().setMetadata( folder=FolderModel().createFolder( parent=CollectionModel().createCollection( name="Context", creator=user, public=True, reuseExisting=True ), name="JSON-LD", parentType='collection', public=True, creator=user, reuseExisting=True ), metadata={ "@context": { "@language": "en-US", "@base": rest.getApiUrl(), "reprolib": REPROLIB_CANONICAL, "http://schema.org/url": { "@type": "@id" } } } ) return (context.get('meta', {}))
def initHistoryData(self, historyFolder, referencesFolder, protocolId, user, activityIDRef={}, itemIDRef={}): from girderformindlogger.utility import jsonld_expander from girderformindlogger.models.item import Item as ItemModel activities = list(FolderModel().find( {'meta.protocolId': ObjectId(protocolId)})) items = list(ItemModel().find( {'meta.protocolId': ObjectId(protocolId)})) protocol = self.load(protocolId, force=True) schemaVersion = protocol['meta'].get('protocol', {}).get('schema:version', None) currentVersion = schemaVersion[0].get( '@value', '0.0.0') if schemaVersion else '0.0.0' activityIdToHistoryObj = {} for activity in activities: identifier = activity['meta'].get('activity', {}).get('url', None) if identifier: activityId = str(activity['_id']) if activityId in activityIDRef: activity['_id'] = activityIDRef[activityId] activityId = str(activityIDRef[activityId]) activityIdToHistoryObj[ activityId] = jsonld_expander.insertHistoryData( activity, identifier, 'activity', currentVersion, historyFolder, referencesFolder, user) for item in items: identifier = item['meta'].get('screen', {}).get('url', None) if identifier: if str(item['_id']) in itemIDRef: item['_id'] = itemIDRef[str(item['_id'])] if str(item['meta']['activityId']) in activityIDRef: item['meta']['activityId'] = activityIDRef[str( item['meta']['activityId'])] activityHistoryObj = activityIdToHistoryObj[str( item['meta']['activityId'])] item['meta'].update({ 'originalActivityId': item['meta']['activityId'], 'activityId': activityHistoryObj['_id'] }) jsonld_expander.insertHistoryData(item, identifier, 'screen', currentVersion, historyFolder, referencesFolder, user)
def getSkin(lang="en-US"): """ Function to return the context for the current instance. :param language: ISO language string, optional :type language: None :returns: context dict """ contextCollection = CollectionModel().findOne({'name': 'Context'}) skinFolder = FolderModel().findOne({ 'name': 'Skin', 'parentCollection': 'collection', 'parentId': contextCollection.get('_id') }) if contextCollection else None defaultSkin = { 'name': '', 'colors': { 'primary': '#000000', 'secondary': '#FFFFFF' }, 'about': '' } skin = skinFolder.get( 'meta', defaultSkin) if skinFolder is not None else defaultSkin for s in ['name', 'about']: lookup = jsonld_expander.getByLanguage( skin.get(s, ""), lang if lang and lang not in ["@context.@language", ""] else None) skin[s] = lookup if lookup and lookup not in [ None, [{}], ] else jsonld_expander.getByLanguage(skin[s], None) skin[s] = jsonld_expander.fileObjectToStr(skin[s][0]) if isinstance( skin[s], list) and len(skin[s]) else skin[s] return (skin)
def __init__(self): super(Activity, self).__init__() self.resourceName = 'activity' self._model = FolderModel() # TODO: self.route('PUT', (':id'), self.deactivateActivity) # TODO: self.route('PUT', ('version', ':id'), self.deactivateActivity) self.route('GET', (':id', ), self.getActivity) self.route('GET', (), self.getActivityByURL)
def selfAssignment(): thisUser = Applet().getCurrentUser() assignmentsFolder = FolderModel().createFolder(parent=thisUser, parentType='user', name='Assignments', creator=thisUser, public=False, reuseExisting=True) return ((assignmentsFolder, 'folder'))
def getUserCipher(appletAssignment, user): """ Returns an applet-specific user ID. Parameters ---------- appletAssignment: Mongo Folder cursor Applet folder in Assignments collection user: string or list applet-specific ID, canonical ID or email address Returns ------- user: string applet-specific ID """ if not isinstance(user, str): return ([getUserCipher(appletAssignment, u) for u in list(user)]) thisUser = getCurrentUser() appletAssignments = list(FolderModel().childFolders( parent=appletAssignment, parentType='folder', user=thisUser)) allCiphers = list( itertools.chain.from_iterable([ list(FolderModel().find( query={ 'parentId': assignment.get('_id'), 'parentCollection': 'folder', 'name': 'userID' })) for assignment in appletAssignments ])) if len(appletAssignments) else [] cUser = getCanonicalUser(user) aUser = [ cipher['parentId'] for cipher in allCiphers if (cipher['meta']['user']['@id'] == cUser) if cipher.get('meta') and cipher['meta'].get('user') and cipher['meta']['user'].get('@id') and cipher.get('parentId') ] if cUser and len(allCiphers) else [] aUser = aUser[0] if len(aUser) else createCipher( appletAssignment, appletAssignments, cUser if cUser is not None else user)['_id'] return (str(aUser))
def createScreen(self, activity, screenName=None): thisUser = self.getCurrentUser() activity = ActivityModel().load(activity, level=AccessType.WRITE, user=thisUser) screen = ScreenModel().createScreen( name=screenName if screenName is not None else str(len(list(FolderModel().childItems(activity))) + 1), creator=thisUser, folder=activity, reuseExisting=False) return (jsonld_expander._fixUpFormat( jsonld_expander.formatLdObject(screen, 'screen', thisUser)))
def createHistoryFolders(self, protocolId, user): protocol = self.load(protocolId, force=True) updated = False # add folder to save historical data if not protocol['meta'].get('historyId', None): historyFolder = FolderModel().createFolder(name='history of ' + protocol['name'], parent=protocol, parentType='folder', public=False, creator=user, allowRename=True, reuseExisting=False) protocol['meta']['historyId'] = historyFolder['_id'] updated = True else: historyFolder = FolderModel().load(protocol['meta']['historyId'], force=True) if not historyFolder.get('meta', {}).get('referenceId', None): referencesFolder = FolderModel().createFolder( name='reference of history data for ' + protocol['name'], parent=historyFolder, parentType='folder', public=False, creator=user, allowRename=True, reuseExisting=False, ) historyFolder = FolderModel().setMetadata( historyFolder, {'referenceId': referencesFolder['_id']}) else: referencesFolder = FolderModel().load( historyFolder['meta']['referenceId'], force=True) # add folder to save contents if not protocol['meta'].get('contentId', None): contentFolder = FolderModel().createFolder(name='content of ' + protocol['name'], parent=protocol, parentType='folder', public=False, creator=user, allowRename=True, reuseExisting=False) protocol['meta']['contentId'] = contentFolder['_id'] updated = True if updated: protocol = self.setMetadata(protocol, protocol['meta']) return (historyFolder, referencesFolder)
def __init__(self): super(Folder, self).__init__() self.resourceName = 'folder' self._model = FolderModel() self.route('DELETE', (':id',), self.deleteFolder) self.route('DELETE', (':id', 'contents'), self.deleteContents) self.route('GET', (), self.find) self.route('GET', (':id',), self.getFolder) self.route('GET', (':id', 'details'), self.getFolderDetails) self.route('GET', (':id', 'access'), self.getFolderAccess) self.route('GET', (':id', 'download'), self.downloadFolder) self.route('GET', (':id', 'rootpath'), self.rootpath) self.route('POST', (), self.createFolder) self.route('PUT', (':id',), self.updateFolder) self.route('PUT', (':id', 'access'), self.updateFolderAccess) self.route('POST', (':id', 'copy'), self.copyFolder) self.route('PUT', (':id', 'metadata'), self.setMetadata) self.route('DELETE', (':id', 'metadata'), self.deleteMetadata)
def getByLanguage(object, tag=None): """ Function to get a value or IRI by a language tag following https://tools.ietf.org/html/bcp47. :param object: The JSON-LD Object to language-parse :type object: dict or list :param tag: The language tag to use. :type tag: str :returns: str, either a literal or an IRI. """ if not tag: from girderformindlogger.api.v1.context import Context tag = FolderModel().findOne({ 'name': 'JSON-LD', 'parentCollection': 'collection', 'parentId': CollectionModel().findOne({ 'name': 'Context' }).get('_id') }) tag = tag.get('meta', {}).get('@context', {}).get('@language') if tag else None if isinstance(tag, str): tags = getMoreGeneric(tag) tags = tags + ["@{}".format(t) for t in tags] tags.sort(key=len, reverse=True) if isinstance(object, dict): return (getFromLongestMatchingKey(object, tags, caseInsensitive=True)) if isinstance(object, list): return ([ getFromLongestMatchingValue(objectList=object, listOfValues=tags, keyToMatch='@language', caseInsensitive=True) ]) if isinstance(object, str): return (object)
def authorizeReviewer(applet, reviewer, user): thisUser = Applet().getCurrentUser() user = UserModel().load(user, level=AccessType.NONE, user=thisUser) try: applet = FolderModel().load(applet, level=AccessType.READ, user=thisUser) responsesCollection = FolderModel().createFolder(parent=user, name='Responses', parentType='user', public=False, creator=thisUser, reuseExisting=True) thisApplet = list(FolderModel().childFolders( parent=responsesCollection, parentType='folder', user=thisUser, filters={'meta.applet.@id': str(applet['_id'])})) thisApplet = thisApplet[0] if len(thisApplet) else FolderModel( ).setMetadata( FolderModel().createFolder( parent=responsesCollection, name=FolderModel().preferredName(applet), parentType='folder', public=False, creator=thisUser, allowRename=True, reuseExisting=False), {'applet': { '@id': str(applet['_id']) }}) accessList = thisApplet['access'] accessList['users'].append({"id": reviewer, "level": AccessType.READ}) thisApplet = FolderModel().setAccessList(thisApplet, accessList, save=True, recurse=True, user=thisUser) except: thisApplet = None return (thisApplet)
def _invite(applet, user, role, rsvp, subject): """ Helper function to invite a user to an applet. :param applet: Applet to invite user to :type applet: AppletModel :param user: ID (canonical or applet-specific) or email address of user to invite :type user: string :param role: Role to invite user to :type role: string :param rsvp: Require user acceptance? :type rsvp: boolean :param subject: Subject about 'user' role can inform or about which 'reviewer' role can review :type subject: string or literal :returns: New assignment (dictionary) """ if role not in USER_ROLE_KEYS: raise ValidationException('Invalid role.', 'role') thisUser = Applet().getCurrentUser() user = user if user else str(thisUser['_id']) if mail_utils.validateEmailAddress(user): user = UserModel().hash(user) if bool(rsvp): groupName = {'title': '{} {}s'.format(str(applet.get('_id')), role)} groupName['lower'] = groupName.get('title', '').lower() group = GroupModel().findOne(query={'lowerName': groupName['lower']}) if not group or group is None: group = GroupModel().createGroup( name=groupName['title'], creator=thisUser, public=bool(role in ['manager', 'reviewer'])) try: assignments = CollectionModel().createCollection(name="Assignments", public=True, reuseExisting=True) assignmentType = 'collection' except AccessException: assignments, assignmentType = selfAssignment() appletAssignment = list(FolderModel().childFolders( parent=assignments, parentType=assignmentType, user=thisUser, filters={ 'meta.applet.@id': str(applet['_id']) if '_id' in applet else None })) appletAssignment = appletAssignment[0] if len( appletAssignment) else FolderModel().setMetadata( FolderModel().createFolder( parent=assignments, name=FolderModel().preferredName(applet), parentType=assignmentType, public=False, creator=thisUser, allowRename=True, reuseExisting=False), { 'applet': { '@id': str(applet['_id']) if '_id' in applet else None } }) meta = appletAssignment.get('meta', {}) members = meta.get('members', []) if meta.get('members') is not None else [] cUser = getUserCipher(appletAssignment, user) subject = subject.upper() if subject is not None and subject.upper( ) in SPECIAL_SUBJECTS else getUserCipher( appletAssignment, str(thisUser['_id']) if subject is None else subject) thisAppletAssignment = { '@id': str(cUser), 'roles': { role: True if role not in ['reviewer', 'user'] else [subject] } } for i, u in enumerate(members): if '@id' in u and u["@id"] == str(cUser): thisAppletAssignment = members.pop(i) if 'roles' not in thisAppletAssignment: thisAppletAssignment['roles'] = {} thisAppletAssignment['roles'][role] = True if role not in [ 'reviewer', 'user' ] else [subject] if (subject in SPECIAL_SUBJECTS) or ( 'reviewer' not in thisAppletAssignment['roles']) else list( set(thisAppletAssignment['roles']['reviewer'] + [subject]).difference(set(SPECIAL_SUBJECTS)) ) if "ALL" not in thisAppletAssignment['roles'][ 'reviewer'] else ["ALL"] members.append(thisAppletAssignment) meta['members'] = members appletAssignment = FolderModel().setMetadata(appletAssignment, meta) authorizeReviewers(appletAssignment) return (appletAssignment)
def load(self, id, level=AccessType.ADMIN, user=None, objectId=True, force=False, fields=None, exc=False): """ We override load in order to ensure the folder has certain fields within it, and if not, we add them lazily at read time. Also, this method will return a specific version of an Activity if given an Activity version ID or the latest version of an Activity if given an Activity ID. :param id: The id of the resource. :type id: string or ObjectId :param user: The user to check access against. :type user: dict or None :param level: The required access type for the object. :type level: AccessType :param force: If you explicitly want to circumvent access checking on this resource, set this to True. :type force: bool """ # Ensure we include extra fields to do the migration below extraFields = { 'baseParentId', 'baseParentType', 'parentId', 'parentCollection', 'name', 'lowerName' } loadFields = self._supplementFields(fields, extraFields) doc = super(FolderModel, self).load(id=id, level=level, user=user, objectId=objectId, force=force, fields=loadFields, exc=exc) if doc is not None: pathFromRoot = FolderModel().parentsToRoot(doc, user=user, force=True) if 'baseParentType' not in doc: baseParent = pathFromRoot[0] doc['baseParentId'] = baseParent['object']['_id'] doc['baseParentType'] = baseParent['type'] self.update({'_id': doc['_id']}, { '$set': { 'baseParentId': doc['baseParentId'], 'baseParentType': doc['baseParentType'] } }) if 'lowerName' not in doc: doc['lowerName'] = doc['name'].lower() self.update({'_id': doc['_id']}, {'$set': { 'lowerName': doc['lowerName'] }}) if '_modelType' not in doc: doc['_modelType'] = 'folder' self._removeSupplementalFields(doc, fields) try: parent = pathFromRoot[-1]['object'] if (parent['name'] in {"Activitysets", "Protocols"} and doc['baseParentType'] in {'collection', 'user'}): """ Check if parent is "Protocols" collection or user folder, ie, if this is a Protocol. If so, return Protocol. """ return (doc) except: raise ValidationException("Invalid Protocol ID.")
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
def loadFromSingleFile(document, user): if 'protocol' not in document or 'data' not in document['protocol']: raise ValidationException( 'should contain protocol field in the json file.', ) if 'activities' not in document['protocol']: raise ValidationException( 'should contain activities field in the json file.', ) contexts = document.get('contexts', {}) protocol = {'protocol': {}, 'activity': {}, 'screen': {}} expandedProtocol = expandObj(contexts, document['protocol']['data']) protocol['protocol'][expandedProtocol['@id']] = { 'expanded': expandedProtocol } protocolId = None for activity in document['protocol']['activities'].values(): expandedActivity = expandObj(contexts, activity['data']) protocol['activity'][expandedActivity['@id']] = { 'parentKey': 'protocol', 'parentId': expandedProtocol['@id'], 'expanded': expandedActivity } if 'items' not in activity: raise ValidationException( 'should contain at least one item in each activity.', ) for item in activity['items'].values(): expandedItem = expandObj(contexts, item) protocol['screen'][expandedItem['@id']] = { 'parentKey': 'activity', 'parentId': expandedActivity['@id'], 'expanded': expandedItem } for modelType in ['protocol', 'activity', 'screen']: modelClass = MODELS()[modelType]() docCollection = getModelCollection(modelType) for model in protocol[modelType].values(): prefName = modelClass.preferredName(model['expanded']) if modelClass.name in ['folder', 'item']: docFolder = FolderModel().createFolder( name=prefName, parent=docCollection, parentType='collection', public=True, creator=user, allowRename=True, reuseExisting=(modelType != 'applet')) metadata = {modelType: model['expanded']} tmp = model while tmp.get('parentId', None): key = tmp['parentKey'] tmp = protocol[key][tmp['parentId']] metadata['{}Id'.format(key)] = '{}/{}'.format( MODELS()[key]().name, tmp['_id']) if modelClass.name == 'folder': newModel = modelClass.setMetadata(docFolder, metadata) elif modelClass.name == 'item': newModel = modelClass.setMetadata( modelClass.createItem( name=prefName if prefName else str( len( list(FolderModel().childItems( FolderModel().load(docFolder, level=None, user=user, force=True)))) + 1), creator=user, folder=docFolder, reuseExisting=True), metadata) # we don't need this in the future because we will only using single-file-format modelClass.update({'_id': newModel['_id']}, {'$set': { 'loadedFromSingleFile': True }}) if modelType != 'protocol': formatted = _fixUpFormat( formatLdObject(newModel, mesoPrefix=modelType, user=user, refreshCache=False)) createCache(newModel, formatted, modelType, user) model['_id'] = newModel['_id'] if modelType == 'protocol': protocolId = newModel['_id'] return formatLdObject(ProtocolModel().load(protocolId, force=True), mesoPrefix='protocol', user=user, refreshCache=False)
def createCipher(applet, appletAssignments, user): thisUser = getCurrentUser() cUser = None try: cUser = UserModel().load(user, level=AccessType.NONE, user=thisUser) except: cur_config = config.getConfig() if not re.match(cur_config['users']['email_regex'], user): raise ValidationException('Invalid email address.', 'user') newCipher = FolderModel().createFolder(parent=applet, name=nextCipher(appletAssignments), parentType='folder', public=False, creator=thisUser, reuseExisting=True) if cUser is None: try: appletName = FolderModel().preferredName(FolderModel().load( applet['meta']['applet']['@id'], level=AccessType.NONE, user=thisUser)['name']) except: raise ValidationException('Invalid assignment folder.', 'applet') try: cUser = UserModel().createUser(login="******".join( [appletName.replace(' ', ''), str(newCipher['name'])]), password=str(uuid.uuid4()), firstName=appletName, email=user, admin=False, public=False, currentUser=thisUser) except: cUser = UserModel().createUser(login="******".join([ appletName.replace(' ', ''), str(applet['meta']['applet']['@id']), str(FolderModel().preferredName(newCipher)) ]), password=str(uuid.uuid4()), firstName=appletName, email=user, admin=False, public=False, currentUser=thisUser) newSecretCipher = FolderModel().setMetadata( FolderModel().createFolder(parent=newCipher, name='userID', parentType='folder', public=False, creator=thisUser, reuseExisting=True), {'user': { '@id': str(cUser['_id']) }}) FolderModel().setAccessList(doc=newSecretCipher, access={ 'users': [], 'groups': [] }, save=True, user=thisUser, force=True) for u in [thisUser, cUser]: FolderModel().setUserAccess(doc=newSecretCipher, user=u, level=None, save=True, currentUser=thisUser, force=True) for u in [thisUser, cUser]: FolderModel().setUserAccess(doc=newSecretCipher, user=u, level=AccessType.READ, save=True, currentUser=thisUser, force=True) return (newCipher)
def importAndCompareModelType(model, url, user, modelType): import threading from girderformindlogger.utility import firstLower if model is None: return (None, None) mt = model.get('@type', '') mt = mt[0] if isinstance(mt, list) else mt atType = mt.split('/')[-1].split(':')[-1] modelType = firstLower(atType) if len(atType) else modelType modelType = 'screen' if modelType.lower( ) == 'field' else 'protocol' if modelType.lower( ) == 'activityset' else modelType changedModel = ((atType != modelType and len(atType)) or (" " in modelType)) modelType = firstLower(atType) if changedModel else modelType modelType = 'screen' if modelType.lower( ) == 'field' else 'protocol' if modelType.lower( ) == 'activityset' else modelType modelClass = MODELS()[modelType]() prefName = modelClass.preferredName(model) cachedDocObj = {} model = expand(url) print("Loaded {}".format(": ".join([modelType, prefName]))) docCollection = getModelCollection(modelType) if modelClass.name in ['folder', 'item']: docFolder = FolderModel().createFolder( name=prefName, parent=docCollection, parentType='collection', public=True, creator=user, allowRename=True, reuseExisting=(modelType != 'applet')) if modelClass.name == 'folder': newModel = modelClass.setMetadata( docFolder, {modelType: { **model, 'schema:url': url, 'url': url }}) elif modelClass.name == 'item': newModel = modelClass.setMetadata( modelClass.createItem(name=prefName if prefName else str( len( list(FolderModel().childItems(FolderModel().load( docFolder, level=None, user=user, force=True)))) + 1), creator=user, folder=docFolder, reuseExisting=True), {modelType: { **model, 'schema:url': url, 'url': url }}) formatted = _fixUpFormat( formatLdObject(newModel, mesoPrefix=modelType, user=user, refreshCache=True)) createCache(newModel, formatted, modelType, user) return (formatted, modelType)
def cycleModels(IRIset, modelType=None, meta={}): from girderformindlogger.constants import HIERARCHY, REPROLIB_TYPES from girderformindlogger.models.folder import Folder as FolderModel from girderformindlogger.models.item import Item as ItemModel from girderformindlogger.utility.jsonld_expander import reprolibCanonize cachedDoc = None primary = [modelType] if isinstance( modelType, str) else [] if modelType is None else modelType secondary = [m for m in HIERARCHY if m not in primary] del modelType if len(primary): query = { '$and': [ { # search by type '$or': [{ 'meta.{}.@type'.format(modelType): { "$in": [ t for t in [ reprolibCanonize(REPROLIB_TYPES[modelType] ), 'reproschema:{}'. format(suffix), 'reprolib:{}'.format( suffix), 'reprolib:schemas/{}'.format( suffix), suffix ] if t is not None ] for suffix in [REPROLIB_TYPES[modelType].split('/')[-1]] } } for modelType in primary if modelType in REPROLIB_TYPES] }, { # search by url '$or': [{ 'meta.{}.url'.format(modelType): { '$in': list(IRIset) } } for modelType in primary if modelType in REPROLIB_TYPES] }, *[{ 'meta.{}'.format(key): meta[key] } for key in meta] ] } cachedDoc = (FolderModel() if not any(['screen' in primary, 'item' in primary]) else ItemModel()).findOne(query) if cachedDoc is None: query = { '$and': [{ '$or': [{ 'meta.{}.@type'.format(modelType): { "$in": [ t for t in [ reprolibCanonize(REPROLIB_TYPES[modelType]), 'reproschema:{}'.format( suffix), 'reprolib:{}'.format(suffix), 'reprolib:schemas/{}'.format(suffix), suffix ] if t is not None ] for suffix in [REPROLIB_TYPES[modelType].split('/')[-1]] } } for modelType in secondary if modelType in REPROLIB_TYPES] }, { '$or': [{ 'meta.{}.url'.format(modelType): { '$in': list(IRIset) } } for modelType in secondary if modelType in REPROLIB_TYPES] }, *[{ 'meta.{}'.format(key): meta[key] } for key in meta]] } cachedDoc = FolderModel().findOne(query) if cachedDoc is None: cachedDoc = ItemModel().findOne(query) if cachedDoc is None: return (None, None) modelType = [ rt for rt in list(REPROLIB_TYPES.keys()) if '@type' in cachedDoc.get('meta', {}).get(rt, {}) ] modelType = modelType[0] if len(modelType) else None print("Found {}/{}".format(modelType, str(cachedDoc['_id']))) return (modelType, cachedDoc)
def __init__(self): super(Context, self).__init__() self.resourceName = 'context' self._model = FolderModel() self.route('GET', (), self.getContext) self.route('GET', ('skin',), self.getSkin)