v1_api.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. __package__ = 'archivebox.api'
  2. from io import StringIO
  3. from traceback import format_exception
  4. from contextlib import redirect_stdout, redirect_stderr
  5. from django.http import HttpRequest, HttpResponse
  6. from django.core.exceptions import ObjectDoesNotExist, EmptyResultSet, PermissionDenied
  7. from ninja import NinjaAPI, Swagger
  8. # TODO: explore adding https://eadwincode.github.io/django-ninja-extra/
  9. from archivebox.config import VERSION
  10. from archivebox.config.version import get_COMMIT_HASH
  11. from api.auth import API_AUTH_METHODS
  12. COMMIT_HASH = get_COMMIT_HASH() or 'unknown'
  13. html_description=f'''
  14. <h3>Welcome to your ArchiveBox server's REST API <code>[v1 ALPHA]</code> homepage!</h3>
  15. <br/>
  16. <i><b>WARNING: This API is still in an early development stage and may change!</b></i>
  17. <br/>
  18. <ul>
  19. <li>⬅️ Manage your server: <a href="/admin/api/"><b>Setup API Keys</b></a>, <a href="/admin/">Go to your Server Admin UI</a>, <a href="/">Go to your Snapshots list</a>
  20. <li>💬 Ask questions and get help here: <a href="https://zulip.archivebox.io">ArchiveBox Chat Forum</a></li>
  21. <li>🐞 Report API bugs here: <a href="https://github.com/ArchiveBox/ArchiveBox/issues">Github Issues</a></li>
  22. <li>📚 ArchiveBox Documentation: <a href="https://github.com/ArchiveBox/ArchiveBox/wiki">Github Wiki</a></li>
  23. <li>📜 See the API source code: <a href="https://github.com/ArchiveBox/ArchiveBox/blob/dev/archivebox/api"><code>archivebox/api/</code></a></li>
  24. </ul>
  25. <small>Served by ArchiveBox v{VERSION} (<a href="https://github.com/ArchiveBox/ArchiveBox/commit/{COMMIT_HASH}"><code>{COMMIT_HASH[:8]}</code></a>), API powered by <a href="https://django-ninja.dev/"><code>django-ninja</code></a>.</small>
  26. '''
  27. def register_urls(api: NinjaAPI) -> NinjaAPI:
  28. api.add_router('/auth/', 'api.v1_auth.router')
  29. api.add_router('/core/', 'api.v1_core.router')
  30. api.add_router('/cli/', 'api.v1_cli.router')
  31. api.add_router('/jobs/', 'api.v1_actors.router')
  32. return api
  33. class NinjaAPIWithIOCapture(NinjaAPI):
  34. def create_temporal_response(self, request: HttpRequest) -> HttpResponse:
  35. stdout, stderr = StringIO(), StringIO()
  36. with redirect_stderr(stderr):
  37. with redirect_stdout(stdout):
  38. request.stdout = stdout
  39. request.stderr = stderr
  40. response = super().create_temporal_response(request)
  41. # Diable caching of API responses entirely
  42. response['Cache-Control'] = 'no-store'
  43. # Add debug stdout and stderr headers to response
  44. response['X-ArchiveBox-Stdout'] = str(request.stdout)[200:]
  45. response['X-ArchiveBox-Stderr'] = str(request.stderr)[200:]
  46. # response['X-ArchiveBox-View'] = self.get_openapi_operation_id(request) or 'Unknown'
  47. # Add Auth Headers to response
  48. api_token = getattr(request, '_api_token', None)
  49. token_expiry = api_token.expires.isoformat() if api_token and api_token.expires else 'Never'
  50. response['X-ArchiveBox-Auth-Method'] = getattr(request, '_api_auth_method', None) or 'None'
  51. response['X-ArchiveBox-Auth-Expires'] = token_expiry
  52. response['X-ArchiveBox-Auth-Token-Id'] = api_token.abid if api_token else 'None'
  53. response['X-ArchiveBox-Auth-User-Id'] = request.user.pk if request.user.pk else 'None'
  54. response['X-ArchiveBox-Auth-User-Username'] = request.user.username if request.user.pk else 'None'
  55. # import ipdb; ipdb.set_trace()
  56. # print('RESPONDING NOW', response)
  57. return response
  58. api = NinjaAPIWithIOCapture(
  59. title='ArchiveBox API',
  60. description=html_description,
  61. version='1.0.0',
  62. csrf=False,
  63. auth=API_AUTH_METHODS,
  64. urls_namespace="api-1",
  65. docs=Swagger(settings={"persistAuthorization": True}),
  66. # docs_decorator=login_required,
  67. # renderer=ORJSONRenderer(),
  68. )
  69. api = register_urls(api)
  70. urls = api.urls
  71. @api.exception_handler(Exception)
  72. def generic_exception_handler(request, err):
  73. status = 503
  74. if isinstance(err, (ObjectDoesNotExist, EmptyResultSet, PermissionDenied)):
  75. status = 404
  76. print(''.join(format_exception(err)))
  77. return api.create_response(
  78. request,
  79. {
  80. "succeeded": False,
  81. "message": f'{err.__class__.__name__}: {err}',
  82. "errors": [
  83. ''.join(format_exception(err)),
  84. # or send simpler parent-only traceback:
  85. # *([str(err.__context__)] if getattr(err, '__context__', None) else []),
  86. ],
  87. },
  88. status=status,
  89. )
  90. # import orjson
  91. # from ninja.renderers import BaseRenderer
  92. # class ORJSONRenderer(BaseRenderer):
  93. # media_type = "application/json"
  94. # def render(self, request, data, *, response_status):
  95. # return {
  96. # "success": True,
  97. # "errors": [],
  98. # "result": data,
  99. # "stdout": ansi_to_html(stdout.getvalue().strip()),
  100. # "stderr": ansi_to_html(stderr.getvalue().strip()),
  101. # }
  102. # return orjson.dumps(data)