Debian Codegraph @

gavo/base/typedmeta.py

raw
1 """
2 Typed metadata.
3
4 These are subclasses of base.MetaValue that deal with special sorts
5 of metadata. Most of the time, they organise some extra (hidden or open)
6 keys, or they do some special HTML rendering.
7
8 Use the meta.forKeys class decorator to teach meta.py where to
9 use your new class.
10 """
11
12 #c Copyright 2008-2025, the GAVO project <[email protected]>
13 #c
14 #c This program is free software, covered by the GNU GPL. See the
15 #c COPYING file in the source distribution.
16
17
18 import datetime
19 import re
20 from urllib import parse as urlparse
21
22 from gavo import utils
23 from gavo.base import config
24 from gavo.base import meta
25 from gavo.utils import misctricks
26 from gavo.utils import stanxml
27
28 from gavo.utils.dachstypes import (
29 cast, Any, Optional, Sequence, Union)
30
31
32 def _getMSContent(ms: meta._MetaSeed) -> str:
33 """returns the stringified version of a _MetaSeed.
34
35 This probably should go to base.meta when we make _MetaSeed public.
36 For now, let's pretend the two modules are good friends.
37 """
38 if ms is None:
39 return ""
40 elif isinstance(ms, meta.MetaValue):
41 return ms.content
42 else:
43 return cast(str, ms)
44
45
46 @meta.forKeys("_related", "referenceURL")
47 class MetaURL(meta.MetaValue):
48 """A meta value containing a link and optionally a title
49
50 In plain text, this would look like
51 this::
52
53 _related:http://foo.bar
54 _related.title: The foo page
55
56 In XML, you can write::
57
58 <meta name="_related" title="The foo page"
59 ivoId="ivo://bar.org/foo">http://foo.bar</meta>
60
61 or, if you prefer::
62
63 <meta name="_related">http://foo.bar
64 <meta name="title">The foo page</meta></meta>
65 </meta>
66
67 _related meta is rendered in the sidebar in the web interface; it is
68 currently ignored for relationships published to the VO.
69
70 For links within your DaCHS site, use the internallink macro, the argument
71 of which the the "path" to a resource, i.e. RD path/service/renderer;
72 we recommend to use the info renderer in such links as a rule. This would
73 look like this::
74
75 meta name="_related" title="Aspec SSAP"
76 \\internallink{aspec/q/ssa/info}</meta>
77 """
78 def __init__(self,
79 url: str,
80 format: str = "plain",
81 title: Optional[str] = None) -> None:
82 if url:
83 url = url.strip()
84 meta.MetaValue.__init__(self, url, format)
85 self.title = title
86
87 def _getContentAsHTML(self, content: str, block: bool = False) -> str:
88 title = self.title or content
89 return '<a href=%s>%s</a>'%(
90 stanxml.escapeAttrVal(content), stanxml.escapePCDATA(title))
91
92 def _addMeta(self, atoms: Sequence[str], metaValue: meta._MetaSeed) -> None:
93 if atoms[0]=="title":
94 self.title = _getMSContent(metaValue)
95 else:
96 meta.MetaValue._addMeta(self, atoms, metaValue)
97
98
99 @meta.forKeys(
100 # if you add new RelationResourceMeta meta keys, be you'll also need to
101 # amend registry.builders._vrResourceBuilder
102
103 # VOResource 1.0 terms
104 "servedBy",
105 "serviceFor",
106 "relatedTo",
107 "mirrorOf",
108 "derivedFrom",
109 "uses",
110
111 # VOResource 1.1 terms
112 "cites",
113 "isSupplementTo",
114 "isSupplementedBy",
115 "isContinuedBy",
116 "continues",
117 "isNewVersionOf",
118 "isPreviousVersionOf",
119 "isPartOf",
120 "hasPart",
121 "isSourceOf",
122 "isDerivedFrom",
123 "isIdenticalTo",
124 "isServiceFor",
125 "isServedBy")
126 class RelatedResourceMeta(meta.MetaValue):
127 """A meta value containing an ivo-id and a name of a related resource.
128
129 The sort of relationsip is encoded in the meta name, where the terms
130 are defined in the vocabuary
131 http://www.g-vo.org/rdf/voresource/relationship_type (where there
132 are minor lexical deviations from identifiers there to DaCHS' meta names).
133
134 All relationship metas should look like this (using isSupplementTo as an
135 example; while an ivoId is not mandatory, it rarely makes sense to declare
136 a relationship without it)::
137
138 isSupplementTo: GAVO TAP service
139 isSupplementTo.ivoId: ivo://org.gavo.dc
140
141 It is also possible to include an altIdentifier (such as a DOI) to declare
142 a relationship to a resource not declared in the IVOA registry.
143
144 ``isServedBy`` and ``isServiceFor`` are somewhat special cases, as
145 the service attribute of data publications automatically takes care
146 of them; so, you shouldn't usually need to bother with these two manually.
147 """
148 def __init__(self,
149 title: str,
150 format: str = "plain",
151 ivoId: Optional[str] = None,
152 altIdentifier: Optional[str] = None) -> None:
153 meta.MetaValue.__init__(self, title, format)
154 if ivoId is not None:
155 self._addMeta(["ivoId"], meta.MetaValue(ivoId))
156 if altIdentifier is not None:
157 self._addMeta(["altIdentifier"], meta.MetaValue(altIdentifier))
158
159
160 @meta.forKeys("_news")
161 class NewsMeta(meta.MetaValue):
162 """A meta value representing a "news" item.
163
164 The content is the body of the news. In addition, they have
165 date, author, and role children. In plain text, you would write::
166
167 _news: Frobnicated the quux.
168 _news.author: MD
169 _news.date: 2009-03-06
170 _news.role: updated
171
172 In XML, you would usually write::
173
174 <meta name="_news" author="MD" date="2009-03-06">
175 Frobnicated the quux.
176 </meta>
177
178 _news items become serialised into Registry records despite their
179 leading underscores. role then becomes the date's role.
180 """
181 discardChildrenInHTML = True
182
183 def __init__(self,
184 content: str,
185 format: str = "plain",
186 author: Optional[str] = None,
187 date: Optional[str] = None,
188 role: Optional[str] = None) -> None:
189 meta.MetaValue.__init__(self, content, format)
190 self.initArgs = format, author, date, role
191 for key in ["author", "date", "role"]:
192 val = locals()[key]
193 if val is not None:
194 self._addMeta([key], meta.MetaValue(val))
195
196 def _getContentAsHTML(self, content: str, block: bool = False) -> str:
197 authorpart = ""
198 if self.author:
199 authorpart = " (%s)"%self.author
200 return meta.IncludesChildren('<span class="newsitem">%s%s: %s</span>'%(
201 stanxml.escapePCDATA(self.date),
202 stanxml.escapePCDATA(authorpart),
203 meta.MetaValue._getContentAsHTML(self, content, block)))
204
205 def _addMeta(self, atoms: Sequence[str], metaValue: meta._MetaSeed) -> None:
206 if atoms[0]=="author":
207 self.author = _getMSContent(metaValue)
208 elif atoms[0]=="date":
209 self.date = _getMSContent(metaValue)
210 elif atoms[0]=="role":
211 self.role = _getMSContent(metaValue)
212 meta.MetaValue._addMeta(self, atoms, metaValue)
213
214
215 @meta.forKeys("note")
216 class NoteMeta(meta.MetaValue):
217 """A meta value representing a "note" item.
218
219 This is like a footnote, typically on tables, and is rendered in table
220 infos.
221
222 The content is the note body. In addition, you want a tag child that
223 gives whatever the note is references as. We recommend numbers.
224
225 Contrary to other meta items, note content defaults to rstx format.
226
227 Typically, this works with a column's note attribute.
228
229 In XML, you would usually write::
230
231 <meta name="note" tag="1">
232 Better ignore this.
233 </meta>
234 """
235 def __init__(self,
236 content: str,
237 format: str = "rst",
238 tag: str = "not-set") -> None:
239 meta.MetaValue.__init__(self, content, format)
240 self.initArgs = content, format, tag
241 self.tag = tag or "(untagged)"
242
243 def _getContentAsHTML(self, content: str, block: bool = False) -> str:
244 return ('<dt class="notehead">'
245 '<a name=%s>Note %s</a></dt><dd>%s</dd>')%(
246 stanxml.escapeAttrVal("note-"+self.tag),
247 stanxml.escapePCDATA(self.tag),
248 meta.MetaValue._getContentAsHTML(self, content))
249
250 def _addMeta(self, atoms: Sequence[str], metaValue: meta._MetaSeed) -> None:
251 if atoms[0]=="tag":
252 self.tag = _getMSContent(metaValue)
253 else:
254 meta.MetaValue._addMeta(self, atoms, metaValue)
255
256
257 @meta.forKeys("creationDate", "_dataUpdated", "_metadataUpdated")
258 class DatetimeMeta(meta.MetaValue):
259 """A meta value representing a timestamp.
260
261 Accessing it, you will get a formatted ISO/DALI string. You
262 can construct them with both strings (that we'll try to parse and
263 bomb if that's not possible) and datetime.datetime objects.
264 """
265 def __init__(self,
266 content: Union[datetime.datetime, str],
267 *args: str,
268 **kwargs: Any) -> None:
269 if isinstance(content, str):
270 if content.startswith("\\metaString{authority"):
271 # backwards compatibility hack: legacy (1.0) userconfigs would try
272 # to pull authority.creationDate via unexpanded macros, and
273 # that breaks now. Hack around it for now.
274 content = meta.getMetaText(meta.CONFIG_META, "authority.creationDate")
275
276 content = utils.parseISODT(content)
277
278 if isinstance(content, datetime.datetime):
279 content = utils.formatISODT(content)
280
281 meta.MetaValue.__init__(self, content, *args, **kwargs)
282
283
284 @meta.forKeys("info")
285 class InfoItem(meta.MetaValue):
286 """A meta value for info items in VOTables.
287
288 In addition to the content (which should be rendered as the info element's
289 text content), it contains an infoName and an infoValue.
290
291 They are only used internally in VOTable generation and might go away
292 without notice.
293 """
294 def __init__(self,
295 content: str,
296 format: str = "plain",
297 infoName: Optional[str] = None,
298 infoValue: Optional[str] = None,
299 infoId: Optional[str] = None) -> None:
300 meta.MetaValue.__init__(self, content, format)
301 self.initArgs = content, format, infoName, infoValue, infoId
302 self.infoName, self.infoValue = infoName, infoValue
303 self.infoId = infoId
304
305
306 @meta.forKeys("logo", "creator.logo")
307 class LogoMeta(meta.MetaValue):
308 """A MetaValue corresponding to a small image.
309
310 These are rendered as little images in HTML. In XML meta, you can
311 say::
312
313 <meta name="_somelogo" type="logo">http://foo.bar/quux.png</meta>
314 """
315 def __init__(self,
316 content: str = "",
317 *args: str,
318 **kwargs: Any) -> None:
319 if not "\\" in content and not re.match("https?://", content):
320 # see above on avoiding circular imports
321 content = urlparse.urljoin(
322 config.get("web", "serverURL"),
323 content)
324 meta.MetaValue.__init__(self, content, *args, **kwargs)
325
326 def _getContentAsHTML(self, content: str, block: bool = False) -> str:
327 return '<img class="metalogo" src="%s" alt="[Logo]"/>'%(
328 str(content).strip())
329
330
331 @meta.forKeys("source")
332 class BibcodeMeta(meta.MetaValue):
333 """A MetaValue that may contain bibcodes, which are rendered as links
334 into ADS.
335 """
336 def _makeADSLink(self, matOb: re.Match) -> str:
337 urlBibcode = urlparse.quote(matOb.group(0))
338 adsURL = f"https://ui.adsabs.harvard.edu/abs/{urlBibcode}/abstract"
339 return '<a href="{}">{}</a>'.format(
340 adsURL,
341 stanxml.escapePCDATA(matOb.group(0)))
342
343 def _getContentAsHTML(self, content: str, block: bool = False) -> str:
344 content = str(content)
345 mat = misctricks.BIBCODE_PATTERN.match(content)
346 if mat:
347 return self._makeADSLink(mat)
348 else:
349 return stanxml.escapePCDATA(content)
350
351
352 @meta.forKeys("votlink")
353 class VotLinkMeta(meta.MetaValue):
354 """A MetaValue serialized into VOTable links (or, ideally,
355 analogous constructs).
356
357 This exposes the various attributes of VOTable LINKs as href
358 linkname, contentType, and role. You cannot set ID here; if this ever
359 needs referencing, we'll need to think about it again.
360 The href attribute is simply the content of our meta (since
361 there's no link without href), and there's never any content
362 in VOTable LINKs).
363
364 You could thus say::
365
366 votlink: http://docs.g-vo.org/DaCHS
367 votlink.role: doc
368 votlink.contentType: text/html
369 votlink.linkname: GAVO DaCHS documentation
370 """
371 def __init__(self,
372 href: str,
373 format: str = "plain",
374 linkname: Optional[str] = None,
375 contentType: Optional[str] = None,
376 role: Optional[str] = None) -> None:
377 meta.MetaValue.__init__(self, href, format)
378 for key in ["linkname", "contentType", "role"]:
379 val = locals()[key]
380 if val is not None:
381 self._addMeta([key], meta.MetaValue(val))
382
383
384 @meta.forKeys("_example")
385 class ExampleMeta(meta.MetaValue):
386 """A MetaValue to keep VOSI examples in.
387
388 All of these must have a title, which is also used to generate
389 references.
390
391 These also are in reStructuredText by default, and changing
392 that probably makes no sense at all, as these will always need
393 interpreted text roles for proper markup.
394
395 Thus, the usual pattern here is::
396
397 <meta name="_example" title="An example for _example">
398 See docs_
399
400 .. _docs: http://docs.g-vo.org
401 </meta>
402 """
403 def __init__(self,
404 content: str,
405 format: str = "rst",
406 title: str = "Unnamed Example") -> None:
407 if title=="Unnamed Example":
408 raise meta.MetaError("_example meta must always have a title")
409 meta.MetaValue.__init__(self, content, format)
410 self._addMeta(["title"], meta.MetaValue(title))
411
412
413 @meta.forKeys("doi")
414 class DOIMeta(meta.MetaValue):
415 """A MetaValue for a DOI.
416
417 This lets people construct DOI meta with or without a doi: prefix.
418 It also creates landing page links in HTML.
419 """
420 def __init__(self, content: str, **kwargs: Any) -> None:
421 if content:
422 if content.startswith("doi:"):
423 content = content[4:]
424 if not re.match("[0-9.]+/", content):
425 raise meta.MetaValueError("%s does not look like a DOI"%content)
426 meta.MetaValue.__init__(self, content.strip(), **kwargs)
427
428 def _getContentAsHTML(self, content: str, block: bool = False) -> str:
429 return '<a href=%s>%s</a>'%(
430 stanxml.escapeAttrVal("http://dx.doi.org/"+content),
431 stanxml.escapePCDATA(content))
432
433
434 # subject meta is in protocols.vocabularies