def __call__(self): """ Accepts GET parameters of: name: Name of the vocabulary field: Name of the field the vocabulary is being retrieved for query: string or json object of criteria and options. json value consists of a structure: { criteria: object, sort_on: index, sort_order: (asc|reversed) } attributes: comma seperated, or json object list batch: { page: 1-based page of results, size: size of paged results } """ context = self.get_context() self.request.response.setHeader("Content-type", "application/json") try: vocabulary = self.get_vocabulary() except VocabLookupException, e: return json_dumps({'error': e.message})
def __call__(self): body = json.loads(self.request.get('BODY')) url = body.get('url') fileType = body.get('fileType') fileTitle = body.get('fileTitle') folderUID = body.get('folderUID') if not url or not fileType or not fileTitle: raise BadRequest( u'Required url or fileType or fileTitle parameters not found.') if not folderUID: portal_url = getToolByName(self.context, "portal_url") folder = portal_url.getPortalObject() else: folder = uuidToObject(folderUID) if not getSecurityManager().checkPermission(AddPortalContent, folder): response = self.request.RESPONSE response.setStatus(403) return "You are not authorized to add content to this folder." fileName = fileUtils.getCorrectFileName(fileTitle + "." + fileType) contentType = mimetypes.guess_type(fileName)[0] or '' data = urlopen(url).read() factory = IDXFileFactory(folder) file = factory(fileName, contentType, data) self.request.response.setHeader("Content-Type", "application/json; charset=utf-8") return json_dumps({"status": "success", "fileName": fileName})
def __call__(self): factories_menu = getUtility(IBrowserMenu, name='plone_contentmenu_factory', context=self.context).getMenuItems( self.context, self.request) factories = [] for item in factories_menu: if item.get('title') == 'folder_add_settings': continue title = item.get('title', '') factories.append({ 'id': item.get('id'), 'title': title and translate(title, context=self.request) or '', # noqa 'action': item.get('action') }) context = aq_inner(self.context) crumbs = [] top_site = get_top_site_from_url(self.context, self.request) while not context == top_site: crumbs.append({ 'id': context.getId(), 'title': utils.pretty_title_or_id(context, context) }) context = utils.parent(context) catalog = getToolByName(self.context, 'portal_catalog') try: brains = catalog(UID=IUUID(self.context)) except TypeError: brains = [] item = None if len(brains) > 0: obj = brains[0] # context here should be site root base_path = '/'.join(context.getPhysicalPath()) item = {} for attr in self.attributes: key = attr if key == 'path': attr = 'getPath' val = getattr(obj, attr, None) if callable(val): val = val() if key == 'path': val = val[len(base_path):] item[key] = val self.request.response.setHeader('Content-Type', 'application/json; charset=utf-8') return json_dumps({ 'addButtons': factories, 'defaultPage': self.context.getDefaultPage(), 'breadcrumbs': [c for c in reversed(crumbs)], 'object': item })
def __call__(self): factories_menu = getUtility( IBrowserMenu, name='plone_contentmenu_factory', context=self.context).getMenuItems(self.context, self.request) factories = [] for item in factories_menu: if item.get('title') == 'folder_add_settings': continue title = item.get('title', '') factories.append({ 'id': item.get('id'), 'title': title and translate(title, context=self.request) or '', # noqa 'action': item.get('action') }) context = aq_inner(self.context) crumbs = [] top_site = get_top_site_from_url(self.context, self.request) while not context == top_site: crumbs.append({ 'id': context.getId(), 'title': utils.pretty_title_or_id(context, context) }) context = utils.parent(context) catalog = getToolByName(self.context, 'portal_catalog') try: brains = catalog(UID=IUUID(self.context)) except TypeError: brains = [] item = None if len(brains) > 0: obj = brains[0] # context here should be site root base_path = '/'.join(context.getPhysicalPath()) item = {} for attr in self.attributes: key = attr if key == 'path': attr = 'getPath' val = getattr(obj, attr, None) if callable(val): val = val() if key == 'path': val = val[len(base_path):] item[key] = val self.request.response.setHeader( 'Content-Type', 'application/json; charset=utf-8' ) return json_dumps({ 'addButtons': factories, 'defaultPage': self.context.getDefaultPage(), 'breadcrumbs': [c for c in reversed(crumbs)], 'object': item })
def __call__(self): site = getSite() base_url = site.absolute_url() base_vocabulary = '%s/@@getVocabulary?name=' % base_url site_path = site.getPhysicalPath() context_path = self.context.getPhysicalPath() options = { 'vocabularyUrl': '%splone.app.vocabularies.Catalog' % ( base_vocabulary), 'urlStructure': { 'base': base_url, 'appended': '/folder_contents' }, 'moveUrl': '%s{path}/fc-itemOrder' % base_url, 'indexOptionsUrl': '%s/@@qsOptions' % base_url, 'contextInfoUrl': '%s{path}/@@fc-contextInfo' % base_url, 'setDefaultPageUrl': '%s{path}/@@fc-setDefaultPage' % base_url, 'availableColumns': { 'id': translate(_('ID'), context=self.request), 'preview': translate(_('Preview'), context=self.request), 'ModificationDate': translate(_('Last modified'), context=self.request), # noqa 'EffectiveDate': translate(_('Publication date'), context=self.request), # noqa 'CreationDate': translate(_('Created on'), context=self.request), # noqa 'review_state': translate(_('Review state'), context=self.request), # noqa 'Subject': translate(_('Tags'), context=self.request), 'Type': translate(_('Type'), context=self.request), 'is_folderish': translate(_('Folder'), context=self.request), 'exclude_from_nav': translate(_('Excluded from navigation'), context=self.request), # noqa 'getObjSize': translate(_('Object Size'), context=self.request), # noqa 'last_comment_date': translate(_('Last comment date'), context=self.request), # noqa 'total_comments': translate(_('Total comments'), context=self.request), # noqa }, 'buttons': self.get_actions(), 'rearrange': { 'properties': { 'id': translate(_('Id'), context=self.request), 'sortable_title': translate(_('Title'), context=self.request), # noqa 'modified': translate(_('Last modified'), context=self.request), # noqa 'created': translate(_('Created on'), context=self.request), # noqa 'effective': translate(_('Publication date'), context=self.request), # noqa 'Type': translate(_('Type'), context=self.request) }, 'url': '%s{path}/@@fc-rearrange' % base_url }, 'basePath': '/' + '/'.join(context_path[len(site_path):]), 'upload': { 'relativePath': 'fileUpload', 'baseUrl': base_url, 'initialFolder': IUUID(self.context, None), 'useTus': TUS_ENABLED } } self.options = json_dumps(options) return super(FolderContentsView, self).__call__()
def __call__(self): factories_menu = getUtility(IBrowserMenu, name="plone_contentmenu_factory", context=self.context).getMenuItems( self.context, self.request ) factories = [] for item in factories_menu: if item.get("title") == "folder_add_settings": continue title = item.get("title", "") factories.append( { "id": item.get("id"), "title": title and translate(title, context=self.request) or "", "action": item.get("action"), } ) context = aq_inner(self.context) crumbs = [] while not IPloneSiteRoot.providedBy(context): crumbs.append({"id": context.getId(), "title": utils.pretty_title_or_id(context, context)}) context = utils.parent(context) catalog = getToolByName(self.context, "portal_catalog") try: brains = catalog(UID=IUUID(self.context)) except TypeError: brains = [] item = None if len(brains) > 0: obj = brains[0] # context here should be site root base_path = "/".join(context.getPhysicalPath()) item = {} for attr in self.attributes: key = attr if key == "path": attr = "getPath" val = getattr(obj, attr, None) if callable(val): val = val() if key == "path": val = val[len(base_path) :] item[key] = val return json_dumps( { "addButtons": factories, "defaultPage": self.context.getDefaultPage(), "breadcrumbs": [c for c in reversed(crumbs)], "object": item, } )
def get_structure_options(self): view_context = self.widget_context site = get_top_site_from_url(view_context, self.request) base_url = site.absolute_url() base_vocabulary = "%s/@@getVocabulary?name=" % base_url site_path = site.getPhysicalPath() upload_context = self.upload_context options = { "vocabularyUrl": "%splone.app.vocabularies.Catalog" % (base_vocabulary), # "attributes": { # "UID": self.get_selected_uids(), # }, "moveUrl": "%s{path}/fc-itemOrder" % base_url, "indexOptionsUrl": "%s/@@qsOptions" % base_url, "contextInfoUrl": "%s{path}/@@fc-contextInfo" % base_url, "setDefaultPageUrl": "%s{path}/@@fc-setDefaultPage" % base_url, "buttons": list(self.get_actions()), "activeColumns": [ "ModificationDate", "getObjSize", ], "activeColumnsCookie": "relatedMediaActiveColumns", "rearrange": { "properties": self.get_indexes(), "url": "%s{path}/@@fc-rearrange" % base_url, }, "basePath": "/" + "/".join( upload_context.getPhysicalPath()[len(site_path):]), # noqa "upload": { "relativePath": "fileUpload", "baseUrl": upload_context.absolute_url(), "initialFolder": IUUID(upload_context, None), "useTus": TUS_ENABLED, }, "traverseView": True, "thumb_scale": "thumb", } return json_dumps(options)
def __call__(self): """ If the 'resultsonly' parameter is in the request then extract the value for "results" from the JSON string returned from the default @@getVocabulary view, so that it can be used by pat-autosuggest. @@getVocabulary also uses the vocabulary item 'token' value for the 'id', which escapes unicode strings. For pat-autosuggest we need to use unicode for both the 'text' and the 'id'. """ vocab_json = super(PersonalizedVocabularyView, self).__call__() if vocab_json and self.request.get('resultsonly', False): vocab_obj = json_loads(vocab_json) results = vocab_obj.get('results', []) text_values = [i['text'] for i in results] vocab_list = [{'text': val, 'id': val} for val in text_values] return json_dumps(vocab_list) return vocab_json
def json(self, data): self.request.response.setHeader( 'Content-Type', 'application/json; charset=utf-8' ) return json_dumps(data)
def __call__(self): site = getSite() base_url = site.absolute_url() base_vocabulary = '%s/@@getVocabulary?name=' % base_url site_path = site.getPhysicalPath() context_path = self.context.getPhysicalPath() options = { 'vocabularyUrl': '%splone.app.vocabularies.Catalog' % (base_vocabulary), 'tagsVocabularyUrl': '%splone.app.vocabularies.Keywords' % (base_vocabulary), 'usersVocabularyUrl': '%splone.app.vocabularies.Users' % (base_vocabulary), 'urlStructure': { 'base': base_url, 'appended': '/folder_contents' }, 'moveUrl': '%s{path}/fc-itemOrder' % base_url, 'indexOptionsUrl': '%s/@@qsOptions' % base_url, 'contextInfoUrl': '%s{path}/@@fc-contextInfo' % base_url, 'setDefaultPageUrl': '%s{path}/@@fc-setDefaultPage' % base_url, 'availableColumns': { 'id': translate(_('ID'), context=self.request), 'Title': translate(_('Title'), context=self.request), 'ModificationDate': translate(_('Last modified'), context=self.request), 'EffectiveDate': translate(_('Publication date'), context=self.request), 'CreationDate': translate(_('Created on'), context=self.request), 'review_state': translate(_('Review state'), context=self.request), 'Subject': translate(_('Tags'), context=self.request), 'Type': translate(_('Type'), context=self.request), 'is_folderish': translate(_('Folder'), context=self.request), 'exclude_from_nav': translate(_('Excluded from nav'), context=self.request), 'getObjSize': translate(_('Object Size'), context=self.request), 'last_comment_date': translate(_('Last comment date'), context=self.request), 'total_comments': translate(_('Total comments'), context=self.request), }, 'buttonGroups': { 'primary': [{ 'id': 'cut', 'title': translate(_('Cut'), context=self.request), }, { 'id': 'copy', 'title': translate(_('Copy'), context=self.request), }, { 'id': 'paste', 'title': translate(_('Paste'), context=self.request), 'url': base_url + '/@@fc-paste' }, { 'id': 'delete', 'title': translate(_('Delete'), context=self.request), 'url': base_url + '/@@fc-delete', 'context': 'danger', 'icon': 'trash' }], 'secondary': [{ 'id': 'workflow', 'title': translate(_('Workflow'), context=self.request), 'url': base_url + '/@@fc-workflow' }, { 'id': 'tags', 'title': translate(_('Tags'), context=self.request), 'url': base_url + '/@@fc-tags' }, { 'id': 'properties', 'title': translate(_('Properties'), context=self.request), 'url': base_url + '/@@fc-properties' }, { 'id': 'rename', 'title': translate(_('Rename'), context=self.request), 'url': base_url + '/@@fc-rename' }] }, 'rearrange': { 'properties': { 'id': translate(_('Id'), context=self.request), 'sortable_title': translate(_('Title'), context=self.request), 'modified': translate(_('Last modified'), context=self.request), 'created': translate(_('Created on'), context=self.request), 'effective': translate(_('Publication date'), context=self.request), 'Type': translate(_('Type'), context=self.request) }, 'url': '%s{path}/@@fc-rearrange' % base_url }, 'basePath': '/' + '/'.join(context_path[len(site_path):]), 'upload': { 'relativePath': 'fileUpload', 'baseUrl': base_url, 'initialFolder': IUUID(self.context, None), 'useTus': TUS_ENABLED } } self.options = json_dumps(options) return super(FolderContentsView, self).__call__()
def json(self, data): self.request.response.setHeader("Content-Type", "application/json") return json_dumps(data)
def __call__(self): """ Accepts GET parameters of: name: Name of the vocabulary field: Name of the field the vocabulary is being retrieved for query: string or json object of criteria and options. json value consists of a structure: { criteria: object, sort_on: index, sort_order: (asc|reversed) } attributes: comma seperated, or json object list batch: { page: 1-based page of results, size: size of paged results } """ context = self.get_context() self.request.response.setHeader('Content-Type', 'application/json; charset=utf-8') try: vocabulary = self.get_vocabulary() except VocabLookupException as e: return json_dumps({'error': e.message}) results_are_brains = False if hasattr(vocabulary, 'search_catalog'): query = self.parsed_query() results = vocabulary.search_catalog(query) results_are_brains = True elif hasattr(vocabulary, 'search'): try: query = self.parsed_query()['SearchableText']['query'] except KeyError: results = iter(vocabulary) else: results = vocabulary.search(query) else: results = vocabulary try: total = len(results) except TypeError: # do not error if object does not support __len__ # we'll check again later if we can figure some size # out total = 0 # get batch batch = _parseJSON(self.request.get('batch', '')) if batch and ('size' not in batch or 'page' not in batch): batch = None # batching not providing correct options if batch: # must be slicable for batching support page = int(batch['page']) size = int(batch['size']) if size > MAX_BATCH_SIZE: raise Exception('Max batch size is 500') # page is being passed in is 1-based start = (max(page - 1, 0)) * size end = start + size # Try __getitem__-based slice, then iterator slice. # The iterator slice has to consume the iterator through # to the desired slice, but that shouldn't be the end # of the world because at some point the user will hopefully # give up scrolling and search instead. try: results = results[start:end] except TypeError: results = itertools.islice(results, start, end) # build result items items = [] attributes = _parseJSON(self.request.get('attributes', '')) if isinstance(attributes, six.string_types) and attributes: attributes = attributes.split(',') translate_ignored = self.get_translated_ignored() if attributes: base_path = self.get_base_path(context) sm = getSecurityManager() can_edit = sm.checkPermission(DEFAULT_PERMISSION_SECURE, context) mtt = getToolByName(self.context, 'mimetypes_registry') for vocab_item in results: if not results_are_brains: vocab_item = vocab_item.value item = {} for attr in attributes: key = attr if ':' in attr: key, attr = attr.split(':', 1) if attr in _unsafe_metadata and not can_edit: continue if key == 'path': attr = 'getPath' val = getattr(vocab_item, attr, None) if callable(val): if attr in _safe_callable_metadata: val = val() else: continue if key == 'path': val = val[len(base_path):] if (key not in translate_ignored and isinstance(val, six.string_types)): item[key] = translate(_(safe_unicode(val)), context=self.request) else: item[key] = val if key == 'getMimeIcon': item[key] = None # get mime type icon url from mimetype registry' contenttype = aq_base( getattr(vocab_item, 'mime_type', None)) if contenttype: ctype = mtt.lookup(contenttype) item[key] = '/'.join( [base_path, guess_icon_path(ctype[0])]) items.append(item) else: items = [{ 'id': item.value, 'text': item.title } for item in results] if total == 0: total = len(items) return json_dumps({'results': items, 'total': total})
def json(self, data): self.request.response.setHeader('Content-Type', 'application/json; charset=utf-8') return json_dumps(data)
class BaseVocabularyView(BrowserView): def __call__(self): """ Accepts GET parameters of: name: Name of the vocabulary field: Name of the field the vocabulary is being retrieved for query: string or json object of criteria and options. json value consists of a structure: { criteria: object, sort_on: index, sort_order: (asc|reversed) } attributes: comma seperated, or json object list batch: { page: 1-based page of results, size: size of paged results } """ context = self.get_context() self.request.response.setHeader("Content-type", "application/json") try: vocabulary = self.get_vocabulary() except VocabLookupException, e: return json_dumps({'error': e.message}) results_are_brains = False if hasattr(vocabulary, 'search_catalog'): query = self.parsed_query() results = vocabulary.search_catalog(query) results_are_brains = True elif hasattr(vocabulary, 'search'): try: query = self.parsed_query()['SearchableText']['query'] except KeyError: results = iter(vocabulary) else: results = vocabulary.search(query) else: results = vocabulary try: total = len(results) except TypeError: # do not error if object does not support __len__ # we'll check again later if we can figure some size # out total = 0 # get batch batch = _parseJSON(self.request.get('batch', '')) if batch and ('size' not in batch or 'page' not in batch): batch = None # batching not providing correct options if batch: # must be slicable for batching support page = int(batch['page']) size = int(batch['size']) if size > MAX_BATCH_SIZE: raise Exception('Max batch size is 500') # page is being passed in is 1-based start = (max(page - 1, 0)) * size end = start + size # Try __getitem__-based slice, then iterator slice. # The iterator slice has to consume the iterator through # to the desired slice, but that shouldn't be the end # of the world because at some point the user will hopefully # give up scrolling and search instead. try: results = results[start:end] except TypeError: results = itertools.islice(results, start, end) # build result items items = [] attributes = _parseJSON(self.request.get('attributes', '')) if isinstance(attributes, basestring) and attributes: attributes = attributes.split(',') if attributes: portal = getToolByName(context, 'portal_url').getPortalObject() base_path = '/'.join(portal.getPhysicalPath()) for vocab_item in results: if not results_are_brains: vocab_item = vocab_item.value item = {} for attr in attributes: key = attr if ':' in attr: key, attr = attr.split(':', 1) if attr in _unsafe_metadata: continue if key == 'path': attr = 'getPath' val = getattr(vocab_item, attr, None) if callable(val): if attr in _safe_callable_metadata: val = val() else: continue if key == 'path': val = val[len(base_path):] item[key] = val items.append(item) else: for item in results: items.append({'id': item.value, 'text': item.title}) if total == 0: total = len(items) return json_dumps({'results': items, 'total': total})
def __call__(self): self.options = json_dumps(self.get_options()) return super(FolderContentsView, self).__call__()
def __call__(self): self.options = json_dumps(self.get_options()) return super().__call__()
def __call__(self): site = getSite() base_url = site.absolute_url() base_vocabulary = "%s/@@getVocabulary?name=" % base_url site_path = site.getPhysicalPath() context_path = self.context.getPhysicalPath() options = { "vocabularyUrl": "%splone.app.vocabularies.Catalog" % (base_vocabulary), "tagsVocabularyUrl": "%splone.app.vocabularies.Keywords" % (base_vocabulary), "usersVocabularyUrl": "%splone.app.vocabularies.Users" % (base_vocabulary), "urlStructure": {"base": base_url, "appended": "/folder_contents"}, "moveUrl": "%s{path}/fc-itemOrder" % base_url, "indexOptionsUrl": "%s/@@qsOptions" % base_url, "contextInfoUrl": "%s{path}/@@fc-contextInfo" % base_url, "setDefaultPageUrl": "%s{path}/@@fc-setDefaultPage" % base_url, "availableColumns": { "id": translate(_("ID"), context=self.request), "Title": translate(_("Title"), context=self.request), "ModificationDate": translate(_("Last modified"), context=self.request), "EffectiveDate": translate(_("Publication date"), context=self.request), "CreationDate": translate(_("Created on"), context=self.request), "review_state": translate(_("Review state"), context=self.request), "Subject": translate(_("Tags"), context=self.request), "Type": translate(_("Type"), context=self.request), "is_folderish": translate(_("Folder"), context=self.request), "exclude_from_nav": translate(_("Excluded from nav"), context=self.request), "getObjSize": translate(_("Object Size"), context=self.request), "last_comment_date": translate(_("Last comment date"), context=self.request), "total_comments": translate(_("Total comments"), context=self.request), }, "buttonGroups": { "primary": [ {"id": "cut", "title": translate(_("Cut"), context=self.request)}, {"id": "copy", "title": translate(_("Copy"), context=self.request)}, { "id": "paste", "title": translate(_("Paste"), context=self.request), "url": base_url + "/@@fc-paste", }, { "id": "delete", "title": translate(_("Delete"), context=self.request), "url": base_url + "/@@fc-delete", "context": "danger", "icon": "trash", }, ], "secondary": [ { "id": "workflow", "title": translate(_("Workflow"), context=self.request), "url": base_url + "/@@fc-workflow", }, {"id": "tags", "title": translate(_("Tags"), context=self.request), "url": base_url + "/@@fc-tags"}, { "id": "properties", "title": translate(_("Properties"), context=self.request), "url": base_url + "/@@fc-properties", }, { "id": "rename", "title": translate(_("Rename"), context=self.request), "url": base_url + "/@@fc-rename", }, ], }, "rearrange": { "properties": { "id": translate(_("Id"), context=self.request), "sortable_title": translate(_("Title"), context=self.request), "modified": translate(_("Last modified"), context=self.request), "created": translate(_("Created on"), context=self.request), "effective": translate(_("Publication date"), context=self.request), "Type": translate(_("Type"), context=self.request), }, "url": "%s{path}/@@fc-rearrange" % base_url, }, "basePath": "/" + "/".join(context_path[len(site_path) :]), "upload": { "relativePath": "fileUpload", "baseUrl": base_url, "initialFolder": IUUID(self.context, None), "useTus": TUS_ENABLED, }, } self.options = json_dumps(options) return super(FolderContentsView, self).__call__()
def __call__(self): site = getSite() base_url = site.absolute_url() base_vocabulary = '%s/@@getVocabulary?name=' % base_url site_path = site.getPhysicalPath() context_path = self.context.getPhysicalPath() options = { 'vocabularyUrl': '%splone.app.vocabularies.Catalog' % ( base_vocabulary), 'tagsVocabularyUrl': '%splone.app.vocabularies.Keywords' % ( base_vocabulary), 'usersVocabularyUrl': '%splone.app.vocabularies.Users' % ( base_vocabulary), 'urlStructure': { 'base': base_url, 'appended': '/folder_contents' }, 'moveUrl': '%s{path}/fc-itemOrder' % base_url, 'indexOptionsUrl': '%s/@@qsOptions' % base_url, 'contextInfoUrl': '%s{path}/@@fc-contextInfo' % base_url, 'setDefaultPageUrl': '%s{path}/@@fc-setDefaultPage' % base_url, 'availableColumns': { 'id': translate(_('ID'), context=self.request), 'Title': translate(_('Title'), context=self.request), 'ModificationDate': translate(_('Last modified'), context=self.request), 'EffectiveDate': translate(_('Publication date'), context=self.request), 'CreationDate': translate(_('Created on'), context=self.request), 'review_state': translate(_('Review state'), context=self.request), 'Subject': translate(_('Tags'), context=self.request), 'Type': translate(_('Type'), context=self.request), 'is_folderish': translate(_('Folder'), context=self.request), 'exclude_from_nav': translate(_('Excluded from nav'), context=self.request), 'getObjSize': translate(_('Object Size'), context=self.request), 'last_comment_date': translate(_('Last comment date'), context=self.request), 'total_comments': translate(_('Total comments'), context=self.request), }, 'buttonGroups': { 'primary': [{ 'id': 'cut', 'title': translate(_('Cut'), context=self.request), }, { 'id': 'copy', 'title': translate(_('Copy'), context=self.request), }, { 'id': 'paste', 'title': translate(_('Paste'), context=self.request), 'url': base_url + '/@@fc-paste' }, { 'id': 'delete', 'title': translate(_('Delete'), context=self.request), 'url': base_url + '/@@fc-delete', 'context': 'danger', 'icon': 'trash' }], 'secondary': [{ 'id': 'workflow', 'title': translate(_('Workflow'), context=self.request), 'url': base_url + '/@@fc-workflow' }, { 'id': 'tags', 'title': translate(_('Tags'), context=self.request), 'url': base_url + '/@@fc-tags' }, { 'id': 'properties', 'title': translate(_('Properties'), context=self.request), 'url': base_url + '/@@fc-properties' }, { 'id': 'rename', 'title': translate(_('Rename'), context=self.request), 'url': base_url + '/@@fc-rename' }] }, 'rearrange': { 'properties': { 'id': translate(_('Id'), context=self.request), 'sortable_title': translate(_('Title'), context=self.request), 'modified': translate(_('Last modified'), context=self.request), 'created': translate(_('Created on'), context=self.request), 'effective': translate(_('Publication date'), context=self.request), 'Type': translate(_('Type'), context=self.request) }, 'url': '%s{path}/@@fc-rearrange' % base_url }, 'basePath': '/' + '/'.join(context_path[len(site_path):]), 'upload': { 'relativePath': 'fileUpload', 'baseUrl': base_url, 'initialFolder': IUUID(self.context, None), 'useTus': TUS_ENABLED } } self.options = json_dumps(options) return super(FolderContentsView, self).__call__()
class BaseVocabularyView(BrowserView): def __call__(self): """ Accepts GET parameters of: name: Name of the vocabulary field: Name of the field the vocabulary is being retrieved for query: string or json object of criteria and options. json value consists of a structure: { criteria: object, sort_on: index, sort_order: (asc|reversed) } attributes: comma seperated, or json object list batch: { page: 1-based page of results, size: size of paged results } """ context = self.get_context() self.request.response.setHeader("Content-type", "application/json") try: vocabulary = self.get_vocabulary() except VocabLookupException, e: return json_dumps({'error': e.message}) results_are_brains = False if hasattr(vocabulary, 'search_catalog'): query = self.parsed_query() results = vocabulary.search_catalog(query) results_are_brains = True elif hasattr(vocabulary, 'search'): try: query = self.parsed_query()['SearchableText']['query'] except KeyError: results = iter(vocabulary) else: results = vocabulary.search(query) else: results = vocabulary try: total = len(results) except TypeError: # do not error if object does not support __len__ # we'll check again later if we can figure some size # out total = 0 # get batch batch = _parseJSON(self.request.get('batch', '')) if batch and ('size' not in batch or 'page' not in batch): batch = None # batching not providing correct options if batch: # must be slicable for batching support page = int(batch['page']) size = int(batch['size']) if size > MAX_BATCH_SIZE: raise Exception('Max batch size is 500') # page is being passed in is 1-based start = (max(page - 1, 0)) * size end = start + size # Try __getitem__-based slice, then iterator slice. # The iterator slice has to consume the iterator through # to the desired slice, but that shouldn't be the end # of the world because at some point the user will hopefully # give up scrolling and search instead. try: results = results[start:end] except TypeError: results = itertools.islice(results, start, end) # build result items items = [] attributes = _parseJSON(self.request.get('attributes', '')) if isinstance(attributes, basestring) and attributes: attributes = attributes.split(',') translate_ignored = [ 'author_name', 'cmf_uid', 'commentators', 'created', 'CreationDate', 'Creator', 'Date', 'Description', 'effective', 'EffectiveDate', 'end', 'exclude_from_nav', 'ExpirationDate', 'expires', 'getIcon', 'getId', 'getObjSize', 'getRemoteUrl', 'getURL', 'id', 'in_response_to', 'is_folderish', 'last_comment_date', 'listCreators', 'location', 'meta_type', 'ModificationDate', 'modified', 'path', 'portal_type', 'review_state', 'start', 'Subject', 'sync_uid', 'Title', 'total_comments' 'UID', ] if attributes: base_path = getNavigationRoot(context) sm = getSecurityManager() can_edit = sm.checkPermission(DEFAULT_PERMISSION_SECURE, context) for vocab_item in results: if not results_are_brains: vocab_item = vocab_item.value item = {} for attr in attributes: key = attr if ':' in attr: key, attr = attr.split(':', 1) if attr in _unsafe_metadata and not can_edit: continue if key == 'path': attr = 'getPath' val = getattr(vocab_item, attr, None) if callable(val): if attr in _safe_callable_metadata: val = val() else: continue if key == 'path': val = val[len(base_path):] if (key not in translate_ignored and isinstance(val, basestring)): item[key] = translate(_(safe_unicode(val)), context=self.request) else: item[key] = val items.append(item) else: for item in results: items.append({'id': item.value, 'text': item.title}) if total == 0: total = len(items) return json_dumps({'results': items, 'total': total})
def __call__(self): """ Accepts GET parameters of: name: Name of the vocabulary field: Name of the field the vocabulary is being retrieved for query: string or json object of criteria and options. json value consists of a structure: { criteria: object, sort_on: index, sort_order: (asc|reversed) } attributes: comma seperated, or json object list batch: { page: 1-based page of results, size: size of paged results } """ context = self.get_context() self.request.response.setHeader( 'Content-Type', 'application/json; charset=utf-8' ) try: vocabulary = self.get_vocabulary() except VocabLookupException as e: return json_dumps({'error': e.args[0]}) results_are_brains = False if hasattr(vocabulary, 'search_catalog'): query = self.parsed_query() results = vocabulary.search_catalog(query) results_are_brains = True elif hasattr(vocabulary, 'search'): try: query = self.parsed_query()['SearchableText']['query'] except KeyError: results = iter(vocabulary) else: results = vocabulary.search(query) else: results = vocabulary try: total = len(results) except TypeError: # do not error if object does not support __len__ # we'll check again later if we can figure some size # out total = 0 # get batch batch = _parseJSON(self.request.get('batch', '')) if batch and ('size' not in batch or 'page' not in batch): batch = None # batching not providing correct options if batch: # must be slicable for batching support page = int(batch['page']) size = int(batch['size']) if size > MAX_BATCH_SIZE: raise Exception('Max batch size is 500') # page is being passed in is 1-based start = (max(page - 1, 0)) * size end = start + size # Try __getitem__-based slice, then iterator slice. # The iterator slice has to consume the iterator through # to the desired slice, but that shouldn't be the end # of the world because at some point the user will hopefully # give up scrolling and search instead. try: results = results[start:end] except TypeError: results = itertools.islice(results, start, end) # build result items items = [] attributes = _parseJSON(self.request.get('attributes', '')) if isinstance(attributes, six.string_types) and attributes: attributes = attributes.split(',') translate_ignored = self.get_translated_ignored() if attributes: base_path = self.get_base_path(context) sm = getSecurityManager() can_edit = sm.checkPermission(DEFAULT_PERMISSION_SECURE, context) mtt = getToolByName(self.context, 'mimetypes_registry') for vocab_item in results: if not results_are_brains: vocab_item = vocab_item.value item = {} for attr in attributes: key = attr if ':' in attr: key, attr = attr.split(':', 1) if attr in _unsafe_metadata and not can_edit: continue if key == 'path': attr = 'getPath' val = getattr(vocab_item, attr, None) if callable(val): if attr in _safe_callable_metadata: val = val() else: continue if key == 'path': val = val[len(base_path):] if ( key not in translate_ignored and isinstance(val, six.string_types) ): item[key] = translate( _(safe_unicode(val)), context=self.request ) else: item[key] = val if key == 'getMimeIcon': item[key] = None # get mime type icon url from mimetype registry' contenttype = aq_base( getattr(vocab_item, 'mime_type', None)) if contenttype: ctype = mtt.lookup(contenttype) item[key] = '/'.join([ base_path, guess_icon_path(ctype[0])]) items.append(item) else: items = [{'id': item.value, 'text': item.title} for item in results] if total == 0: total = len(items) return json_dumps({ 'results': items, 'total': total })