Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import logging
  2. from datetime import UTC, datetime
  3. from typing import Any
  4. from flask import request
  5. from flask_login import current_user
  6. from flask_restful import Resource, inputs, marshal_with, reqparse
  7. from sqlalchemy import and_
  8. from werkzeug.exceptions import BadRequest, Forbidden, NotFound
  9. from controllers.console import api
  10. from controllers.console.explore.wraps import InstalledAppResource
  11. from controllers.console.wraps import account_initialization_required, cloud_edition_billing_resource_check
  12. from extensions.ext_database import db
  13. from fields.installed_app_fields import installed_app_list_fields
  14. from libs.login import login_required
  15. from models import App, InstalledApp, RecommendedApp
  16. from services.account_service import TenantService
  17. from services.app_service import AppService
  18. from services.enterprise.enterprise_service import EnterpriseService
  19. from services.feature_service import FeatureService
  20. logger = logging.getLogger(__name__)
  21. class InstalledAppsListApi(Resource):
  22. @login_required
  23. @account_initialization_required
  24. @marshal_with(installed_app_list_fields)
  25. def get(self):
  26. app_id = request.args.get("app_id", default=None, type=str)
  27. current_tenant_id = current_user.current_tenant_id
  28. if app_id:
  29. installed_apps = (
  30. db.session.query(InstalledApp)
  31. .filter(and_(InstalledApp.tenant_id == current_tenant_id, InstalledApp.app_id == app_id))
  32. .all()
  33. )
  34. else:
  35. installed_apps = db.session.query(InstalledApp).filter(InstalledApp.tenant_id == current_tenant_id).all()
  36. current_user.role = TenantService.get_user_role(current_user, current_user.current_tenant)
  37. installed_app_list: list[dict[str, Any]] = [
  38. {
  39. "id": installed_app.id,
  40. "app": installed_app.app,
  41. "app_owner_tenant_id": installed_app.app_owner_tenant_id,
  42. "is_pinned": installed_app.is_pinned,
  43. "last_used_at": installed_app.last_used_at,
  44. "editable": current_user.role in {"owner", "admin"},
  45. "uninstallable": current_tenant_id == installed_app.app_owner_tenant_id,
  46. }
  47. for installed_app in installed_apps
  48. if installed_app.app is not None
  49. ]
  50. # filter out apps that user doesn't have access to
  51. if FeatureService.get_system_features().webapp_auth.enabled:
  52. user_id = current_user.id
  53. res = []
  54. for installed_app in installed_app_list:
  55. app_code = AppService.get_app_code_by_id(str(installed_app["app"].id))
  56. if EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp(
  57. user_id=user_id,
  58. app_code=app_code,
  59. ):
  60. res.append(installed_app)
  61. installed_app_list = res
  62. logger.debug(f"installed_app_list: {installed_app_list}, user_id: {user_id}")
  63. installed_app_list.sort(
  64. key=lambda app: (
  65. -app["is_pinned"],
  66. app["last_used_at"] is None,
  67. -app["last_used_at"].timestamp() if app["last_used_at"] is not None else 0,
  68. )
  69. )
  70. return {"installed_apps": installed_app_list}
  71. @login_required
  72. @account_initialization_required
  73. @cloud_edition_billing_resource_check("apps")
  74. def post(self):
  75. parser = reqparse.RequestParser()
  76. parser.add_argument("app_id", type=str, required=True, help="Invalid app_id")
  77. args = parser.parse_args()
  78. recommended_app = db.session.query(RecommendedApp).filter(RecommendedApp.app_id == args["app_id"]).first()
  79. if recommended_app is None:
  80. raise NotFound("App not found")
  81. current_tenant_id = current_user.current_tenant_id
  82. app = db.session.query(App).filter(App.id == args["app_id"]).first()
  83. if app is None:
  84. raise NotFound("App not found")
  85. if not app.is_public:
  86. raise Forbidden("You can't install a non-public app")
  87. installed_app = (
  88. db.session.query(InstalledApp)
  89. .filter(and_(InstalledApp.app_id == args["app_id"], InstalledApp.tenant_id == current_tenant_id))
  90. .first()
  91. )
  92. if installed_app is None:
  93. # todo: position
  94. recommended_app.install_count += 1
  95. new_installed_app = InstalledApp(
  96. app_id=args["app_id"],
  97. tenant_id=current_tenant_id,
  98. app_owner_tenant_id=app.tenant_id,
  99. is_pinned=False,
  100. last_used_at=datetime.now(UTC).replace(tzinfo=None),
  101. )
  102. db.session.add(new_installed_app)
  103. db.session.commit()
  104. return {"message": "App installed successfully"}
  105. class InstalledAppApi(InstalledAppResource):
  106. """
  107. update and delete an installed app
  108. use InstalledAppResource to apply default decorators and get installed_app
  109. """
  110. def delete(self, installed_app):
  111. if installed_app.app_owner_tenant_id == current_user.current_tenant_id:
  112. raise BadRequest("You can't uninstall an app owned by the current tenant")
  113. db.session.delete(installed_app)
  114. db.session.commit()
  115. return {"result": "success", "message": "App uninstalled successfully"}, 204
  116. def patch(self, installed_app):
  117. parser = reqparse.RequestParser()
  118. parser.add_argument("is_pinned", type=inputs.boolean)
  119. args = parser.parse_args()
  120. commit_args = False
  121. if "is_pinned" in args:
  122. installed_app.is_pinned = args["is_pinned"]
  123. commit_args = True
  124. if commit_args:
  125. db.session.commit()
  126. return {"result": "success", "message": "App info updated successfully"}
  127. api.add_resource(InstalledAppsListApi, "/installed-apps")
  128. api.add_resource(InstalledAppApi, "/installed-apps/<uuid:installed_app_id>")