Debian Codegraph @

gavo/web/metarender.py

raw
1 # -*- coding: utf-8 -*-
2 """
3 Renderers that take services "as arguments".
4 """
5
6 #c Copyright 2008-2025, the GAVO project <[email protected]>
7 #c
8 #c This program is free software, covered by the GNU GPL. See the
9 #c COPYING file in the source distribution.
10
11
12 import re
13 import urllib.request, urllib.parse, urllib.error
14
15 from twisted.web import resource
16 from twisted.web import template
17 from twisted.web.template import tags as T
18
19 from gavo import base
20 from gavo import formal
21 from gavo import registry
22 from gavo import stc
23 from gavo import svcs
24 from gavo import utils
25 from gavo.web import common
26 from gavo.web import grend
27
28
29 def _protectForBibTeX(tx):
30 """returns tx in a way that hopefully prevents larger disasters
31 when used with BibTeX.
32
33 Among others, this just looks for multiple uppercase characters within
34 one word and protects the respective word with curly braces; for now,
35 this is ASCII only.
36
37 This is also where we escape for TeX.
38 """
39 return re.sub(r"([#$_&\\%])", r"\\\1",
40 re.sub(r"(\w*[A-Z]\w+[A-Z]\w*)", r"{\1}", tx))
41
42
43 def makeBibTeXForMetaCarrier(mc):
44 """returns a (unicode) best-effort BibTeX record for something mixing in
45 mc.
46
47 This needs, at least, a creationDate, a creator, a referenceURL,
48 and a title to work; if these aren't there, you'll get a MetaError.
49 """
50 creationDate = utils.parseISODT(
51 base.getMetaText(mc,
52 "creationDate",
53 raiseOnFail=True))
54 year = creationDate.year
55
56 # for the BibTeX tag, prefer the short name if given...
57 label = base.getMetaText(mc, "shortName", None)
58 if label is None:
59 # ... else hope it's a table...
60 try:
61 label = mc.getQName()
62 except AttributeError:
63 # fall back to something made from the creation date
64 # (which at least won't change between invocations)
65 label = utils.intToFunnyWord(
66 int(re.sub(r"[^\d]+", "", creationDate.isoformat())))
67 label = "vo:"+re.sub(r"[^\w]", "_", label)
68
69 authors = " and ".join(m.getContent()
70 for m in mc.iterMeta("creator.name",
71 propagate=True))
72
73 res = [
74 "@MISC{%s"%label,
75 " year=%s"%year,
76 " title={%s}"%_protectForBibTeX(
77 base.getMetaText(mc, "title", "Untitled Resource")),
78 " author={%s}"%_protectForBibTeX(authors),
79 " url={%s}"%base.getMetaText(mc, "referenceURL", raiseOnFail=True),
80 " howpublished={{VO} resource provided by the %s}"%
81 _protectForBibTeX(base.getConfig("web", "sitename")),
82 ]
83 doi = base.getMetaText(mc, "doi", None)
84 if doi:
85 res.append(
86 " doi = {%s}"%doi)
87 return ",\n".join(res)+"\n}\n"
88
89
90 class MetaRenderer(grend.CustomTemplateMixin, grend.ServiceBasedPage):
91 """Renderers that are allowed on all services.
92 """
93 checkedRenderer = False
94
95 @classmethod
96 def isCacheable(self, segments, request):
97 return True
98
99 def data_otherServices(self, request, tag):
100 """returns a list of dicts describing other services provided by the
101 the describing RD.
102
103 The class mixing this in needs to provide a describingRD attribute for
104 this to work. This may be the same as self.service.rd, and the
105 current service will be excluded from the list in this case.
106 """
107 res = []
108 for svc in self.describingRD.services:
109 if svc is not self.service:
110 res.append({"infoURL": svc.getURL("info"),
111 "title": base.getMetaText(svc, "title")})
112 return res
113
114 @template.renderer
115 def sortOrder(self, request, tag):
116 if "alphaOrder" in request.strargs:
117 return tag["Sorted alphabetically. ",
118 T.a(href=request.path)[
119 "[Sort by DB column index]"]]
120 else:
121 return tag["Sorted by DB column index. ",
122 T.a(href=request.path+b"?alphaOrder=True")[
123 "[Sort alphabetically]"]]
124
125 @template.renderer
126 def rdInfoLink(self, request, tag):
127 # a link to the info to data's RD (i.e., data needs an rd attribute).
128 return tag(href="/browse/"+tag.slotData.rd.sourceId)[
129 RDInfoPage.makePageTitle(tag.slotData.rd)]
130
131 @template.renderer
132 def ifkey(self, keyName):
133 def render(request, tag):
134 if keyName in tag.slotData:
135 return tag
136 return ""
137 return render
138
139 @template.renderer
140 def ifbibcode(self, request, tag):
141 """renders its children if the source metadata looks like a bibcode.
142 """
143 source = base.getMetaText(self.metaCarrier, "source", "")
144 if utils.couldBeABibcode(source):
145 return tag
146 else:
147 return ""
148
149 def data_bibtexentry(self, request, tag):
150 """returns BibTeX for the current record.
151
152 This will return None if no BibTeX can be made.
153 """
154 try:
155 return makeBibTeXForMetaCarrier(self.metaCarrier)
156 except base.MetaError:
157 return None
158
159
160 class RendExplainer(object):
161 """is a container for various functions having to do with explaining
162 renderers on services.
163
164 Use the explain(renderer, service) class method.
165 """
166
167 @classmethod
168 def _explain_form(cls, service):
169 return T.transparent["an interface for web browsers through an ",
170 T.a(href=service.getURL("form"))["HTML form"]]
171
172 @classmethod
173 def _explain_fixed(cls, service):
174 return T.transparent["a ",
175 T.a(href=service.getURL("fixed"))["custom page"],
176 ", possibly with dynamic content"]
177
178 @classmethod
179 def _explain_volatile(cls, service):
180 return T.transparent["a ",
181 T.a(href=service.getURL("volatile"))["custom page"],
182 ", possibly with dynamic content"]
183
184 @classmethod
185 def _explain_soap(cls, service):
186
187 def generateArguments():
188 # Slightly obfuscated -- I need to get ", " in between the items.
189 fieldIter = iter(service.getInputKeysFor("soap"))
190 try:
191 nextItem = next(fieldIter)
192 while True:
193 desc = "%s/%s"%(nextItem.name, nextItem.type)
194 if nextItem.required:
195 desc = T.strong[desc]
196 yield desc
197 nextItem = next(fieldIter)
198 yield ', '
199 except StopIteration:
200 pass
201
202 return T.transparent["enables remote procedure calls through the"
203 " slightly aged SOAP mechanism; to use it,"
204 " feed the WSDL URL "+
205 service.getURL("soap")+"/go?wsdl"+
206 " to your SOAP library; the function signature is"
207 " useService(",
208 generateArguments(),
209 "). See also our ",
210 T.a(render="rootlink", href="/static/doc/soaplocal.shtml")[
211 "local soap hints"]]
212
213 @classmethod
214 def _explain_custom(cls, service):
215 res = T.transparent["a custom rendering of the service, typically"
216 " for interactive web applications."]
217 if svcs.getRenderer("custom").isBrowseable(service):
218 res[" See also the ",
219 T.a(href=service.getURL("custom"))["entry page"], "."]
220 return res
221
222 @classmethod
223 def _explain_static(cls, service):
224 return T.transparent["static (i.e. prepared) data or custom client-side"
225 " code; probably used to access ancillary files here"]
226
227
228 @classmethod
229 def _explain_text(cls, service):
230 return T.transparent["a text interface not intended for user"
231 " applications"]
232
233 @classmethod
234 def _explain_siap_xml(cls, service):
235 return T.transparent["a standard SIAP interface as defined by the"
236 " IVOA to access collections of celestial images; SIAP clients"
237 " use ", service.getURL("siap.xml"), " to access the service",
238 T.transparent(render="ifadmin")[" – ",
239 T.a(href="http://voparis-validator.obspm.fr/validator.php?"
240 "spec=Simple+Image+Access+1.0"
241 "&format=XHTML&batch=yes"
242 +"&serviceURL=%s"%urllib.parse.quote(service.getURL("siap.xml"))
243 +"&POS=%s%%2C%s&SIZE=%s%%2C%s&FORMAT=ALL"%(
244 base.getMetaText(service, "testQuery.pos.ra", default="180"),
245 base.getMetaText(service, "testQuery.pos.dec", default="60"),
246 base.getMetaText(service, "testQuery.size.ra", default="3"),
247 base.getMetaText(service, "testQuery.size.dec", default="3")))[
248 "Validate"]]]
249
250 @classmethod
251 def _explain_siap2_xml(cls, service):
252 return T.transparent["a standard SIAP version 2 interface as defined by the"
253 " IVOA to access collections of celestial images; SIAP clients"
254 " use ", service.getURL("siap2.xml"), " to access the service",
255 T.transparent(render="ifadmin")[" – ",
256 T.a(href="http://voparis-validator.obspm.fr/validator.php?"
257 "spec=Simple+Image+Access+2.0"
258 "&serviceURL=%s"%urllib.parse.quote(service.getURL("siap2.xml"))
259 +"&FOV=&BAND=&TIME=&POL=&SPATRES=&EXPTIME=&ID=&COLLECTION=&FACILITY=&INSTRUMENT=&DPTYPE=image&CALIB=&TARGET=&TIMERES=&SPECRP=&FORMAT=&MAXREC=&format=XHTML&REQUEST=query"
260 +"&POS=CIRCLE+{}+{}+{}".format(
261 base.getMetaText(service, "testQuery.pos.ra", default="180"),
262 base.getMetaText(service, "testQuery.pos.dec", default="60"),
263 base.getMetaText(service, "testQuery.size.ra", default="3")))[
264 "Validate"]]]
265
266 @classmethod
267 def _explain_scs_xml(cls, service):
268 return T.transparent["a standard SCS interface as defined by the"
269 " IVOA to access catalog-type data; SCS clients"
270 " use ", service.getURL("scs.xml"), " to access the service",
271 T.transparent(render="ifadmin")[" – ",
272 T.a(href="http://voparis-validator.obspm.fr/validator.php?"
273 "spec=Simple+Cone+Search+1.03"
274 "&format=XHTML&batch=yes"
275 +"&serviceURL=%s"%urllib.parse.quote(service.getURL("scs.xml"))
276 +"&RA=%s&DEC=%s&SR=%s&VERB=3"%(
277 base.getMetaText(service, "testQuery.ra", default="180"),
278 base.getMetaText(service, "testQuery.dec", default="60"),
279 base.getMetaText(service, "testQuery.sr", default="1")))[
280 "Validate"]]]
281
282 @classmethod
283 def _explain_ssap_xml(cls, service):
284 return T.transparent["a standard SSAP interface as defined by the"
285 " IVOA to access spectral or time-series data; SSAP clients"
286 " use ", service.getURL("ssap.xml"), " to access the service",
287 T.transparent(render="ifadmin")[" – ",
288 T.a(href="http://voparis-validator.obspm.fr/validator.php?"
289 "REQUEST=queryData&POS=&SIZE=&TIME=&BAND=&FORMAT=ALL"
290 "&VERSION=1.1&APERTURE=&SPECRP=&SPATRES=&TIMERES=&SNR="
291 "&REDSHIFT=&VARAMPL=&TARGETNAME=&TARGETCLASS=&FLUXCALIB=any"
292 "&WAVECALIB=any&PUBDID=&CREATORDID=&COLLECTION=&TOP=&MAXREC=1"
293 "&MTIME=&COMPRESS=true&RUNID=&spec=Simple+Spectral+Access+1.1"
294 "&format=XHTML"
295 +"&serviceURL=%s"%urllib.parse.quote(service.getURL("ssap.xml")))[
296 "Validate"]]]
297
298 @classmethod
299 def _explain_slap_xml(cls, service):
300 return T.transparent["a standard SLAP interface as defined by the"
301 " IVOA to access spectral line data; SLAP clients (usually"
302 " spectral analysis programs)"
303 " use ", service.getURL("slap.xml"), " to access the service",
304 T.transparent(render="ifadmin")[" – ",
305 T.a(href="http://voparis-validator.obspm.fr/validator.php?"
306 "REQUEST=queryData&spec=Simple+Line+Access+1.0"
307 "&format=XHTML"
308 "&addparams=MAXREC%3D1%26"
309 +"&serviceURL=%s"%urllib.parse.quote(service.getURL("slap.xml")))[
310 "Validate"]]]
311
312 @classmethod
313 def _explain_dali(cls, service):
314 return T.transparent["a complex interface consisting of multiple"
315 " endpoints (sync, async, perhaps tables or examples, and possibly"
316 " more). This is used, in particular, for TAP. You will usually need"
317 " a client programme to use this."
318 " In such clients, you can find this service by its"
319 " IVOID, ",
320 T.code(render="meta")["identifier"],
321 ", or access it by entering its base URL ",
322 T.code[service.getURL("dali")],
323 " directly. Using an XSL-enabled web browser you can, in a pinch,"
324 " also operate ",
325 T.a(href=service.getURL("async"))["the service"],
326 " asynchronously without a specialized client."]
327
328 @classmethod
329 def _explain_uws_xml(cls, service):
330 return T.transparent["a user-defined UWS service."
331 " This service is best accessed using specialized clients"
332 " or libraries. Give those its base URL ",
333 T.a(href=service.getURL("uws.xml"))[service.getURL("uws.xml")],
334 ". Using an XSL-enabled web browser you can"
335 " also click on the link above and operate the service 'manually'."
336 " For parameters and the output schema, see below."]
337
338 @classmethod
339 def _explain_pubreg_xml(cls, service):
340 return T.transparent["an interface for the OAI-PMH protocol, typically"
341 " this site's publishing registry (but possibly some other"
342 " registry-like thing). This endpoint is usually accessed"
343 " by harvesters, but with an XML-enabled browser you can"
344 " also try the access URL at ",
345 T.a(href=service.getURL("pubreg.xml"))[service.getURL("pubreg.xml")],
346 "."]
347
348 @classmethod
349 def _explain_qp(cls, service):
350 return T.transparent["an interface that uses the last path element"
351 " to query the column %s in the underlying table."%
352 service.getProperty("queryField", "defunct")]
353
354 @classmethod
355 def _explain_upload(cls, service):
356 return T.transparent["a ",
357 T.a(href=service.getURL("upload"))["form-based interface"],
358 " for uploading data"]
359
360 @classmethod
361 def _explain_dlget(cls, service):
362 return T.transparent["a datalink interface letting specialized clients"
363 " retrieve parts of datasets or discover related data. You"
364 " use this kind of service exclusively in combination with"
365 " a pubdid, usually via a direct link."]
366
367 @classmethod
368 def _explain_dlmeta(cls, service):
369 return T.transparent["a datalink interface for discovering access"
370 " options (processed data, related datasets...) for a dataset."
371 " You usually need a publisherDID to use this kind of service."
372 " For special applications, the base URL of this service might"
373 " still come handy: %s"%service.getURL("dlmeta")]
374
375 @classmethod
376 def _explain_dlasync(cls, service):
377 return T.transparent["an asynchronous interface to retrieving"
378 " processed data. This needs a special client that presumably"
379 " would first look at the dlmeta endpoint to discover what"
380 " processing options are available."]
381
382 @classmethod
383 def _explain_api(cls, service):
384 return T.transparent["an interface for operation with curl and"
385 " similar low-level tools. The endpoint is at ",
386 T.a(href=service.getURL("api"))[service.getURL("api")],
387 "; as usual for DALI-conforming services, parameters"
388 " an response structure is available by ",
389 T.a(href=service.getURL("api")+"MAXREC=0")["querying with"
390 " MAXREC=0"],
391 "."]
392
393 @classmethod
394 def _explain_coverage(cls, service):
395 return T.transparent["an interface to retrieve the spatial coverage"
396 " of this service. By default, this will return a FITS MOC,"
397 " but browsers and similar clients declaring they accept PNGs"
398 " will get a sky plot showing the coverage."]
399
400 @classmethod
401 def _explain_examples(cls, service):
402 return T.transparent["a list of examples for"
403 " how to use this resource. You can read ",
404 T.a(href=service.getURL("examples"))["the examples"],
405 " with your browser. RDFa-aware clients can figure out the"
406 " examples at ",
407 service.getURL("api")]
408
409 @classmethod
410 def _explain_hips(cls, service):
411 return T.transparent["a HiPS endpoint for fast zooming and panning"
412 " through in particular images. Paste the access URL ",
413 T.a(href=service.getURL("hips"))[service.getURL("hips")],
414 " into a HiPS client or click it when you have a javascript-"
415 "enabled browser."]
416
417 @classmethod
418 def _explain_biblinks_json(cls, service):
419 return T.transparent["an endpoint for harvesting pairs of"
420 " of bibliographic identifiers and dataset-related URLs."
421 " This is probably not interestering to you unless you"
422 " are the ADS. Retrieve the data from ",
423 T.a(href=service.getURL("biblinks.json"))[
424 service.getURL("biblinks.json")],
425 "."]
426
427 @classmethod
428 def _explain_edition(cls, service):
429 return T.transparent["a version of a document. See ",
430 T.a(href=service.getURL("edition"))[
431 service.getURL("edition")],
432 " for details."]
433
434 @classmethod
435 def _explainEverything(cls, service):
436 return T.transparent["a renderer with some custom access method that"
437 " should be mentioned in the service description"]
438
439 @classmethod
440 def explain(cls, renderer, service):
441 return getattr(cls, "_explain_"+renderer.replace(".", "_"),
442 cls._explainEverything)(service)
443
444
445 class ServiceInfoRenderer(MetaRenderer, utils.IdManagerMixin):
446 """A renderer showing all kinds of metadata on a service.
447
448 This renderer produces the default referenceURL page. To change its
449 appearance, override the serviceinfo.html template.
450 """
451 name = "info"
452
453 customTemplate = svcs.loadSystemTemplate("serviceinfo.html")
454
455 def __init__(self, *args, **kwargs):
456 grend.ServiceBasedPage.__init__(self, *args, **kwargs)
457 self.describingRD = self.service.rd
458 self.rawFootnotes = set()
459
460 @template.renderer
461 def title(self, request, tag):
462 return tag["Information on Service '%s'"%
463 base.getMetaText(self.service, "title")]
464
465 @template.renderer
466 def notebubble(self, request, tag):
467 if not tag.slotData["note"]:
468 return ""
469 id = tag.slotData["note"].tag
470 self.rawFootnotes.add(tag.slotData["note"])
471 return tag(href="#note-%s"%id)["Note %s"%id]
472
473 @template.renderer
474 def footnotes(self, request, tag):
475 """renders the footnotes as a definition list.
476 """
477 return T.dl(class_="footnotes")[[
478 T.xml(note.getContent(targetFormat="html"))
479 for note in sorted(self.rawFootnotes, key=lambda n: n.tag)]]
480
481 @template.renderer
482 def spectral_coverage(self, request, tag):
483 intervals = list(self.describingRD.iterMeta("coverage.spectral"))
484 if not intervals:
485 return ""
486
487 tag["Intervals of messenger energies reflected in this resource: "]
488 for m in intervals:
489 lower, upper = map(float, m.getContent().split())
490 # turn from Joule to eV
491 lower = utils.formatFloat(lower/base.ELECTRON_CHARGE)
492 upper = utils.formatFloat(upper/base.ELECTRON_CHARGE)
493 tag[f"{lower} {upper} eV", T.br]
494 return tag
495
496 @staticmethod
497 def _mjdToJYear(mjd):
498 return utils.formatFloat(
499 stc.dateTimeToJYear(
500 stc.mjdToDateTime(float(mjd))))
501
502 @template.renderer
503 def temporal_coverage(self, request, tag):
504 intervals = list(self.describingRD.iterMeta("coverage.temporal"))
505 if not intervals:
506 return ""
507
508 tag["Time covered by this resource's data: "]
509 for m in intervals:
510 lower, upper = m.getContent().split()
511 lower = self._mjdToJYear(lower)
512 upper = self._mjdToJYear(upper)
513 tag[f"{lower} {upper}", T.br]
514 return tag
515
516 def data_internalpath(self, request, tag):
517 return "%s/%s"%(self.service.rd.sourceId, self.service.id)
518
519 def data_inputFields(self, request, tag):
520 res = [f.asInfoDict() for f in self.service.getInputKeysFor("info")]
521 res.sort(key=lambda val: val["name"].lower())
522 return res
523
524 def data_htmlOutputFields(self, request, tag):
525 res = [f.asInfoDict() for f in self.service.getCurOutputFields()]
526 res.sort(key=lambda val: val["name"].lower())
527 return res
528
529 def data_votableOutputFields(self, request, tag):
530 queryMeta = svcs.QueryMeta({"_FORMAT": "VOTable", "_VERB": 3})
531 res = [f.asInfoDict() for f in self.service.getCurOutputFields(queryMeta)]
532 res.sort(key=lambda val: val["verbLevel"])
533 return res
534
535 def data_rendAvail(self, request, tag):
536 return [{"rendName": rend,
537 "rendExpl": RendExplainer.explain(rend, self.service)}
538 for rend in self.service.allowed]
539
540 def data_publications(self, request, tag):
541 res = [{"sets": ",".join(p.sets), "render": p.render}
542 for p in self.service.publications
543 if p.sets and p.render not in registry.HIDDEN_RENDERERS]
544 return sorted(res, key=lambda v: v["render"])
545
546 def data_browserURL(self, request, tag):
547 return self.service.getBrowserURL()
548
549 def data_service(self, request, tag):
550 return self.service
551
552 defaultLoader = common.doctypedStan(
553 T.html[
554 T.head[
555 T.title["Missing Template"]],
556 T.body[
557 T.p["Infos are only available with a serviceinfo.html template"]]
558 ])
559
560
561 class TableInfoRenderer(MetaRenderer):
562 """A renderer for displaying table information.
563
564 Since tables don't necessarily have associated services, this
565 renderer cannot use a service to sit on. Instead, the table is
566 being passed in as as an argument. There's a built-in vanity tableinfo
567 that sits on //dc_tables#show using this renderer (it could really
568 sit anywhere else).
569 """
570 name = "tableinfo"
571 customTemplate = svcs.loadSystemTemplate("tableinfo.html")
572
573 def render(self, request):
574 if not hasattr(self, "table"):
575 # _retrieveTableDef did not run, i.e., no tableName was given
576 raise svcs.UnknownURI(
577 "You must provide a table name to this renderer.")
578 self.macroPackage = self.table
579 self.metaCarrier = self.table
580 return super(TableInfoRenderer, self).render(request)
581
582 def _retrieveTableDef(self, tableName):
583 try:
584 self.tableName = tableName
585 self.table = registry.getTableDef(tableName)
586 self.describingRD = self.table.rd
587 except base.NotFoundError as msg:
588 raise base.ui.logOldExc(svcs.UnknownURI(str(msg)))
589
590 def data_forADQL(self, request, tag):
591 return self.table.adql
592
593 def data_fields(self, request, tag):
594 res = [f.asInfoDict() for f in self.table]
595 for d in res:
596 if d["note"]:
597 d["noteKey"] = d["note"].tag
598 if "alphaOrder" in request.strargs:
599 res.sort(key=lambda item: item["name"].lower())
600 return res
601
602 def data_internalpath(self, request, tag):
603 return "%s/%s"%(self.table.rd.sourceId, self.table.id)
604
605 @template.renderer
606 def title(self, request, tag):
607 return tag["Table information for '%s'"%self.tableName]
608
609 @template.renderer
610 def rdmeta(self, request, tag):
611 # rdmeta: Meta info at the table's rd (since there's ownmeta)
612 metaKey = tag.children[0]
613 tag.clear()
614 htmlBuilder = common.HTMLMetaBuilder(self.describingRD)
615 try:
616 return tag[self.describingRD.buildRepr(metaKey, htmlBuilder)]
617 except base.NoMetaKey:
618 return ""
619
620 @template.renderer
621 def ifrdmeta(self, metaName):
622 if self.describingRD.getMeta(metaName, propagate=False):
623 return lambda request, tag: tag
624 else:
625 return lambda request, tag: ""
626
627 @template.renderer
628 def iftapinfo(self, request, tag):
629 """renders the content if there was a tapinfo key somewhere in
630 the query string.
631 """
632 if "tapinfo" in request.strargs:
633 return tag
634 else:
635 return ""
636
637 def data_tableDef(self, request, tag):
638 return self.table
639
640 def getChild(self, name, request):
641 self._retrieveTableDef(name.decode("utf-8"))
642 return self
643
644 defaultLoader = common.doctypedStan(
645 T.html[
646 T.head[
647 T.title["Missing Template"]],
648 T.body[
649 T.p["Infos are only available with a tableinfo.html template"]]
650 ])
651
652
653 class TableNoteRenderer(MetaRenderer):
654 """A renderer for displaying table notes.
655
656 It takes a schema-qualified table name and a note tag in the segments.
657
658 This does not use the underlying service, so it could and will run on
659 any service. However, you really should run it on __system__/dc_tables/show,
660 and there's a built-in vanity name tablenote for this.
661 """
662 name = "tablenote"
663
664 def render(self, request):
665 if not hasattr(self, "noteTag"):
666 # _retrieveTableDef did not run, i.e., no tableName was given
667 raise svcs.UnknownURI(
668 "You must provide table name and note tag to this renderer.")
669 return super(TableNoteRenderer, self).render(request)
670
671 def _retrieveNote(self, tableName, noteTag):
672 try:
673 table = registry.getTableDef(tableName)
674 self.metaCarrier = table
675 self.renderedNote = table.getNote(noteTag
676 ).getContent(targetFormat="html", macroPackage=table)
677 except base.NotFoundError as msg:
678 raise base.ui.logOldExc(svcs.UnknownURI(msg))
679 self.noteTag = noteTag
680 self.tableName = tableName
681
682 def getChild(self, name, request):
683 segments = request.popSegments(name)
684
685 if len(segments)==2:
686 self._retrieveNote(segments[0], segments[1])
687 elif len(segments)==3: # segments[0] may be anything,
688 # but conventionally "inner"
689 self._retrieveNote(segments[1], segments[2])
690 self.loader = self.innerLoader
691 else:
692 raise svcs.UnknownURI("No such table note")
693 return self
694
695 def data_tableName(self, request, tag):
696 return self.tableName
697
698 def data_noteTag(self, request, tag):
699 return self.noteTag
700
701 @template.renderer
702 def noteHTML(self, request, tag):
703 return T.xml(self.renderedNote)
704
705 loader = formal.XMLString(r"""
706 <html xmlns="xmlns=http://www.w3.org/1999/xhtml"
707 xmlns:n="http://nevow.com/ns/nevow/0.1">
708 <head>
709 <title>\getConfig{web}{sitename} – Note for table
710 <n:invisible n:render="unicode" n:data="tableName"/></title>
711 <n:invisible n:render="commonhead"/>
712 <style>
713 span.target {font-size: 180%;font-weight:bold}
714 </style>
715 </head>
716 <body>
717 <n:invisible n:render="noteHTML"/>
718 </body>
719 </html>""")
720
721 innerLoader = template.TagLoader(
722 T.transparent(render="noteHTML"))
723
724
725 class HowToCiteRenderer(MetaRenderer):
726 """A renderer that lets you format citation instructions.
727 """
728 name = "howtocite"
729
730 customTemplate = svcs.loadSystemTemplate("howtocite.html")
731
732
733 class CoverageRenderer(MetaRenderer):
734 """A renderer returning various forms of a service's spatial coverage.
735
736 This will return a 404 if the service doesn't have a coverage.spatial
737 meta (and will bomb out if that isn't a SMoc).
738
739 Based on the accept header, it will return a PNG if the client
740 indicates it's interested in that or if it accepts text/html, in which
741 case we assume it's a browser; otherwise, it will produce a
742 MOC in FITS format.
743 """
744 name = "coverage"
745
746 def render(self, request):
747 from gavo.utils import pgsphere
748 try:
749 moc = pgsphere.SMoc.fromASCII(
750 self.service.getMeta(
751 "coverage.spatial", raiseOnFail=True).getContent())
752 except base.NoMetaKey:
753 raise svcs.UnknownURI(
754 "No spatial coverage available for this service.")
755
756 if self.returnAPNG(request):
757 request.setHeader("content-type", "image/png")
758 return moc.getPlot(xsize=400)
759
760 else:
761 request.setHeader("content-type", "application/fits")
762 return moc.asFITS()
763
764 @classmethod
765 def returnAPNG(self, request):
766 """returns true if request indicates we're being retrieved by
767 a web browser.
768 """
769 acceptDict = utils.parseAccept(request.getHeader("accept"))
770 return ("image/png" in acceptDict
771 or "image/webp" in acceptDict # firefox ~78 hack
772 or "image/*" in acceptDict
773 or "text/html" in acceptDict)
774
775 @classmethod
776 def isCacheable(cls, segments, request):
777 """only cache this if we return a PNG.
778
779 Our caching system doesn't support content negotiation, so we
780 can't keep the FITS (and it's fast to generate, so that doesn't
781 matter so much.
782 """
783 return cls.returnAPNG(request)
784
785
786 class EditionRenderer(MetaRenderer):
787 """A renderer representing a (tutorial-like) text document.
788
789 This must have a meta accessURL with the document URI. It may
790 have a sourceURL meta giving the VCS URI.
791 """
792 name = "edition"
793
794 @template.renderer
795 def title(self, request, tag):
796 return tag["Editions of “{}”".format(
797 base.getMetaText(self.metaCarrier, "title", default="unnamed document"))]
798
799 @template.renderer
800 def datameta(self, request, tag):
801 return self._doRenderMeta(request, tag, carrier=tag.slotData)
802
803 @template.renderer
804 def ifdatameta(self, metaName):
805 def _(request, tag):
806 if tag.slotData.getMeta(metaName) is not None:
807 return tag
808 else:
809 return ""
810 return _
811
812 @template.renderer
813 def accurl(self, request, tag):
814 url = base.getMetaText(tag.slotData, "accessURL")
815 return tag(href=url, class_="access-url")[url]
816
817 def data_editions(self, request, tag):
818 return self.metaCarrier.publications or []
819
820 defaultLoader = common.doctypedStan(
821 T.html[
822 T.head[
823 T.title(render="title"),
824 T.transparent(render="commonhead"),
825 ],
826 T.body(render="withsidebar")[
827 T.h1(render="title"),
828 T.p["The following editions of this document are available:"],
829 formal.addNevowAttributes(T.ul, data="editions")(render="sequence")[
830 formal.addNevowAttributes(T.li, pattern="item")[
831 T.a(render="accurl"),
832 T.transparent(render="ifdatameta locTitle") [
833 " with a localised title ",
834 T.em(render="datameta")["locTitle"]],
835 T.transparent(render="ifdatameta languageCode")[
836 " written in the BCP 47 language ",
837 T.em(class_="langcode", render="datameta")["languageCode"]],
838 ".",
839 T.transparent(render="ifdatameta sourceURL") [
840 " Source code available at ",
841 T.transparent(render="datameta")["sourceURL"]]]
842 ]]])
843
844
845 class ExternalRenderer(grend.ServiceBasedPage):
846 """A renderer redirecting to an external resource.
847
848 These try to access an external publication on the parent service
849 and ask it for an accessURL. If it doesn't define one, this will
850 lead to a redirect loop.
851
852 In the DC, external renderers are mainly used for registration of
853 third-party browser-based services.
854 """
855 name = "external"
856
857 @classmethod
858 def getExternalURL(cls, service):
859 """returns the URL this service should redirect to.
860 """
861 # look for a matching publication in the parent service...
862 for pub in service.publications:
863 if pub.render==cls.name:
864 break
865 else: # no publication, 404
866 raise svcs.UnknownURI("No publication for an external service here.")
867 return base.getMetaText(pub, "accessURL", macroPackage=service)
868
869 @classmethod
870 def isBrowseable(self, service):
871 try:
872 destSchema = self.getExternalURL(service).split(":")[0]
873 return destSchema in ("http", "https")
874 except Exception:
875 return False
876
877 def render(self, request):
878 raise svcs.WebRedirect(self.getExternalURL(self.service))
879
880
881 class VOEventRenderer(ExternalRenderer):
882 """A purely formal renderer only used for registering VOEventStreams.
883
884 VOEvent registration is done in a way that the individual interfaces
885 carry standard ids and would be the carriers of the actual protocols.
886 But we'll probably never have any of that in DaCHS, so actually,
887 this is only being used to link a renderer name and a standard id.
888 """
889 standardId = "ivo://ivoa.net/std/voevent"
890 name = "voevent"
891
892
893 class RDInfoPage(grend.CustomTemplateMixin, grend.ResourceBasedPage):
894 """A page giving infos about an RD.
895
896 This is not a renderer but a helper for RDInfoRenderer.
897 """
898 customTemplate = svcs.loadSystemTemplate("rdinfo.html")
899
900 def data_services(self, request, tag):
901 return sorted(self.rd.services,
902 key=lambda s: base.getMetaText(s, "title", default=s.id))
903
904 def data_tables(self, request, tag):
905 return sorted((t for t in self.rd.tables
906 if t.onDisk
907 and not t.temporary
908 and not t.hasProperty("internal")),
909 key=lambda t: t.id)
910
911 def data_otherrecs(self, request, tag):
912 return self.rd.resRecs
913
914 def data_clientRdId(self, request, tag):
915 return self.rd.sourceId
916
917 def _getDescriptionHTML(self, descItem):
918 """returns stan for the "description" of a service or a table.
919
920 The RD's description is not picked up.
921 """
922 iDesc = descItem.getMeta("description", propagate=False)
923 if iDesc is None:
924 return ""
925 else:
926 return T.div(class_="lidescription")[
927 T.xml(iDesc.getContent("blockhtml", macroPackage=descItem))]
928
929 @template.renderer
930 def rdsvc(self, request, tag):
931 service = tag.slotData
932 return tag[
933 T.a(href=service.getURL("info"))[
934 base.getMetaText(service, "title", default=service.id)],
935 self._getDescriptionHTML(service)]
936
937 @template.renderer
938 def rdtable(self, request, tag):
939 tableDef = tag.slotData
940 qName = tableDef.getQName()
941
942 adqlNote = ""
943 if tableDef.adql:
944 adqlNote = T.span(class_="adqlnote")[" ",
945 "–", " queryable through ",
946 T.a(href="/tap")["TAP"], " and ",
947 T.a(href="/adql")["ADQL"],
948 " "]
949
950 return tag[
951 T.a(href="/tableinfo/%s"%qName)[qName],
952 adqlNote,
953 self._getDescriptionHTML(tableDef)]
954
955 @classmethod
956 def makePageTitle(cls, rd):
957 """returns a suitable title for the rd info page.
958
959 This is a class method to allow other renderers to generate
960 titles for link anchors.
961 """
962 return "Information on resource '%s'"%base.getMetaText(
963 rd, "title", default="%s"%rd.sourceId)
964
965 @template.renderer
966 def title(self, request, tag):
967 return tag[self.makePageTitle(self.rd)]
968
969 defaultLoader = common.doctypedStan(
970 T.html[
971 T.head[
972 T.title["Missing Template"]],
973 T.body[
974 T.p["RD infos are only available with an rdinfo.html template"]]
975 ])
976
977
978 class RDInfoRenderer(grend.CustomTemplateMixin, grend.ServiceBasedPage):
979 """A renderer for displaying various properties about a resource descriptor.
980
981 This renderer could really be attached to any service since
982 it does not call it, but it usually lives on //services/overview.
983
984 By virtue of builtin vanity, you can reach the rdinfo renderer
985 at /browse, and thus you can access /browse/foo/q to view the RD infos.
986 This is the form used by table registrations.
987
988 In addition to all services, this renderer also links tableinfos
989 for all non-temporary, on-disk tables defined in the RD. When
990 you actually want to hide some internal on-disk tables, you can
991 set a property ``internal`` on the table (the value is ignored).
992 """
993 name = "rdinfo"
994 customTemplate = svcs.loadSystemTemplate("rdlist.html")
995
996 def data_publishedRDs(self, request, tag):
997 with base.getTableConn() as conn:
998 return [row[0] for row in
999 conn.query(
1000 """SELECT DISTINCT sourceRD
1001 FROM (
1002 SELECT sourceRD FROM dc.resources
1003 WHERE NOT deleted) as q
1004 ORDER BY sourceRD""")]
1005
1006 def getChild(self, name, request):
1007 rdId = "/".join(request.popSegments(name))
1008 if not rdId:
1009 raise svcs.WebRedirect("browse")
1010 clientRD = base.caches.getRD(rdId)
1011 return RDInfoPage(request, clientRD)
1012
1013 defaultLoader = common.doctypedStan(
1014 T.html[
1015 T.head[
1016 T.title["Missing Template"]],
1017 T.body[
1018 T.p["The RD list is only available with an rdlist.html template"]]
1019 ])
1020
1021
1022 class ResourceRecordMaker(resource.Resource):
1023 """A page that returns resource records for internal services.
1024
1025 This is basically like OAI-PMH getRecord, except we're using rd/id/svcid
1026 from our path.
1027
1028 Also (and that's fairly important for purx), this will use the
1029 _metadataUpdated meta for a modified header.
1030 """
1031 def render(self, request):
1032 raise svcs.UnknownURI("What resource record do you want?")
1033
1034 def getChild(self, name, request):
1035 from gavo.registry import builders
1036 segments = request.popSegments(name)
1037
1038 rdParts, svcId = segments[:-1], segments[-1]
1039 rdId = "/".join(rdParts)
1040 try:
1041 rd = base.caches.getRD(rdId)
1042 resob = rd.getById(svcId)
1043 except base.NotFoundError:
1044 raise svcs.UnknownURI("The resource %s#%s is unknown at this site."%(
1045 rdId, svcId))
1046
1047 timestampUpdated = utils.parseISODT(
1048 resob.getMeta("_metadataUpdated").getContent("text")).timestamp()
1049
1050 return common.TypedData(
1051 utils.xmlrender(
1052 builders.getVORMetadataElement(resob),
1053 prolog="<?xml version='1.0'?>"
1054 "<?xml-stylesheet href='/static/xsl/oai.xsl' type='text/xsl'?>",
1055 ),
1056 "application/xml",
1057 timestampUpdated)