Files
replypier/backend/app/api/channels/line.py
T
WangShen007 20fef2b9f3 chore: settle product naming across app, widget and deployments
One word everywhere: ReplyPier in UI copy, package and image names, the
replypier.site domains (app/api/docs/help), REPLYPIER_* settings and the
--rp-* design tokens.

- public widget API is window.ReplyPier with replypierId / replypierBaseUrl /
  replypierConfig / replypierToken, loader at webclient/replypier.min.js;
  both bundles rebuilt from source
- NOTICE, llms.txt, CONTRIBUTING, HELP_CENTER_INFRA and the demo runtime
  config rewritten; the demo config ships no third-party keys
- migration adds the ReplyPier managed model value to the AI model enum
- local compose project, database, role, volume and Docker network carry the
  same name
2026-10-26 00:57:22 +08:00

96 lines
3.8 KiB
Python

"""
Copyright 2024-2026 ReplyPier
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api.channels.accounts import get_org_account_or_404, to_account_out
from app.channels import line as line_api
from app.core.auth import get_current_organization, require_permissions
from app.core.config import settings
from app.database import get_db
from app.models.channels import ChannelType
from app.models.organization import Organization
from app.models.schemas.channel import ChannelAccountOut, LineConnectRequest
from app.models.user import User
from app.repositories.channels import ChannelAccountRepository
from app.core.logger import get_logger
router = APIRouter()
logger = get_logger(__name__)
def _webhook_url(account_id) -> str:
return f"{settings.BACKEND_URL.rstrip('/')}{settings.API_V1_STR}/webhooks/line/{account_id}"
@router.post("", response_model=ChannelAccountOut)
async def connect_line(
request: LineConnectRequest,
current_user: User = Depends(require_permissions("manage_organization")),
organization: Organization = Depends(get_current_organization),
db: Session = Depends(get_db),
):
"""Connect a LINE Official Account (channel secret + access token from the
LINE Developers console). The webhook endpoint is set automatically."""
bot = await line_api.get_bot_info(request.channel_access_token.strip())
if bot is None:
raise HTTPException(status_code=400, detail="Invalid LINE channel access token")
bot_user_id = str(bot.get("userId", ""))
credentials = {
"channel_access_token": request.channel_access_token.strip(),
"channel_secret": request.channel_secret.strip(),
}
repo = ChannelAccountRepository(db)
existing = repo.get_by_external_id(ChannelType.LINE.value, bot_user_id)
if existing is not None:
if existing.organization_id != organization.id:
raise HTTPException(status_code=409, detail="This LINE account is already connected to another organization")
repo.update_credentials(existing, credentials)
account = repo.set_active(existing, True)
else:
account = repo.create_account(
organization_id=organization.id,
channel_type=ChannelType.LINE.value,
external_account_id=bot_user_id,
credentials=credentials,
display_name=bot.get("displayName") or bot.get("basicId") or bot_user_id,
)
if not await line_api.set_webhook_endpoint(credentials["channel_access_token"], _webhook_url(account.id)):
logger.warning(f"LINE webhook auto-set failed for {account.id}; set it manually in the console")
out = to_account_out(db, account)
out.webhook_url = _webhook_url(account.id)
return out
@router.delete("/{account_id}")
async def disconnect_line(
account_id: UUID,
current_user: User = Depends(require_permissions("manage_organization")),
organization: Organization = Depends(get_current_organization),
db: Session = Depends(get_db),
):
account = get_org_account_or_404(db, account_id, organization)
if account.channel_type != ChannelType.LINE.value:
raise HTTPException(status_code=404, detail="Channel account not found")
ChannelAccountRepository(db).delete(account)
return {"status": "disconnected"}