| 1 |
""" |
| 2 |
Infrastructure pages. |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import datetime |
| 12 |
import io |
| 13 |
import os |
| 14 |
import pathlib |
| 15 |
import time |
| 16 |
|
| 17 |
import pkg_resources |
| 18 |
from twisted.internet import reactor |
| 19 |
from twisted.web import client |
| 20 |
from twisted.web import http |
| 21 |
from twisted.web import resource |
| 22 |
from twisted.web import server |
| 23 |
from twisted.web import static |
| 24 |
from twisted.web import template |
| 25 |
from twisted.web.template import tags as T |
| 26 |
|
| 27 |
from gavo import base |
| 28 |
from gavo import registry |
| 29 |
from gavo import svcs |
| 30 |
from gavo import utils |
| 31 |
from gavo.base import meta |
| 32 |
from gavo.base import sqlsupport |
| 33 |
from gavo.formal import nevowc |
| 34 |
from gavo.protocols import vocabularies |
| 35 |
from gavo.utils import stanxml |
| 36 |
from gavo.votable import V |
| 37 |
from gavo.web import common |
| 38 |
from gavo.web import caching |
| 39 |
from gavo.web import grend |
| 40 |
|
| 41 |
# prefer globally installed version to what we deliver |
| 42 |
try: |
| 43 |
import rjsmin |
| 44 |
except ImportError: |
| 45 |
from gavo.imp import rjsmin |
| 46 |
|
| 47 |
class LoginPage(nevowc.TemplatedPage, grend.GavoRenderMixin): |
| 48 |
"""a page that logs people in or out. |
| 49 |
|
| 50 |
You should usually give a nextURL parameter in the context, the page |
| 51 |
the user is returned to after login. |
| 52 |
|
| 53 |
If the user is already authenticated, this will do a logout (by |
| 54 |
sending a 403). |
| 55 |
""" |
| 56 |
@template.renderer |
| 57 |
def nextURL(self, request, tag): |
| 58 |
return tag(href=request.args.get("nextURL", ["/"])[0]) |
| 59 |
|
| 60 |
@template.renderer |
| 61 |
def iflogged(self, request, tag): |
| 62 |
if request.getUser(): |
| 63 |
return tag |
| 64 |
return "" |
| 65 |
|
| 66 |
@template.renderer |
| 67 |
def ifnotlogged(self, request, tag): |
| 68 |
if not request.getUser(): |
| 69 |
return tag |
| 70 |
return "" |
| 71 |
|
| 72 |
def data_loggedUser(self, request, tag): |
| 73 |
return request.getUser() |
| 74 |
|
| 75 |
def render(self, request): |
| 76 |
relogging = base.parseBooleanLiteral(utils.getfirst( |
| 77 |
request.strargs, "relog", default="False")) |
| 78 |
if request.getUser(): # user is logged in... |
| 79 |
if relogging: # ...and wants to log out: show login dialog... |
| 80 |
raise svcs.Authenticate() |
| 81 |
else: # ...and has just logged in: forward to destination |
| 82 |
raise svcs.SeeOther(str(request.URLPath().click( |
| 83 |
request.args.get(b"nextURL", [b"/"])[0]))) |
| 84 |
else: # user is not logged in |
| 85 |
if relogging: #...but was and has just logged out: forward to dest |
| 86 |
raise svcs.SeeOther(str(request.URLPath().click( |
| 87 |
request.args.get(b"nextURL", [b"/"])[0]))) |
| 88 |
else: # ... and wants to log in. |
| 89 |
raise svcs.Authenticate() |
| 90 |
|
| 91 |
loader = svcs.loadSystemTemplate("loginout.html") |
| 92 |
|
| 93 |
|
| 94 |
class TemplatedPage(grend.CustomTemplateMixin, grend.ServiceBasedPage): |
| 95 |
"""a "server-wide" template. |
| 96 |
|
| 97 |
For now, they all are based on the dc root service. |
| 98 |
""" |
| 99 |
checkedRenderer = False |
| 100 |
def __init__(self, request, fName): |
| 101 |
self.customTemplate = fName |
| 102 |
grend.ServiceBasedPage.__init__(self, request, |
| 103 |
base.caches.getRD(registry.SERVICELIST_ID |
| 104 |
).getById("root")) |
| 105 |
self.metaCarrier = meta.MetaMixin() |
| 106 |
self.metaCarrier.setMetaParent(self.service) |
| 107 |
if isinstance(fName, str): |
| 108 |
self.metaCarrier.setMeta("_dataUpdated", |
| 109 |
datetime.datetime.fromtimestamp(os.path.getmtime(fName))) |
| 110 |
|
| 111 |
|
| 112 |
def minifyJS(request, path): |
| 113 |
"""returns javascript in path minified. |
| 114 |
|
| 115 |
You can turn off auto-minification by setting [web] jsSource to True; |
| 116 |
that's sometimes convenient while debugging the javascript. |
| 117 |
|
| 118 |
If jsSource is false (the default), changes to javascript are only picked |
| 119 |
up on a server reload. |
| 120 |
""" |
| 121 |
with open(path, "rb") as f: |
| 122 |
if base.getConfig("web", "jsSource"): |
| 123 |
return f.read() |
| 124 |
else: |
| 125 |
return rjsmin.jsmin(f.read().decode("utf-8")).encode("utf-8") |
| 126 |
|
| 127 |
|
| 128 |
def expandTemplate(request, fName): |
| 129 |
"""renders fName as a template on the root service. |
| 130 |
""" |
| 131 |
return TemplatedPage(request, fName) |
| 132 |
|
| 133 |
|
| 134 |
class StaticFile(static.File): |
| 135 |
"""a file from the file system, served pretty directly. |
| 136 |
|
| 137 |
Some of these static files can be javascript (that's usually minified |
| 138 |
on the fly) or nevow templates. These we want to cache. For everything |
| 139 |
else, we don't win anything by caching, but, when we serve large data, |
| 140 |
we can DoS ourselves. So, we decide manually whether to cache. |
| 141 |
|
| 142 |
The caches are bound to an RD passed in as cacheRD at construction time. |
| 143 |
For system resources, that should be getRD(registry.SERVICELIST_ID). |
| 144 |
|
| 145 |
On-the-fly processing is based on certain magic mime types: |
| 146 |
text/nevow-template is rendered and application/javascript is minified. |
| 147 |
""" |
| 148 |
defaultType = "application/octet-stream" |
| 149 |
isLeaf = True |
| 150 |
|
| 151 |
processors = { |
| 152 |
".shtml": expandTemplate, |
| 153 |
".js": minifyJS, |
| 154 |
} |
| 155 |
|
| 156 |
def __init__(self, fName, cacheRD, defaultType="text/html"): |
| 157 |
self.cacheRD = cacheRD |
| 158 |
self.overriddenContent = None |
| 159 |
static.File.__init__(self, fName, defaultType=defaultType) |
| 160 |
|
| 161 |
def openForReading(self): |
| 162 |
if self.overriddenContent is None: |
| 163 |
return self.open() |
| 164 |
else: |
| 165 |
return io.BytesIO(self.overriddenContent) |
| 166 |
|
| 167 |
def getFileSize(self): |
| 168 |
if self.overriddenContent is None: |
| 169 |
return static.File.getFileSize(self) |
| 170 |
else: |
| 171 |
return len(self.overriddenContent) |
| 172 |
|
| 173 |
def render(self, request): |
| 174 |
modStamp = max(self.cacheRD.loadedAt, os.path.getmtime(self.path)) |
| 175 |
if request.setLastModified(modStamp) is http.CACHED: |
| 176 |
return b"" |
| 177 |
|
| 178 |
if not os.path.isfile(self.path): |
| 179 |
raise svcs.ForbiddenURI("Only plain files are served here") |
| 180 |
|
| 181 |
ext = os.path.splitext(self.path)[1] |
| 182 |
if ext in self.processors: |
| 183 |
cachedRes = caching.getFromRDCache( |
| 184 |
request, self.cacheRD, self.path.split("/")) |
| 185 |
if cachedRes is not None and cachedRes.creationStamp>modStamp: |
| 186 |
return cachedRes.render(request) |
| 187 |
|
| 188 |
processed = self.processors[ext](request, self.path) |
| 189 |
if hasattr(processed, "render"): |
| 190 |
return processed.render(request) |
| 191 |
else: |
| 192 |
self.overriddenContent = utils.bytify(processed) |
| 193 |
|
| 194 |
return static.File.render(self, request) |
| 195 |
|
| 196 |
|
| 197 |
class DirectoryLister(static.DirectoryLister): |
| 198 |
"""a directory listing -- we only have this here because some versions |
| 199 |
of t.w returned unicode strings here. |
| 200 |
""" |
| 201 |
def render(self, request): |
| 202 |
rtval = static.DirectoryLister.render(self, request) |
| 203 |
if isinstance(rtval, str): # pragma: no cover |
| 204 |
rtval = rtval.encode("utf-8") |
| 205 |
request.setHeader("content-type", "text/html;charset=utf-8") |
| 206 |
return rtval |
| 207 |
|
| 208 |
|
| 209 |
########### Begin Debian Fallbacks: If no local jquery and friends are |
| 210 |
# present (as happens when the official package is used) |
| 211 |
# several javascript libraries are taken from where Debian packages |
| 212 |
# put them. The URI path parts DaCHS sees them under are mapped to |
| 213 |
# the absolute path names or resource instances in DEBIAN_FALLBACKS. |
| 214 |
|
| 215 |
class GavoJquery(resource.Resource): |
| 216 |
"""synthesises a query-gavo.js from Debian packages. |
| 217 |
""" |
| 218 |
INSTALL_ROOT = "/usr/share/javascript/" |
| 219 |
PARTS = ["jquery/jquery.js", |
| 220 |
io.StringIO(""" |
| 221 |
(function( factory ) { |
| 222 |
if ( typeof define === "function" && define.amd ) { |
| 223 |
|
| 224 |
// AMD. Register as an anonymous module. |
| 225 |
define([ "jquery" ], factory ); |
| 226 |
} else { |
| 227 |
|
| 228 |
// Browser globals |
| 229 |
factory( jQuery ); |
| 230 |
} |
| 231 |
}(function( $ ) { |
| 232 |
|
| 233 |
$.ui = $.ui || {}; |
| 234 |
|
| 235 |
var version = $.ui.version = "1.12.1"; |
| 236 |
"""), |
| 237 |
"jquery-ui/ui/widget.js", |
| 238 |
"jquery-ui/ui/position.js", |
| 239 |
"jquery-ui/ui/data.js", |
| 240 |
"jquery-ui/ui/disable-selection.js", |
| 241 |
"jquery-ui/ui/focusable.js", |
| 242 |
"jquery-ui/ui/form-reset-mixin.js", |
| 243 |
"jquery-ui/ui/jquery-1-7.js", |
| 244 |
"jquery-ui/ui/keycode.js", |
| 245 |
"jquery-ui/ui/labels.js", |
| 246 |
"jquery-ui/ui/scroll-parent.js", |
| 247 |
"jquery-ui/ui/tabbable.js", |
| 248 |
"jquery-ui/ui/unique-id.js", |
| 249 |
"jquery-ui/ui/widgets/mouse.js", |
| 250 |
io.StringIO(""" |
| 251 |
var plugin = $.ui.plugin = { |
| 252 |
add: function( module, option, set ) { |
| 253 |
var i, |
| 254 |
proto = $.ui[ module ].prototype; |
| 255 |
for ( i in set ) { |
| 256 |
proto.plugins[ i ] = proto.plugins[ i ] || []; |
| 257 |
proto.plugins[ i ].push( [ option, set[ i ] ] ); |
| 258 |
} |
| 259 |
}, |
| 260 |
call: function( instance, name, args, allowDisconnected ) { |
| 261 |
var i, |
| 262 |
set = instance.plugins[ name ]; |
| 263 |
|
| 264 |
if ( !set ) { |
| 265 |
return; |
| 266 |
} |
| 267 |
|
| 268 |
if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || |
| 269 |
instance.element[ 0 ].parentNode.nodeType === 11 ) ) { |
| 270 |
return; |
| 271 |
} |
| 272 |
|
| 273 |
for ( i = 0; i < set.length; i++ ) { |
| 274 |
if ( instance.options[ set[ i ][ 0 ] ] ) { |
| 275 |
set[ i ][ 1 ].apply( instance.element, args ); |
| 276 |
} |
| 277 |
} |
| 278 |
} |
| 279 |
}; |
| 280 |
"""), |
| 281 |
"jquery-ui/ui/widgets/draggable.js", |
| 282 |
"jquery-ui/ui/widgets/resizable.js", |
| 283 |
"jquery-ui/ui/safe-active-element.js", |
| 284 |
"jquery-ui/ui/safe-blur.js", |
| 285 |
io.StringIO("}));"), |
| 286 |
] |
| 287 |
|
| 288 |
def __init__(self): |
| 289 |
self.content = None |
| 290 |
resource.Resource.__init__(self) |
| 291 |
|
| 292 |
def _getContent(self): |
| 293 |
parts = [] |
| 294 |
for part in self.PARTS: |
| 295 |
if hasattr(part, "read"): |
| 296 |
parts.append(part.read()) |
| 297 |
else: |
| 298 |
try: |
| 299 |
with open(os.path.join(self.INSTALL_ROOT, part), "r") as f: |
| 300 |
parts.append(f.read()) |
| 301 |
except IOError: |
| 302 |
# We don't worry about missing modules here; this lets |
| 303 |
# us accept multiple versions of the Debian packages |
| 304 |
# of jquery and jquery-ui. |
| 305 |
pass |
| 306 |
stuff = "\n".join(parts) |
| 307 |
|
| 308 |
self.modStamp = time.time() |
| 309 |
if base.getConfig("web", "jsSource"): |
| 310 |
return stuff |
| 311 |
else: |
| 312 |
return rjsmin.jsmin(stuff) |
| 313 |
|
| 314 |
def render(self, request): |
| 315 |
if self.content is None: |
| 316 |
self.content = self._getContent() |
| 317 |
|
| 318 |
if request.setLastModified(self.modStamp) is http.CACHED: |
| 319 |
return b'' |
| 320 |
request.setHeader("content-type", "text/javascript;charset=utf-8") |
| 321 |
|
| 322 |
return utils.bytify(self.content) |
| 323 |
|
| 324 |
|
| 325 |
DEBIAN_FALLBACKS = { |
| 326 |
'js/jquery-gavo.js': GavoJquery(), |
| 327 |
'js/jquery.flot.js': |
| 328 |
"/usr/share/javascript/jquery-flot/jquery.flot.js", |
| 329 |
} |
| 330 |
|
| 331 |
########### End Debian Fallbacks |
| 332 |
|
| 333 |
class StaticServer(resource.Resource): |
| 334 |
"""is a server for various static files. |
| 335 |
|
| 336 |
This is basically like static.File, except |
| 337 |
|
| 338 |
- we don't do directory listings |
| 339 |
- we don't bother with ranges |
| 340 |
- we look for each file in a user area and then in the system area. |
| 341 |
""" |
| 342 |
def __init__(self): |
| 343 |
resource.Resource.__init__(self) |
| 344 |
self.userPath = (base.getConfig("webDir") / "nv_static").resolve() |
| 345 |
self.systemPath = pathlib.Path( |
| 346 |
pkg_resources.resource_filename('gavo', "resources/web")).resolve() |
| 347 |
|
| 348 |
def render(self, request): |
| 349 |
raise svcs.UnknownURI("What did you expect here?") |
| 350 |
|
| 351 |
def getChild(self, name, request): |
| 352 |
relPath = "/".join(request.popSegments(name)) |
| 353 |
associatedRD = base.caches.getRD(registry.SERVICELIST_ID) |
| 354 |
|
| 355 |
# check in the user resources and our built-in files. |
| 356 |
for basePath in [self.userPath, self.systemPath]: |
| 357 |
try: |
| 358 |
path = (basePath / relPath).resolve(strict=True) |
| 359 |
except FileNotFoundError: |
| 360 |
# try next prefix |
| 361 |
continue |
| 362 |
|
| 363 |
if not str(path).startswith(str(basePath)): |
| 364 |
raise svcs.ForbiddenURI( |
| 365 |
f"{path} is not located in a published static directory") |
| 366 |
return common.compwrap(StaticFile(path, associatedRD)) |
| 367 |
|
| 368 |
# built-in magic for files we don't have in the Debian |
| 369 |
# package. |
| 370 |
if relPath in DEBIAN_FALLBACKS: |
| 371 |
res = DEBIAN_FALLBACKS[relPath] |
| 372 |
if isinstance(res, str): |
| 373 |
return common.compwrap(StaticFile(res, associatedRD)) |
| 374 |
else: |
| 375 |
return common.compwrap(res) |
| 376 |
|
| 377 |
raise svcs.UnknownURI("No matching file," |
| 378 |
" neither built-in nor user-provided") |
| 379 |
|
| 380 |
|
| 381 |
class SchemaServer(nevowc.TemplatedPage, common.CommonRenderers): |
| 382 |
"""a resource returning our built-in schema files. |
| 383 |
|
| 384 |
This exposes stanxml's NSRegistry, i.e., everything that's been |
| 385 |
introduced to DaCHS using registryPrefix at any point. |
| 386 |
|
| 387 |
This both reacts to prefixes and to the last segments of schema locations. |
| 388 |
|
| 389 |
This needs to look a bit deeper into stanxml.NSRegistry. As long |
| 390 |
as it's not operationally relevant, I'll accept using underscored |
| 391 |
names here. |
| 392 |
|
| 393 |
TODO: We actually have essentially all of these schema locally |
| 394 |
(except we don't necessarily know their canonical prefixes), but |
| 395 |
the NSRegistry so far only records locations on alnilam. We |
| 396 |
should probably return them from the local server. |
| 397 |
""" |
| 398 |
def data_schemadata(self, request, tag): |
| 399 |
return list( |
| 400 |
sorted(item for item in |
| 401 |
stanxml.NSRegistry._schemaLocations.items() |
| 402 |
if item[0] and item[1])) |
| 403 |
|
| 404 |
@template.renderer |
| 405 |
def schemalink(self, request, tag): |
| 406 |
# data is an item from schemadata |
| 407 |
return tag(href=tag.slotData[1])[tag.slotData[0]] |
| 408 |
|
| 409 |
def getChild(self, name, request): |
| 410 |
name = utils.debytify(name) |
| 411 |
try: |
| 412 |
_, loc = stanxml.NSRegistry.getPrefixInfo(name) |
| 413 |
raise svcs.Found(loc) |
| 414 |
except KeyError: |
| 415 |
# it's not a prefix, try to get a schema for it |
| 416 |
for loc in stanxml.NSRegistry._schemaLocations.values(): |
| 417 |
if loc and loc.split("/")[-1]==name: |
| 418 |
raise svcs.Found(loc) |
| 419 |
|
| 420 |
raise svcs.UnknownURI(f"'{name}' is neither a prefix nor a" |
| 421 |
" schema name known here") |
| 422 |
|
| 423 |
loader = common.doctypedStan( |
| 424 |
T.html[ |
| 425 |
T.head(render="commonhead")[ |
| 426 |
T.title["Schema files known here"]], |
| 427 |
T.body() [ |
| 428 |
T.h1["XML Schema Namespaces and Schemata known to DaCHS"], |
| 429 |
nevowc.addNevowAttributes( |
| 430 |
T.ul(render="sequence"), |
| 431 |
data="schemadata") [ |
| 432 |
nevowc.addNevowAttributes(T.li, pattern="item")[ |
| 433 |
T.a(render="schemalink")]]]]) |
| 434 |
|
| 435 |
|
| 436 |
class RobotsTxt(resource.Resource): |
| 437 |
"""A page combining some built-in robots.txt material with etc/robots.txt |
| 438 |
if it exists. |
| 439 |
""" |
| 440 |
is_leaf = True |
| 441 |
|
| 442 |
builtin = utils.fixIndentation(""" |
| 443 |
Disallow: /login |
| 444 |
Disallow: /seffe |
| 445 |
""", "") |
| 446 |
|
| 447 |
def _getContent(self): |
| 448 |
content = self.builtin |
| 449 |
try: |
| 450 |
with open(base.getConfig("webDir") / "robots.txt", |
| 451 |
encoding="utf-8") as f: |
| 452 |
content = content+"\n"+f.read() |
| 453 |
except IOError: |
| 454 |
pass |
| 455 |
return content |
| 456 |
|
| 457 |
def render(self, request): |
| 458 |
request.setHeader("content-type", "text/plain; charset=utf-8") |
| 459 |
return utils.bytify(self._getContent()) |
| 460 |
|
| 461 |
|
| 462 |
class ServiceUnavailable(resource.Resource): |
| 463 |
"""A page to be rendered in emergencies. |
| 464 |
|
| 465 |
Essentially, this is a 503 with a text taken from stateDir/MAINT. |
| 466 |
|
| 467 |
Root checks for the presence of that file before returning this |
| 468 |
page, so (ignoring race conditions) this page assumes it's there. |
| 469 |
""" |
| 470 |
def render(self, request): |
| 471 |
request.setResponseCode(503) |
| 472 |
request.setHeader("retry-after", "3600") |
| 473 |
|
| 474 |
with open( |
| 475 |
base.getConfig("stateDir") / "MAINT", |
| 476 |
"r", encoding="utf-8") as f: |
| 477 |
try: |
| 478 |
maintText = f.read() |
| 479 |
except Exception: |
| 480 |
maintText = "Botched MAINT file (utf-8 encoded? readable?)" |
| 481 |
|
| 482 |
vot = V.VOTABLE[ |
| 483 |
V.RESOURCE(type="results")[ |
| 484 |
V.INFO(name="QUERY_STATUS", value="ERROR")[ |
| 485 |
maintText] |
| 486 |
]] |
| 487 |
|
| 488 |
request.setHeader("content-type", "text/xml") |
| 489 |
return (b"<?xml-stylesheet href='/static" |
| 490 |
b"/xsl/mainterror-to-html.xsl' type='text/xsl'?>" |
| 491 |
+vot.render()) |
| 492 |
|
| 493 |
|
| 494 |
class ACMEChallenge(resource.Resource): |
| 495 |
"""A resource for letsencrypt and friends. |
| 496 |
""" |
| 497 |
acmeChallengeDir = base.getConfig("stateDir") / "acme-challenge" |
| 498 |
|
| 499 |
def render(self, request): |
| 500 |
# nobody has a reason to request a directory here |
| 501 |
raise svcs.ForbiddenURI("No listing of challenges") |
| 502 |
|
| 503 |
def getChild(self, name, request): |
| 504 |
fullPath = self.acmeChallengeDir / utils.debytify(name) |
| 505 |
if os.path.exists(fullPath): |
| 506 |
return static.File(fullPath) |
| 507 |
raise svcs.UnknownURI("No such challenge known here") |
| 508 |
|
| 509 |
|
| 510 |
class WellKnown(resource.Resource): |
| 511 |
"""A handler for the .well-known hierarchy. |
| 512 |
|
| 513 |
We only do something for ACME at this point. |
| 514 |
""" |
| 515 |
|
| 516 |
def getChild(self, name, request): |
| 517 |
if name==b"acme-challenge": |
| 518 |
return ACMEChallenge() |
| 519 |
|
| 520 |
elif name==b"security.txt": |
| 521 |
return StaticFile( |
| 522 |
base.getPathForDistFile("templates/security.txt"), |
| 523 |
base.caches.getRD("//services")) |
| 524 |
|
| 525 |
raise svcs.UnknownURI(f"{name} not supported in .well-known") |
| 526 |
|
| 527 |
|
| 528 |
class CurReaders(resource.Resource): |
| 529 |
"""A page returning an approximate number of clients served currently. |
| 530 |
|
| 531 |
This is actually surprisingly hard to compute or even estimate; and for |
| 532 |
what this is really intended to do -- indicate a safe time to restart --, |
| 533 |
running async operations, for instance, don't really matter, as they |
| 534 |
can be resumed. |
| 535 |
|
| 536 |
So, what I do to figure out how much is going on: look at how many |
| 537 |
database connections are taken from the untrusted and table connection |
| 538 |
pools (which are what the server uses). |
| 539 |
""" |
| 540 |
def render(self, request): |
| 541 |
nCheckedOut = 0 |
| 542 |
for manager in [ |
| 543 |
sqlsupport.getUntrustedConn, |
| 544 |
sqlsupport.getWritableUntrustedConn, |
| 545 |
sqlsupport.getTableConn, |
| 546 |
sqlsupport.getWritableTableConn]: |
| 547 |
if manager.pool: |
| 548 |
nCheckedOut += len(manager.pool[0]._used) |
| 549 |
|
| 550 |
request.setHeader("content-type", "text/plain") |
| 551 |
return utils.bytify(str(nCheckedOut)+"\n") |
| 552 |
|
| 553 |
|
| 554 |
class BlockMessage(resource.Resource): |
| 555 |
"""A resource handed out universally to people on web.root.BLOCKED_HOSTS. |
| 556 |
""" |
| 557 |
def render(self, request): |
| 558 |
try: |
| 559 |
with open( |
| 560 |
base.getConfig("stateDir") / "block-message.txt", |
| 561 |
encoding="utf-8") as f: |
| 562 |
content = f.read() |
| 563 |
except IOError: |
| 564 |
content = ("Sorry, you're blocked.\nThere should be an explanation," |
| 565 |
" but alas, there is none.\n") |
| 566 |
|
| 567 |
request.setHeader("content-type", "text/plain; charset=utf-8") |
| 568 |
return content.encode("utf-8") |
| 569 |
|
| 570 |
|
| 571 |
class Teapot(resource.Resource): |
| 572 |
# I simply wanted to have something in DaCHS that returns a 418. |
| 573 |
def render(self, request): |
| 574 |
request.setHeader("content-type", "text/plain") |
| 575 |
request.setResponseCode(418) |
| 576 |
return b"I'm a tea pot. Of course.\r\n" |
| 577 |
|
| 578 |
def getChild(self, name, request): |
| 579 |
return self |
| 580 |
|
| 581 |
|
| 582 |
class _ThirdPartyCacher(resource.Resource): |
| 583 |
"""A page used by ThirdPartyCachePage in case of cache misses. |
| 584 |
|
| 585 |
It is constructed with the key to ThirdPartyCachePage.urlMapping |
| 586 |
and the parent third party cache. |
| 587 |
""" |
| 588 |
def __init__(self, keyToGet, parent): |
| 589 |
self.keyToGet, self.parent = keyToGet, parent |
| 590 |
|
| 591 |
def render(self, request): |
| 592 |
retriever = client.Agent(reactor) |
| 593 |
d = retriever.request(b"GET", |
| 594 |
self.parent.urlMapping[self.keyToGet]) |
| 595 |
d.addCallback(self.startReadingRemote, request) |
| 596 |
d.addErrback(self.stopAndForget, request) |
| 597 |
return server.NOT_DONE_YET |
| 598 |
|
| 599 |
def startReadingRemote(self, response, request): |
| 600 |
"""arranges for the agent response to be cached and then served to |
| 601 |
request. |
| 602 |
""" |
| 603 |
reading = client.readBody(response) |
| 604 |
reading.addErrback(self.acceptPartialDownloads, request) |
| 605 |
reading.addCallback(self.saveAndServe, request) |
| 606 |
reading.addErrback(self.stopAndForget, request) |
| 607 |
return server.NOT_DONE_YET |
| 608 |
|
| 609 |
def acceptPartialDownloads(self, failure, request): |
| 610 |
"""An errback that lets us accept twisted's PartialDownloadError |
| 611 |
as a successful download. |
| 612 |
|
| 613 |
This needs to be added before startReadingRemote. |
| 614 |
""" |
| 615 |
failure.trap(client.PartialDownloadError) |
| 616 |
if failure.value.status==b'200': |
| 617 |
return failure.value.response |
| 618 |
return failure |
| 619 |
|
| 620 |
def saveAndServe(self, data, request): |
| 621 |
"""writes data to the cache for the current document and then |
| 622 |
serves that cache. |
| 623 |
""" |
| 624 |
with open(self.parent.getCacheName(self.keyToGet), "wb") as f: |
| 625 |
f.write(data) |
| 626 |
return self.serveFromCache(self.keyToGet, request) |
| 627 |
|
| 628 |
def stopAndForget(self, failure, request): |
| 629 |
return svcs.renderDCErrorPage(failure, request) |
| 630 |
|
| 631 |
def serveFromCache(self, name, request): |
| 632 |
"""writes the cached resource name to the request and finished it. |
| 633 |
|
| 634 |
If name isn't cached yet, this will raise a KeyError. |
| 635 |
""" |
| 636 |
res = self.parent.getFromCache(name) |
| 637 |
return res.render(request) |
| 638 |
|
| 639 |
|
| 640 |
class ThirdPartyCachePage(resource.Resource): |
| 641 |
"""A page returning third-party resources I don't want to distribute |
| 642 |
with DaCHS for a variety of reason. |
| 643 |
|
| 644 |
I still want them to come from the service itself, if only to |
| 645 |
keep the number of third-party requests down. |
| 646 |
|
| 647 |
These things are retrieved and cached on first access. They are |
| 648 |
removed on upgrades. |
| 649 |
""" |
| 650 |
# NOTE: this maps bytes to bytes! |
| 651 |
urlMapping = { |
| 652 |
b"aladin.min.js": |
| 653 |
b"https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.js", |
| 654 |
b"aladin.min.css": |
| 655 |
b"https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.css", |
| 656 |
} |
| 657 |
|
| 658 |
cacheDir = base.getConfig("cacheDir") / "3rdparty" |
| 659 |
|
| 660 |
def render(self, request): |
| 661 |
raise svcs.UnknownURI("No representation here") |
| 662 |
|
| 663 |
def getCacheName(self, name): |
| 664 |
"""returns the name of a file the resource name would be |
| 665 |
cached under. |
| 666 |
""" |
| 667 |
return self.cacheDir / utils.debytify(name) |
| 668 |
|
| 669 |
def getFromCache(self, name): |
| 670 |
"""returns a resource serving name if it's alreading in the cache, |
| 671 |
raises a KeyError if not. |
| 672 |
""" |
| 673 |
fn = self.getCacheName(name) |
| 674 |
if os.path.exists(fn): |
| 675 |
return static.File(fn) |
| 676 |
else: |
| 677 |
os.makedirs(self.cacheDir, exist_ok=True) |
| 678 |
raise KeyError(name) |
| 679 |
|
| 680 |
def getChild(self, name, request): |
| 681 |
if name not in self.urlMapping: |
| 682 |
raise svcs.UnknownURI(f"No cache rule for {name}") |
| 683 |
try: |
| 684 |
return self.getFromCache(name) |
| 685 |
except KeyError: |
| 686 |
# We'll have to retrieve the stuff yourselves. That'll be done |
| 687 |
# from the the render method |
| 688 |
return _ThirdPartyCacher(name, self) |
| 689 |
|
| 690 |
|
| 691 |
############### resources for the javascript-enabled root page |
| 692 |
# These once had a module of their own, which I didn't like. |
| 693 |
# Really, we'd like them in some RD, as they're really linked to |
| 694 |
# *some* resource. Aw. Never mind. |
| 695 |
|
| 696 |
# these are the fields necessary for formatting resource headers |
| 697 |
RESMETA_FIELDS = ("title, accessurl, referenceurl," |
| 698 |
" sourcerd, resid, owner, browseable") |
| 699 |
|
| 700 |
class Titles(common.JSONQuery): |
| 701 |
query = ( |
| 702 |
"SELECT "+RESMETA_FIELDS+ |
| 703 |
" FROM dc.resources" |
| 704 |
" NATURAL JOIN dc.interfaces" |
| 705 |
" NATURAL JOIN dc.sets" |
| 706 |
" WHERE setname='local'" |
| 707 |
" AND NOT deleted" |
| 708 |
" ORDER BY title") |
| 709 |
|
| 710 |
|
| 711 |
class Subjects(common.JSONQuery): |
| 712 |
def doQuery(self, queryArgs): |
| 713 |
res = common.JSONQuery.doQuery(self, queryArgs) |
| 714 |
uat = vocabularies.get_vocabulary("uat") |
| 715 |
for rec in res: |
| 716 |
rec["subject_label"] = vocabularies.get_label(uat, rec["subject"]) |
| 717 |
return res |
| 718 |
|
| 719 |
query = ( |
| 720 |
"SELECT subject, count(*) as numMatch" |
| 721 |
" FROM dc.subjects" |
| 722 |
" NATURAL JOIN dc.sets" |
| 723 |
" WHERE setname='local'" |
| 724 |
" AND NOT deleted" |
| 725 |
" GROUP BY subject" |
| 726 |
" ORDER BY subject") |
| 727 |
|
| 728 |
|
| 729 |
class Authors(common.JSONQuery): |
| 730 |
query = ( |
| 731 |
"SELECT author, count(*) as numMatch" |
| 732 |
" FROM dc.authors" |
| 733 |
" NATURAL JOIN dc.sets" |
| 734 |
" WHERE setname='local'" |
| 735 |
" AND NOT deleted" |
| 736 |
" GROUP BY author" |
| 737 |
" ORDER BY author") |
| 738 |
|
| 739 |
|
| 740 |
class ByFulltext(common.JSONQuery): |
| 741 |
query = ( |
| 742 |
"SELECT DISTINCT "+RESMETA_FIELDS+ |
| 743 |
" FROM dc.resources" |
| 744 |
" NATURAL JOIN dc.interfaces" |
| 745 |
" NATURAL JOIN dc.subjects" |
| 746 |
" NATURAL JOIN dc.sets" |
| 747 |
" WHERE setname='local'" |
| 748 |
" AND NOT deleted" |
| 749 |
" AND (to_tsvector('english', description) || to_tsvector(subject) " |
| 750 |
" || to_tsvector('english', title) || to_tsvector(authors))" |
| 751 |
" @@ plainto_tsquery(%(q)s)" |
| 752 |
" ORDER BY title") |
| 753 |
|
| 754 |
|
| 755 |
class BySubject(common.JSONQuery): |
| 756 |
query = ( |
| 757 |
"SELECT "+RESMETA_FIELDS+ |
| 758 |
" FROM dc.resources" |
| 759 |
" NATURAL JOIN dc.interfaces" |
| 760 |
" NATURAL JOIN dc.subjects" |
| 761 |
" NATURAL JOIN dc.sets" |
| 762 |
" WHERE setname='local'" |
| 763 |
" AND subject=%(subject)s" |
| 764 |
" AND NOT deleted" |
| 765 |
" ORDER BY title") |
| 766 |
|
| 767 |
|
| 768 |
class ByAuthor(common.JSONQuery): |
| 769 |
query = ( |
| 770 |
"SELECT "+RESMETA_FIELDS+ |
| 771 |
" FROM dc.resources" |
| 772 |
" NATURAL JOIN dc.interfaces" |
| 773 |
" NATURAL JOIN dc.authors" |
| 774 |
" NATURAL JOIN dc.sets" |
| 775 |
" WHERE setname='local'" |
| 776 |
" AND author=%(author)s" |
| 777 |
" AND NOT deleted" |
| 778 |
" ORDER BY title") |
| 779 |
|
| 780 |
|
| 781 |
class ServiceInfo(common.JSONQuery): |
| 782 |
query = ( |
| 783 |
"SELECT title, description, authors," |
| 784 |
" case when dateUpdated is null then 'N/A'" |
| 785 |
" else to_char(dateUpdated, 'YYYY-MM-DD') end as lastupdate," |
| 786 |
" referenceURL, accessURL" |
| 787 |
" FROM dc.interfaces" |
| 788 |
" NATURAL JOIN dc.sets" |
| 789 |
" RIGHT OUTER JOIN dc.resources USING (sourcerd, resid)" |
| 790 |
" WHERE setname='local'" |
| 791 |
" AND resId=%(resId)s and sourceRd=%(sourceRD)s") |
| 792 |
|
| 793 |
def doQuery(self, queryArgs): |
| 794 |
res = super().doQuery(queryArgs) |
| 795 |
for rec in res: |
| 796 |
try: |
| 797 |
rec["description"] = utils.rstxToHTML( |
| 798 |
(rec["description"] or "").strip()) |
| 799 |
except Exception: |
| 800 |
# well, perhaps it's no RST. Whatever it is, don't fail |
| 801 |
# but show what you have. |
| 802 |
pass |
| 803 |
return res |
| 804 |
|
| 805 |
|
| 806 |
ROOT_PAGE_HELPERS = resource.Resource() |
| 807 |
ROOT_PAGE_HELPERS.putChild(b"titles", Titles()) |
| 808 |
ROOT_PAGE_HELPERS.putChild(b"subjects", Subjects()) |
| 809 |
ROOT_PAGE_HELPERS.putChild(b"authors", Authors()) |
| 810 |
ROOT_PAGE_HELPERS.putChild(b"bySubject", BySubject()) |
| 811 |
ROOT_PAGE_HELPERS.putChild(b"byAuthor", ByAuthor()) |
| 812 |
ROOT_PAGE_HELPERS.putChild(b"byFulltext", ByFulltext()) |
| 813 |
ROOT_PAGE_HELPERS.putChild(b"serviceInfo", ServiceInfo()) |
| 814 |
|
| 815 |
|
| 816 |
if __name__=="__main__": |
| 817 |
# you can call this module to update jquery-gavo.js and jquery.flot.js |
| 818 |
# as is distributed in the tarball to what Debian gives upstream. |
| 819 |
# See develNotes.rstx in our docs. |
| 820 |
for path, data in DEBIAN_FALLBACKS.items(): |
| 821 |
if not path.startswith("js/"): |
| 822 |
continue |
| 823 |
if isinstance(data, str): |
| 824 |
with open(data, "rb") as f: |
| 825 |
payload = f.read() |
| 826 |
else: |
| 827 |
base.setConfig("web", "jsSource", "True") |
| 828 |
payload = data._getContent().encode("utf-8") |
| 829 |
|
| 830 |
with open(path[3:], "wb") as f: |
| 831 |
f.write(payload) |