This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
collective.dms.thesaurus/src/collective/dms/thesaurus/utils.py

97 lines
3.6 KiB
Python

import json
from zope import component
from Products.Five.browser import BrowserView
from zope.component import getUtility
from zope.schema.interfaces import IVocabularyFactory
from zope.event import notify
from zope.lifecycleevent import ObjectAddedEvent, ObjectModifiedEvent
from plone.app.textfield.value import RichTextValue
from plone import api
from Products.CMFCore.utils import getToolByName
class ImportJson(BrowserView):
def __call__(self):
path = '/tmp/thesaurus.json'
# XXX: replace with a path given in the query string, or load json
# from POST data
terms = json.load(file(path))
# 1st step; create object for terms
for term_id, term in terms.items():
try:
object = getattr(self.context, term_id)
except AttributeError:
self.context.invokeFactory('dmskeyword', term_id,
title=term.get('title'))
object = getattr(self.context, term_id)
notify(ObjectAddedEvent(object))
object.title = term.get('title')
object.historical_note = None
if term.get('historical_note'):
object.historical_note = RichTextValue(
raw=term.get('historical_note'),
mimeType='text/html',
outputMimeType='text/x-html-safe')
object.scope_note = None
if term.get('scope_note'):
object.scope_note = RichTextValue(
raw=term.get('scope_note'),
mimeType='text/html',
outputMimeType='text/x-html-safe')
object.equivs = [x for x in term.get('equivalents') or [] if x]
# 2nd step; add relations
for term_id, term in terms.items():
object = getattr(self.context, term_id)
object.related = [x for x in term.get('related', [])]
object.broader = [x for x in term.get('parents', [])]
notify(ObjectModifiedEvent(object))
return 'OK'
def get_thesaurus_object(context):
catalog = getToolByName(context, 'portal_catalog')
try:
thesaurus = catalog(portal_type='dmsthesaurus')[0].getObject()
except IndexError:
return None
return thesaurus
class JsonView(BrowserView):
def __call__(self):
portal_catalog = api.portal.get_tool('portal_catalog')
folder_path = '/'.join(self.context.getPhysicalPath())
query = {'path': {'query' : folder_path},
'portal_type': 'dmskeyword',
'sort_on': 'sortable_title',
'sort_order': 'ascending'}
results = portal_catalog.searchResults(query)
keywords = {}
for brain in results:
keyword = brain.getObject()
keywords[keyword.id] = {
'title': keyword.title,
'equivalents': keyword.equivs,
'historical_note': keyword.historical_note,
'scope_note': keyword.scope_note,
'related': list(keyword.related or []),
'parents': list(keyword.broader or []),
}
if isinstance(keyword.historical_note, RichTextValue):
keywords[keyword.id]['historical_note'] = keyword.historical_note.raw
if isinstance(keyword.scope_note, RichTextValue):
keywords[keyword.id]['scope_note'] = keyword.scope_note.raw
self.request.response.setHeader('Content-type', 'application/json')
return json.dumps(keywords)