frontend.py 2.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import os
  2. from pyramid.renderers import render_to_response
  3. from pyramid.config import Configurator
  4. from tracim_backend.extensions import APP_LIST
  5. from tracim_backend.exceptions import PageNotFound
  6. from tracim_backend.lib.core.application import ApplicationApi
  7. from tracim_backend.lib.utils.utils import Color
  8. from tracim_backend.views import BASE_API_V2
  9. from tracim_backend.lib.utils.request import TracimRequest
  10. from tracim_backend.views.controllers import Controller
  11. INDEX_PAGE_NAME = 'index.mak'
  12. APP_FRONTEND_PATH = 'app/{minislug}.app.js'
  13. class FrontendController(Controller):
  14. def __init__(self, dist_folder_path: str):
  15. self.dist_folder_path = dist_folder_path
  16. def _get_index_file_path(self):
  17. index_file_path = os.path.join(self.dist_folder_path, INDEX_PAGE_NAME)
  18. if not os.path.exists(index_file_path):
  19. raise FileNotFoundError()
  20. return index_file_path
  21. def not_found_view(self, context, request: TracimRequest):
  22. if request.path.startswith(BASE_API_V2):
  23. raise PageNotFound('{} is not a valid path'.format(request.path)) from context # nopep8
  24. return self.index(context, request)
  25. def index(self, context, request: TracimRequest):
  26. app_config = request.registry.settings['CFG']
  27. # TODO - G.M - 2018-08-07 - Refactor autogen valid app list for frontend
  28. frontend_apps = []
  29. app_api = ApplicationApi(
  30. app_list=APP_LIST,
  31. )
  32. applications = app_api.get_all()
  33. for app in applications:
  34. app_frontend_path = APP_FRONTEND_PATH.replace('{minislug}',
  35. app.minislug) # nopep8
  36. app_path = os.path.join(self.dist_folder_path,
  37. app_frontend_path) # nopep8
  38. if os.path.exists(app_path):
  39. frontend_apps.append(app)
  40. return render_to_response(
  41. self._get_index_file_path(),
  42. {
  43. 'colors': {
  44. 'primary': Color(app_config.APPS_COLORS['primary']),
  45. },
  46. 'applications': frontend_apps,
  47. }
  48. )
  49. def bind(self, configurator: Configurator) -> None:
  50. configurator.add_notfound_view(self.not_found_view)
  51. # index.html for /index.html and /
  52. configurator.add_route('root', '/', request_method='GET')
  53. configurator.add_view(self.index, route_name='root')
  54. configurator.add_route('index', INDEX_PAGE_NAME, request_method='GET')
  55. configurator.add_view(self.index, route_name='index')
  56. for dirname in os.listdir(self.dist_folder_path):
  57. configurator.add_static_view(
  58. name=dirname,
  59. path=os.path.join(self.dist_folder_path, dirname)
  60. )