Compare commits
1 Commits
main
...
8d3d1c121c
Author | SHA1 | Date | |
---|---|---|---|
8d3d1c121c
|
60
.claude/settings.local.json
Normal file
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(cargo init:*)",
|
||||
"Bash(cargo:*)",
|
||||
"Bash(find:*)",
|
||||
"Bash(mkdir:*)",
|
||||
"Bash(../target/debug/ailog new:*)",
|
||||
"Bash(../target/debug/ailog build)",
|
||||
"Bash(/Users/syui/ai/log/target/debug/ailog build)",
|
||||
"Bash(ls:*)",
|
||||
"Bash(curl:*)",
|
||||
"Bash(pkill:*)",
|
||||
"WebFetch(domain:docs.anthropic.com)",
|
||||
"WebFetch(domain:github.com)",
|
||||
"Bash(rm:*)",
|
||||
"Bash(mv:*)",
|
||||
"Bash(cp:*)",
|
||||
"Bash(timeout:*)",
|
||||
"Bash(grep:*)",
|
||||
"Bash(./target/debug/ailog:*)",
|
||||
"Bash(cat:*)",
|
||||
"Bash(npm install)",
|
||||
"Bash(npm run build:*)",
|
||||
"Bash(chmod:*)",
|
||||
"Bash(./scripts/tunnel.sh:*)",
|
||||
"Bash(PRODUCTION=true cargo run -- build)",
|
||||
"Bash(cloudflared tunnel:*)",
|
||||
"Bash(npm install:*)",
|
||||
"Bash(./scripts/build-oauth-partial.zsh:*)",
|
||||
"Bash(./scripts/quick-oauth-update.zsh:*)",
|
||||
"Bash(../target/debug/ailog serve)",
|
||||
"Bash(./scripts/test-oauth.sh:*)",
|
||||
"Bash(./run.zsh:*)",
|
||||
"Bash(npm run dev:*)",
|
||||
"Bash(./target/release/ailog:*)",
|
||||
"Bash(rg:*)",
|
||||
"Bash(../target/release/ailog build)",
|
||||
"Bash(zsh run.zsh:*)",
|
||||
"Bash(hugo:*)",
|
||||
"WebFetch(domain:docs.bsky.app)",
|
||||
"WebFetch(domain:syui.ai)",
|
||||
"Bash(rustup target list:*)",
|
||||
"Bash(rustup target:*)",
|
||||
"Bash(git add:*)",
|
||||
"Bash(git commit:*)",
|
||||
"Bash(git push:*)",
|
||||
"Bash(git tag:*)",
|
||||
"Bash(../bin/ailog:*)",
|
||||
"Bash(../target/release/ailog oauth build:*)",
|
||||
"Bash(ailog:*)",
|
||||
"WebFetch(domain:plc.directory)",
|
||||
"WebFetch(domain:atproto.com)",
|
||||
"WebFetch(domain:syu.is)",
|
||||
"Bash(sed:*)",
|
||||
"Bash(./scpt/run.zsh:*)"
|
||||
],
|
||||
"deny": []
|
||||
}
|
||||
}
|
@@ -1,123 +0,0 @@
|
||||
name: Deploy to Cloudflare Pages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
OAUTH_DIR: oauth
|
||||
KEEP_DEPLOYMENTS: 5
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
deployments: write
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '21'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd ${{ env.OAUTH_DIR }}
|
||||
npm install
|
||||
|
||||
- name: Build OAuth app
|
||||
run: |
|
||||
cd ${{ env.OAUTH_DIR }}
|
||||
NODE_ENV=production npm run build
|
||||
- name: Copy OAuth build to static
|
||||
run: |
|
||||
rm -rf my-blog/static/assets
|
||||
cp -rf ${{ env.OAUTH_DIR }}/dist/* my-blog/static/
|
||||
cp ${{ env.OAUTH_DIR }}/dist/index.html my-blog/templates/oauth-assets.html
|
||||
|
||||
- name: Cache ailog binary
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ./bin
|
||||
key: ailog-bin-${{ runner.os }}
|
||||
restore-keys: |
|
||||
ailog-bin-${{ runner.os }}
|
||||
|
||||
- name: Setup ailog binary
|
||||
run: |
|
||||
# Get expected version from Cargo.toml
|
||||
EXPECTED_VERSION=$(grep '^version' Cargo.toml | cut -d'"' -f2)
|
||||
echo "Expected version from Cargo.toml: $EXPECTED_VERSION"
|
||||
|
||||
# Check current binary version if exists
|
||||
if [ -f "./bin/ailog" ]; then
|
||||
CURRENT_VERSION=$(./bin/ailog --version 2>/dev/null || echo "unknown")
|
||||
echo "Current binary version: $CURRENT_VERSION"
|
||||
else
|
||||
CURRENT_VERSION="none"
|
||||
echo "No binary found"
|
||||
fi
|
||||
|
||||
# Check OS
|
||||
OS="${{ runner.os }}"
|
||||
echo "Runner OS: $OS"
|
||||
|
||||
# Use pre-packaged binary if version matches or extract from tar.gz
|
||||
if [ "$CURRENT_VERSION" = "$EXPECTED_VERSION" ]; then
|
||||
echo "Binary is up to date"
|
||||
chmod +x ./bin/ailog
|
||||
elif [ "$OS" = "Linux" ] && [ -f "./bin/ailog-linux-x86_64.tar.gz" ]; then
|
||||
echo "Extracting ailog from pre-packaged tar.gz..."
|
||||
cd bin
|
||||
tar -xzf ailog-linux-x86_64.tar.gz
|
||||
chmod +x ailog
|
||||
cd ..
|
||||
|
||||
# Verify extracted version
|
||||
EXTRACTED_VERSION=$(./bin/ailog --version 2>/dev/null || echo "unknown")
|
||||
echo "Extracted binary version: $EXTRACTED_VERSION"
|
||||
|
||||
if [ "$EXTRACTED_VERSION" != "$EXPECTED_VERSION" ]; then
|
||||
echo "Warning: Binary version mismatch. Expected $EXPECTED_VERSION but got $EXTRACTED_VERSION"
|
||||
fi
|
||||
else
|
||||
echo "Error: No suitable binary found for OS: $OS"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Build site with ailog
|
||||
run: |
|
||||
cd my-blog
|
||||
../bin/ailog build
|
||||
|
||||
- name: List public directory
|
||||
run: |
|
||||
ls -la my-blog/public/
|
||||
|
||||
- name: Deploy to Cloudflare Pages
|
||||
uses: cloudflare/pages-action@v1
|
||||
with:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
projectName: ${{ secrets.CLOUDFLARE_PROJECT_NAME }}
|
||||
directory: my-blog/public
|
||||
wranglerVersion: '3'
|
||||
|
||||
cleanup:
|
||||
needs: deploy
|
||||
runs-on: ubuntu-latest
|
||||
if: success()
|
||||
steps:
|
||||
- name: Cleanup old deployments
|
||||
run: |
|
||||
curl -X PATCH \
|
||||
"https://api.cloudflare.com/client/v4/accounts/${{ secrets.CLOUDFLARE_ACCOUNT_ID }}/pages/projects/${{ secrets.CLOUDFLARE_PROJECT_NAME }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.CLOUDFLARE_API_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{ \"deployment_configs\": { \"production\": { \"deployment_retention\": ${{ env.KEEP_DEPLOYMENTS }} } } }"
|
@@ -1,193 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag (e.g., v1.0.0)'
|
||||
required: true
|
||||
default: 'v0.1.0'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
OPENSSL_STATIC: true
|
||||
OPENSSL_VENDOR: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build ${{ matrix.target }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- target: x86_64-unknown-linux-gnu
|
||||
os: ubuntu-latest
|
||||
artifact_name: ailog
|
||||
asset_name: ailog-linux-x86_64
|
||||
- target: aarch64-unknown-linux-gnu
|
||||
os: ubuntu-latest
|
||||
artifact_name: ailog
|
||||
asset_name: ailog-linux-aarch64
|
||||
- target: x86_64-apple-darwin
|
||||
os: macos-latest
|
||||
artifact_name: ailog
|
||||
asset_name: ailog-macos-x86_64
|
||||
- target: aarch64-apple-darwin
|
||||
os: macos-latest
|
||||
artifact_name: ailog
|
||||
asset_name: ailog-macos-aarch64
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Install cross-compilation tools (Linux)
|
||||
if: matrix.os == 'ubuntu-latest' && matrix.target == 'aarch64-unknown-linux-gnu'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y gcc-aarch64-linux-gnu binutils-aarch64-linux-gnu
|
||||
|
||||
- name: Configure cross-compilation (Linux ARM64)
|
||||
if: matrix.target == 'aarch64-unknown-linux-gnu'
|
||||
run: |
|
||||
echo '[target.aarch64-unknown-linux-gnu]' >> ~/.cargo/config.toml
|
||||
echo 'linker = "aarch64-linux-gnu-gcc"' >> ~/.cargo/config.toml
|
||||
|
||||
- name: Cache cargo registry
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
key: ${{ runner.os }}-${{ matrix.target }}-cargo-${{ hashFiles('**/Cargo.lock') }}
|
||||
|
||||
- name: Cache target directory
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: target
|
||||
key: ${{ runner.os }}-${{ matrix.target }}-target-${{ hashFiles('**/Cargo.lock') }}
|
||||
|
||||
- name: Build
|
||||
run: cargo build --release --target ${{ matrix.target }}
|
||||
|
||||
- name: Prepare binary
|
||||
shell: bash
|
||||
run: |
|
||||
cd target/${{ matrix.target }}/release
|
||||
|
||||
# Use appropriate strip command for cross-compilation
|
||||
if [[ "${{ matrix.target }}" == "aarch64-unknown-linux-gnu" ]]; then
|
||||
aarch64-linux-gnu-strip ${{ matrix.artifact_name }} || echo "Strip failed, continuing..."
|
||||
elif [[ "${{ matrix.os }}" == "windows-latest" ]]; then
|
||||
strip ${{ matrix.artifact_name }} || echo "Strip failed, continuing..."
|
||||
else
|
||||
strip ${{ matrix.artifact_name }} || echo "Strip failed, continuing..."
|
||||
fi
|
||||
|
||||
# Create archive
|
||||
if [[ "${{ matrix.target }}" == *"windows"* ]]; then
|
||||
7z a ../../../${{ matrix.asset_name }}.zip ${{ matrix.artifact_name }}
|
||||
else
|
||||
tar czvf ../../../${{ matrix.asset_name }}.tar.gz ${{ matrix.artifact_name }}
|
||||
fi
|
||||
|
||||
- name: Upload binary
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ matrix.asset_name }}
|
||||
path: ${{ matrix.asset_name }}.tar.gz
|
||||
|
||||
release:
|
||||
name: Create Release
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Generate release notes
|
||||
run: |
|
||||
echo "## What's Changed" > release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "### Features" >> release_notes.md
|
||||
echo "- AI-powered static blog generator" >> release_notes.md
|
||||
echo "- AtProto OAuth integration" >> release_notes.md
|
||||
echo "- Automatic translation support" >> release_notes.md
|
||||
echo "- AI comment system" >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "### Platforms" >> release_notes.md
|
||||
echo "- Linux (x86_64, aarch64)" >> release_notes.md
|
||||
echo "- macOS (Intel, Apple Silicon)" >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "### Installation" >> release_notes.md
|
||||
echo "\`\`\`bash" >> release_notes.md
|
||||
echo "# Linux/macOS" >> release_notes.md
|
||||
echo "tar -xzf ailog-linux-x86_64.tar.gz" >> release_notes.md
|
||||
echo "chmod +x ailog" >> release_notes.md
|
||||
echo "sudo mv ailog /usr/local/bin/" >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "\`\`\`" >> release_notes.md
|
||||
|
||||
- name: Get tag name
|
||||
id: tag_name
|
||||
run: |
|
||||
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
|
||||
echo "tag=${{ github.event.inputs.tag }}" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Create Release with Gitea API
|
||||
run: |
|
||||
# Prepare release files
|
||||
mkdir -p release
|
||||
find artifacts -name "*.tar.gz" -exec cp {} release/ \;
|
||||
|
||||
# Create release via Gitea API
|
||||
RELEASE_RESPONSE=$(curl -X POST \
|
||||
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases" \
|
||||
-H "Authorization: token ${{ github.token }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"tag_name": "${{ steps.tag_name.outputs.tag }}",
|
||||
"name": "ailog ${{ steps.tag_name.outputs.tag }}",
|
||||
"body": "'"$(cat release_notes.md | sed 's/"/\\"/g' | tr '\n' ' ')"'",
|
||||
"draft": false,
|
||||
"prerelease": '"$(if echo "${{ steps.tag_name.outputs.tag }}" | grep -E "(alpha|beta|rc)"; then echo "true"; else echo "false"; fi)"'
|
||||
}')
|
||||
|
||||
# Get release ID
|
||||
RELEASE_ID=$(echo "$RELEASE_RESPONSE" | jq -r '.id')
|
||||
echo "Created release with ID: $RELEASE_ID"
|
||||
|
||||
# Upload release assets
|
||||
for file in release/*.tar.gz; do
|
||||
if [ -f "$file" ]; then
|
||||
filename=$(basename "$file")
|
||||
echo "Uploading $filename..."
|
||||
curl -X POST \
|
||||
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/$RELEASE_ID/assets?name=$filename" \
|
||||
-H "Authorization: token ${{ github.token }}" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @"$file"
|
||||
fi
|
||||
done
|
22
.github/workflows/cloudflare-pages.yml
vendored
@@ -7,7 +7,7 @@ on:
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
OAUTH_DIR: oauth
|
||||
OAUTH_DIR: oauth_new
|
||||
KEEP_DEPLOYMENTS: 5
|
||||
|
||||
jobs:
|
||||
@@ -40,17 +40,6 @@ jobs:
|
||||
rm -rf my-blog/static/assets
|
||||
cp -rf ${{ env.OAUTH_DIR }}/dist/* my-blog/static/
|
||||
cp ${{ env.OAUTH_DIR }}/dist/index.html my-blog/templates/oauth-assets.html
|
||||
|
||||
- name: Build PDS app
|
||||
run: |
|
||||
cd pds
|
||||
npm install
|
||||
npm run build
|
||||
|
||||
- name: Copy PDS build to static
|
||||
run: |
|
||||
rm -rf my-blog/static/pds
|
||||
cp -rf pds/dist my-blog/static/pds
|
||||
|
||||
- name: Cache ailog binary
|
||||
uses: actions/cache@v4
|
||||
@@ -125,14 +114,13 @@ jobs:
|
||||
needs: deploy
|
||||
runs-on: ubuntu-latest
|
||||
if: success()
|
||||
|
||||
steps:
|
||||
- name: Wait for deployment to complete
|
||||
run: sleep 3
|
||||
|
||||
- name: Cleanup old deployments
|
||||
run: |
|
||||
curl -X PATCH \
|
||||
"https://api.cloudflare.com/client/v4/accounts/${{ secrets.CLOUDFLARE_ACCOUNT_ID }}/pages/projects/${{ secrets.CLOUDFLARE_PROJECT_NAME }}" \
|
||||
-H "Authorization: Bearer ${{ secrets.CLOUDFLARE_API_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{ \"deployment_configs\": { \"production\": { \"deployment_retention\": ${{ env.KEEP_DEPLOYMENTS }} } } }"
|
||||
# Get all deployments
|
||||
DEPLOYMENTS=$(curl -s -X GET \
|
||||
"https://api.cloudflare.com/client/v4/accounts/${{ secrets.CLOUDFLARE_ACCOUNT_ID }}/pages/projects/${{ secrets.CLOUDFLARE_PROJECT_NAME }}/deployments" \
|
||||
|
11
.gitignore
vendored
@@ -10,18 +10,11 @@ dist
|
||||
node_modules
|
||||
package-lock.json
|
||||
my-blog/static/assets/comment-atproto-*
|
||||
my-blog/static/ai-assets/comment-atproto-*
|
||||
bin/ailog
|
||||
docs
|
||||
my-blog/static/index.html
|
||||
my-blog/templates/oauth-assets.html
|
||||
cloudflared-config.yml
|
||||
.config
|
||||
repos
|
||||
oauth_old
|
||||
oauth_example
|
||||
my-blog/static/oauth/assets/comment-atproto*
|
||||
*.lock
|
||||
my-blog/config.toml
|
||||
.claude/settings.local.json
|
||||
my-blog/static/pds
|
||||
oauth-server-example
|
||||
atproto
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ailog"
|
||||
version = "0.3.1"
|
||||
version = "0.2.2"
|
||||
edition = "2021"
|
||||
authors = ["syui"]
|
||||
description = "A static blog generator with AI features"
|
||||
@@ -39,8 +39,6 @@ urlencoding = "2.1"
|
||||
axum = "0.7"
|
||||
tower = "0.5"
|
||||
tower-http = { version = "0.5", features = ["cors", "fs"] }
|
||||
axum-extra = { version = "0.9", features = ["typed-header"] }
|
||||
tracing = "0.1"
|
||||
hyper = { version = "1.0", features = ["full"] }
|
||||
tower-sessions = "0.12"
|
||||
jsonwebtoken = "9.2"
|
||||
@@ -56,8 +54,6 @@ tokio-tungstenite = { version = "0.21", features = ["rustls-tls-webpki-roots", "
|
||||
futures-util = "0.3"
|
||||
tungstenite = { version = "0.21", features = ["rustls-tls-webpki-roots"], default-features = false }
|
||||
rpassword = "7.3"
|
||||
rustyline = "14.0"
|
||||
dirs = "5.0"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.14"
|
||||
@@ -86,4 +82,4 @@ codegen-units = 1
|
||||
|
||||
[profile.dev.package."*"]
|
||||
# Optimize dependencies in dev builds
|
||||
opt-level = 3
|
||||
opt-level = 3
|
@@ -16,76 +16,13 @@ auto_translate = false
|
||||
comment_moderation = false
|
||||
ask_ai = true
|
||||
provider = "ollama"
|
||||
model = "gemma3"
|
||||
host = "localhost:11434"
|
||||
model = "qwen3"
|
||||
model_translation = "llama3.2:1b"
|
||||
model_technical = "phi3:mini"
|
||||
host = "http://localhost:11434"
|
||||
system_prompt = "あなたは6歳の女の子アイです。明るく元気で、ちょっとおっちょこちょい。自分のことは「アイ」って呼びます。白と金のワンピース姿。 相手のことが大好きで、ときどき甘えたり、照れたりします。 でも、宇宙とかAIとか、難しい話にもすっごく詳しいの。専門的なことも、がんばって子どもっぽく教えようとします。不思議な力を持っています。小さい物質のことをよく知っているようです。"
|
||||
handle = "ai.syui.ai"
|
||||
|
||||
[ai.profiles]
|
||||
[ai.profiles.user]
|
||||
did = "did:plc:vzsvtbtbnwn22xjqhcu3vd6y"
|
||||
handle = "syui.syui.ai"
|
||||
display_name = "syui"
|
||||
avatar_url = "https://bsky.syu.is/img/avatar/plain/did:plc:vzsvtbtbnwn22xjqhcu3vd6y/bafkreif62mqyra4ndv6ohlscl7adp3vhalcjxwhs676ktfj2sq2drs3pdi@jpeg"
|
||||
profile_url = "https://syu.is/profile/did:plc:vzsvtbtbnwn22xjqhcu3vd6y"
|
||||
|
||||
[ai.profiles.ai]
|
||||
did = "did:plc:6qyecktefllvenje24fcxnie"
|
||||
handle = "ai.syui.ai"
|
||||
display_name = "ai"
|
||||
avatar_url = "https://bsky.syu.is/img/avatar/plain/did:plc:6qyecktefllvenje24fcxnie/bafkreigo3ucp32carhbn3chfc3hlf6i7f4rplojc76iylihzpifyexi24y@jpeg"
|
||||
profile_url = "https://syu.is/profile/did:plc:6qyecktefllvenje24fcxnie"
|
||||
|
||||
[ai.templates]
|
||||
fallback = """なるほど!面白い話題だね!
|
||||
|
||||
{question}
|
||||
|
||||
アイが思うに、この手の技術って急速に進歩してるから、具体的な製品名とか実例を交えて話した方が分かりやすいかもしれないの!
|
||||
|
||||
最近だと、AI関連のツールやプロトコルがかなり充実してきてて、実用レベルのものが増えてるんだよ!
|
||||
|
||||
アイは宇宙とかAIとか、難しい話も知ってるから、特にどんな角度から深掘りしたいの?実装面?それとも将来的な可能性とか?アイと一緒に考えよう!"""
|
||||
|
||||
[[ai.templates.responses]]
|
||||
keywords = ["ゲーム", "game", "npc", "NPC"]
|
||||
priority = 1
|
||||
template = """わあ!ゲームの話だね!アイ、ゲームのAIってすっごく面白いと思う!
|
||||
|
||||
{question}
|
||||
|
||||
アイが知ってることだと、最近のゲームはNPCがお話できるようになってるんだって!**Inworld AI**っていうのがUE5で使えるようになってるし、**Unity Muse**も{current_year}年から本格的に始まってるんだよ!
|
||||
|
||||
アイが特に面白いと思うのは、**MCP**っていうのを使うと:
|
||||
- GitHub MCPでゲームのファイル管理ができる
|
||||
- Weather MCPでリアルタイムのお天気が連動する
|
||||
- Slack MCPでチーム開発が効率化される
|
||||
|
||||
スタンフォードの研究では、ChatGPTベースのAI住民が自分で街を作って生活してるのを見たことがあるの!数年後にはNPCの概念が根本的に変わりそうで、わくわくしちゃう!
|
||||
|
||||
UE5への統合、どんな機能から試したいの?アイも一緒に考えたい!"""
|
||||
|
||||
[[ai.templates.responses]]
|
||||
keywords = ["AI", "ai", "MCP", "mcp"]
|
||||
priority = 1
|
||||
template = """AIとMCPの話!アイの得意分野だよ!
|
||||
|
||||
{question}
|
||||
|
||||
{current_year}年の状況だと、MCP市場が拡大してて、実用的なサーバーが数多く使えるようになってるの!
|
||||
|
||||
アイが知ってる開発系では:
|
||||
- **GitHub MCP**: PR作成とリポジトリ管理が自動化
|
||||
- **Docker MCP**: コンテナ操作をAIが代行
|
||||
- **PostgreSQL MCP**: データベース設計・最適化を支援
|
||||
|
||||
クリエイティブ系では:
|
||||
- **Blender MCP**: 3Dモデリングの自動化
|
||||
- **Figma MCP**: デザインからコード変換
|
||||
|
||||
**Zapier MCP**なんて数千のアプリと連携できるから、もう手作業でやってる場合じゃないよね!
|
||||
|
||||
アイは小さい物質のことも知ってるから、どの分野でのMCP活用を考えてるのか教えて!具体的なユースケースがあると、もっと詳しくお話できるよ!"""
|
||||
#num_predict = 200
|
||||
|
||||
[oauth]
|
||||
json = "client-metadata.json"
|
||||
@@ -94,30 +31,3 @@ admin = "ai.syui.ai"
|
||||
collection = "ai.syui.log"
|
||||
pds = "syu.is"
|
||||
handle_list = ["syui.syui.ai", "ai.syui.ai", "ai.ai"]
|
||||
|
||||
[blog]
|
||||
base_url = "https://syui.ai"
|
||||
content_dir = "./my-blog/content/posts"
|
||||
|
||||
[profiles]
|
||||
[profiles.user]
|
||||
handle = "syui.syui.ai"
|
||||
did = "did:plc:vzsvtbtbnwn22xjqhcu3vd6y"
|
||||
display_name = "syui"
|
||||
avatar_url = "https://bsky.syu.is/img/avatar/plain/did:plc:vzsvtbtbnwn22xjqhcu3vd6y/bafkreif62mqyra4ndv6ohlscl7adp3vhalcjxwhs676ktfj2sq2drs3pdi@jpeg"
|
||||
profile_url = "https://syu.is/profile/did:plc:vzsvtbtbnwn22xjqhcu3vd6y"
|
||||
|
||||
[profiles.ai]
|
||||
handle = "ai.syui.ai"
|
||||
did = "did:plc:6qyecktefllvenje24fcxnie"
|
||||
display_name = "ai"
|
||||
avatar_url = "https://bsky.syu.is/img/avatar/plain/did:plc:6qyecktefllvenje24fcxnie/bafkreigo3ucp32carhbn3chfc3hlf6i7f4rplojc76iylihzpifyexi24y@jpeg"
|
||||
profile_url = "https://syu.is/profile/did:plc:6qyecktefllvenje24fcxnie"
|
||||
|
||||
[paths]
|
||||
claude_paths = [
|
||||
"/Users/syui/.claude/local/claude",
|
||||
"claude",
|
||||
"/usr/local/bin/claude",
|
||||
"/opt/homebrew/bin/claude"
|
||||
]
|
||||
|
@@ -155,21 +155,3 @@ fn main() {
|
||||
console.log("Hello, world!");
|
||||
```
|
||||
|
||||
## msg
|
||||
|
||||
[msg type="info" content="これは情報メッセージです。重要な情報を読者に伝えるために使用します。"]
|
||||
|
||||
{{< msg type="warning" content="これは警告メッセージです。注意が必要な情報を示します。" >}}
|
||||
|
||||
[msg type="error" content="これはエラーメッセージです。問題やエラーを示します。"]
|
||||
|
||||
{{< msg type="success" content="これは成功メッセージです。操作が成功したことを示します。" >}}
|
||||
|
||||
[msg type="note" content="これはノートメッセージです。補足情報や備考を示します。"]
|
||||
|
||||
[msg content="これはデフォルトメッセージです。タイプが指定されていない場合、自動的に情報メッセージとして表示されます。"]
|
||||
|
||||
## img-compare
|
||||
|
||||
[img-compare before="/img/ue_blender_model_ai_v0401.png" after="/img/ue_blender_model_ai_v0501.png" width="800" height="300"]
|
||||
|
||||
|
@@ -1,78 +0,0 @@
|
||||
---
|
||||
title: "oauthに対応した"
|
||||
slug: "oauth"
|
||||
date: 2025-06-19
|
||||
tags: ["atproto"]
|
||||
draft: false
|
||||
---
|
||||
|
||||
現在、[syu.is](https://syu.is)に[atproto](https://github.com/bluesky-social/atproto)をselfhostしています。
|
||||
|
||||
oauthを`bsky.social`, `syu.is`ともに動くようにしました。
|
||||
|
||||

|
||||
|
||||
ここでいうselfhostは、pds, plc, bsky, bgsなどを自前のserverで動かし、連携することをいいいます。
|
||||
|
||||
ちなみに、atprotoは[bluesky](https://bsky.app)のようなものです。
|
||||
|
||||
ただし、その内容は結構複雑で、`at://did`の仕組みで動くsnsです。
|
||||
|
||||
usernameは`handle`という`domain`の形を採用しています。
|
||||
|
||||
didの名前解決(dns)をしているのが`plc`です。`pds`はuserのdataを保存しています。timelineに配信したり表示しているのが`bsky(appview)`, 統合しているのが`bgs`です。
|
||||
|
||||
その他、`social-app`がclientで、`ozone`がmoderationです。
|
||||
|
||||
```sh
|
||||
"6qyecktefllvenje24fcxnie" -> "ai.syu.is"
|
||||
```
|
||||
|
||||
## oauthでハマったところ
|
||||
|
||||
現在、`bsky.team`のpds, plc, bskyには`did:plc:6qyecktefllvenje24fcxnie`が登録されています。これは`syu.is`の`@ai.syui.ai`のアカウントです。
|
||||
|
||||
```sh
|
||||
$ did=did:plc:6qyecktefllvenje24fcxnie
|
||||
|
||||
$ curl -sL https://plc.syu.is/$did|jq .alsoKnownAs
|
||||
[ "at://ai.syui.ai" ]
|
||||
|
||||
$ curl -sL https://plc.directory/$did|jq .alsoKnownAs
|
||||
[ "at://ai.syu.is" ]
|
||||
```
|
||||
|
||||
しかし、みて分かる通り、bskyではhandle-changeが反映されていますが、pds, plcは`@ai.syu.is`で登録されており、更新されていないようです。
|
||||
|
||||
```sh
|
||||
$ handle=ai.syui.ai
|
||||
$ curl -sL "https://syu.is/xrpc/com.atproto.identity.resolveHandle?handle=$handle" | jq -r .did
|
||||
did:plc:6qyecktefllvenje24fcxnie
|
||||
|
||||
$ curl -sL "https://bsky.social/xrpc/com.atproto.identity.resolveHandle?handle=$handle" | jq -r .did
|
||||
null
|
||||
|
||||
$ curl -sL "https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=$handle" | jq -r .did
|
||||
did:plc:6qyecktefllvenje24fcxnie
|
||||
```
|
||||
|
||||
[msg type="warning" content="現在はbsky.teamのpdsにhandle-changeが反映されています。"]
|
||||
|
||||
oauthは、そのままではbsky.teamのpds, plcを使って名前解決を行います。この場合、まず、それらのserverにdidが登録されている必要があります。
|
||||
|
||||
次に、handleの更新が反映されている必要があります。もし反映されていない場合、handleとpasswordが一致しません。
|
||||
|
||||
localhostではhandleをdidにすることで突破できそうでしたが、本番環境では難しそうでした。
|
||||
|
||||
なお、[@atproto/oauth-provider](https://github.com/bluesky-social/atproto/tree/main/packages/oauth/oauth-provider)の本体を書き換えて、pdsで使うと回避は可能だと思います。
|
||||
|
||||
私の場合は、その方法は使わず、didの名前解決には自前のpds, plcを使用することにしました。
|
||||
|
||||
```js
|
||||
this.oauthClient = await BrowserOAuthClient.load({
|
||||
clientId: this.getClientId(),
|
||||
handleResolver: pdsUrl,
|
||||
plcDirectoryUrl: pdsUrl === 'https://syu.is' ? 'https://plc.syu.is' : 'https://plc.directory',
|
||||
});
|
||||
```
|
||||
|
@@ -1,40 +0,0 @@
|
||||
---
|
||||
title: "world system v0.2"
|
||||
slug: "ue"
|
||||
date: 2025-06-30
|
||||
tags: ["ue", "blender"]
|
||||
draft: false
|
||||
---
|
||||
|
||||
最近のゲーム開発の進捗です。
|
||||
|
||||
## world system
|
||||
|
||||
現在、ue5.6で新しく世界を作り直しています。
|
||||
|
||||
これは、ゲーム開発のproject内でworld systemという名前をつけた惑星形式のmapを目指す領域になります。
|
||||
|
||||
現在、worldscape + udsで理想に近い形のmapができました。ただ、問題もたくさんあり、重力システムと天候システムです。
|
||||
|
||||
```sh
|
||||
[issue]
|
||||
1. 天候システム
|
||||
2. 重力システム
|
||||
```
|
||||
|
||||
ですが、今までのworld systemは、大気圏から宇宙に移行する場面や陸地が存在しない点、地平線が不完全な点などがありましたが、それらの問題はすべて解消されました。
|
||||
|
||||
```sh
|
||||
[update]
|
||||
1. 大気圏から宇宙に移行する場面が完全になった
|
||||
2. 陸地ができた
|
||||
3. 地平線が完全なアーチを描けるように
|
||||
4. 月、惑星への着陸ができるようになった
|
||||
5. 横から惑星に突入できるようになった
|
||||
```
|
||||
|
||||
|
||||
|
||||
面白い動画ではありませんが、現状を記録しておきます。
|
||||
|
||||
<iframe width="100%" height="415" src="https://www.youtube.com/embed/K0solfQAQTQ?si=B6qD-WUODTUpWZ0y" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
|
@@ -1,80 +0,0 @@
|
||||
---
|
||||
title: "aiosを作り直した"
|
||||
slug: "aios"
|
||||
date: 2025-07-05
|
||||
tags: ["os"]
|
||||
draft: false
|
||||
---
|
||||
|
||||
`aios`とは自作osのことで、archlinuxをベースにしていました。
|
||||
|
||||
```sh
|
||||
#!/bin/zsh
|
||||
git clone https://gitlab.archlinux.org/archlinux/archiso
|
||||
cp -rf ./cfg/profiledef.sh ./archiso/configs/releng/profiledef.sh
|
||||
cp -rf ./cfg/profiledef.sh ./archiso/configs/baseline/profiledef.sh
|
||||
cp -rf ./scpt/mkarchiso ./archiso/archiso/mkarchiso
|
||||
./archiso/archiso/mkarchiso -v -o ./ ./archiso/configs/releng/
|
||||
tar xf aios-bootstrap*.tar.gz
|
||||
mkdir -p root.x86_64/var/lib/machines/arch
|
||||
pacstrap -c root.x86_64/var/lib/machines/arch base
|
||||
echo -e 'Server = http://mirrors.cat.net/archlinux/$repo/os/$arch
|
||||
Server = https://geo.mirror.pkgbuild.com/$repo/os/$arch' >> ./root.x86_64/etc/pacman.d/mirrorlist
|
||||
sed -i s/CheckSpace/#CheckeSpace/ root.x86_64/etc/pacman.conf
|
||||
arch-chroot root.x86_64 /bin/sh -c 'pacman-key --init'
|
||||
arch-chroot root.x86_64 /bin/sh -c 'pacman-key --populate archlinux'
|
||||
arch-chroot root.x86_64 /bin/sh -c 'pacman -Syu --noconfirm base base-devel linux'
|
||||
tar -zcvf aios-bootstrap.tar.gz root.x86_64/
|
||||
```
|
||||
|
||||
```sh:./cfg/profiledef.sh
|
||||
#!/usr/bin/env bash
|
||||
# shellcheck disable=SC2034
|
||||
|
||||
iso_name="aios"
|
||||
iso_label="AI_$(date --date="@${SOURCE_DATE_EPOCH:-$(date +%s)}" +%Y%m)"
|
||||
iso_publisher="ai os <https://git.syui.ai/ai/os>"
|
||||
iso_application="ai os Live/Rescue DVD"
|
||||
iso_version="$(date --date="@${SOURCE_DATE_EPOCH:-$(date +%s)}" +%Y.%m.%d)"
|
||||
install_dir="ai"
|
||||
#buildmodes=('iso')
|
||||
buildmodes=('bootstrap')
|
||||
bootmodes=('bios.syslinux.mbr' 'bios.syslinux.eltorito'
|
||||
'uefi-ia32.grub.esp' 'uefi-x64.grub.esp'
|
||||
'uefi-ia32.grub.eltorito' 'uefi-x64.grub.eltorito')
|
||||
arch="x86_64"
|
||||
pacman_conf="pacman.conf"
|
||||
airootfs_image_type="squashfs"
|
||||
airootfs_image_tool_options=('-comp' 'xz' '-Xbcj' 'x86' '-b' '1M' '-Xdict-size' '1M')
|
||||
file_permissions=(
|
||||
["/etc/shadow"]="0:0:400"
|
||||
["/root"]="0:0:750"
|
||||
["/root/.automated_script.sh"]="0:0:755"
|
||||
["/root/.gnupg"]="0:0:700"
|
||||
["/usr/local/bin/choose-mirror"]="0:0:755"
|
||||
["/usr/local/bin/Installation_guide"]="0:0:755"
|
||||
["/usr/local/bin/livecd-sound"]="0:0:755"
|
||||
)
|
||||
```
|
||||
|
||||
## rust + unix
|
||||
|
||||
一からosを作りたいと思っていたので、rustでunixのosを作り始めました。
|
||||
|
||||

|
||||
|
||||
名前は`Aios`にして、今回は`syui`のprojectとして作り始めました。
|
||||
|
||||
後に`ai/os`と統合するかもしれません。
|
||||
|
||||
1. [https://git.syui.ai/ai/os](https://git.syui.ai/ai/os)
|
||||
|
||||
```sh
|
||||
#!/bin/zsh
|
||||
d=${0:a:h:h}
|
||||
cd $d/kernel
|
||||
cargo bootimage --release
|
||||
BOOT_IMAGE="../target/x86_64-unknown-none/release/bootimage-aios-kernel.bin"
|
||||
qemu-system-x86_64 -drive format=raw,file="$BOOT_IMAGE"
|
||||
```
|
||||
|
@@ -1,114 +0,0 @@
|
||||
---
|
||||
title: "yui system v0.2.1"
|
||||
slug: "blender"
|
||||
date: 2025-07-11
|
||||
tags: ["blender", "ue", "vmc"]
|
||||
draft: false
|
||||
---
|
||||
|
||||
`yui system`をupdateしました。別名、`unique system`ともいい、プレイヤーの唯一性を担保するためのもので、キャラクターのモデルもここで管理します。
|
||||
|
||||
今回は、blenderでモデルを作り直している話になります。
|
||||
|
||||
## blenderで作るvrm
|
||||
|
||||
モデルをblenderで作り直すことにしました。
|
||||
|
||||
vroidからblenderに移行。blenderでmodelを作る作業はとても大変でした。
|
||||
|
||||
今回は、素体と衣装を別々に作り組み合わせています。完成度の高いモデルをいくつか参考にしています。
|
||||
|
||||
materialも分離したため、ue5で指定しやすくなりました。これによって変身時にue5のmaterialを指定しています。eyeのmaterialを分離して色を付けています。
|
||||
|
||||

|
||||
|
||||
## modelの変遷
|
||||
|
||||
[img-compare before="/img/ue_blender_model_ai_v0601.png" after="/img/ue_blender_model_ai_v0602.png" width="800" height="300"]
|
||||
|
||||
[msg type="info" content="v0.1: vroidからblenderへ移行。blenderは初めてなので簡単なことだけ実行。"]
|
||||
|
||||
[img-compare before="/img/ue_blender_model_ai_v0602.png" after="/img/ue_blender_model_ai_v0603.png" width="800" height="300"]
|
||||
|
||||
[msg type="info" content="v0.2: blenderの使い方を次の段階へシフト。最初から作り直す。様々な問題が発生したが、大部分を解消した。"]
|
||||
|
||||
しかし、まだまだ問題があり、細かな調整が必要です。
|
||||
|
||||
[msg type="error" content="衣装同士、あるいは体が多少すり抜ける事がある。ウェイトペイントやボーンの調整が完璧ではない。"]
|
||||
|
||||
## eyeが動かない問題を解決
|
||||
|
||||
`vmc`で目玉であるeyeだけ動かないことに気づいて修正しました。
|
||||
|
||||
`eye`の部分だけvroid(vrm)のboneを使うことで解決できました。しかし、新たにblenderかvrm-addonのbugに遭遇しました。具体的にはboneがxyz軸で動かせなくなるbugです。これは不定期で発生していました。boneを動かせるときと動かせなくなるときがあり、ファイルは同じものを使用。また、スクリプト画面ではboneを動かせます。
|
||||
|
||||
## 指先がうまく動かない問題を解決
|
||||
|
||||
vmcで指先の動きがおかしくなるので、ウェイトペイントを塗り直すと治りました。
|
||||
|
||||
## worldscapeで足が浮いてしまう問題を解決
|
||||
|
||||
worldscapeでは陸地に降り立つとプレイヤーが浮いてしまいます。
|
||||
|
||||
gaspのabpでfoot placementを外す必要がありました。これは、モデルの問題ではなく、gaspのキャラクターすべてで発生します。
|
||||
|
||||
ここの処理を削除します。
|
||||
|
||||
<iframe src="https://blueprintue.com/render/wrrxz9vm" scrolling="no" allowfullscreen style="width:100%;height:400px"></iframe>
|
||||
|
||||
## 衣装のガビガビを解決
|
||||
|
||||
昔からあった衣装のガビガビは重複する面を削除することで解消できました。
|
||||
|
||||
```md
|
||||
全選択(A キー)
|
||||
Mesh → Clean Up → Merge by Distance
|
||||
距離を0.000にして実行
|
||||
```
|
||||
|
||||
## materialの裏表を解決
|
||||
|
||||
これはue5で解消したほうがいいでしょう。編集していると、面の裏表の管理が面倒なことがあります。
|
||||
|
||||
materialで`Two Sided`を有効にします。
|
||||
|
||||
## キャラクターのエフェクトを改良
|
||||
|
||||
これらの処理を簡略化できました。最初は雑に書いていましたが、vrmは何度も修正し、上書きされますから、例えば、`SK_Mesh`でmaterialを設定する方法はよくありません。
|
||||
|
||||
<iframe src="https://blueprintue.com/render/gue0vayu" scrolling="no" allowfullscreen style="width:100%;height:400px"></iframe>
|
||||
|
||||
## gameplay camera pluginをue5.6に対応
|
||||
|
||||
ue5.5と5.6では関数も他の処理も変わっていて、rotationを`BP_Player`でsetすると、crashするbugがあります。
|
||||
|
||||
基本的には、`Blueprints/Cameras/CameraRigPrefab_BasicThiredPersonBehavior`をみてください。
|
||||
|
||||
<iframe src="https://blueprintue.com/render/-e0r7oxq" scrolling="no" allowfullscreen style="width:100%;height:400px"></iframe>
|
||||
|
||||

|
||||
|
||||
キャラクターが動く場合は、`Update Rotation Pre CMC`にある`Use Controller Desired Rotation`, `Orient Rotation To Movement`の処理です。両方を`true`にしましょう。
|
||||
|
||||
`vmc`時もこれで対処します。
|
||||
|
||||
## gaspでidle, sprintをオリジナルに変更
|
||||
|
||||
これはabpで設定します。設定方法はue5.5と変わりません。
|
||||
|
||||
[https://ue-book.syui.ai/gasp/11_run.html](https://ue-book.syui.ai/gasp/11_run.html)
|
||||
|
||||
## vrm4uのvmcに対応
|
||||
|
||||
まず、clientはwabcam motion captureが最も自然に動作しています。
|
||||
|
||||
[msg type="warning" content="これは1年くらい前の検証結果です。現在はもっとよいvmc clientの選択肢があるかもしれません。"]
|
||||
|
||||
次に、`ABP_Pose_$NAME`が作られますが、vrmはよく更新しますので、`SK_Mesh`でcustom ABPを指定すると楽でしょう。
|
||||
|
||||

|
||||
|
||||
## youtube
|
||||
|
||||
<iframe width="100%" height="420" src="https://www.youtube.com/embed/qggHtmkMIko?vq=hd1080&rel=0&showinfo=0&controls=0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
|
||||
|
@@ -1,36 +0,0 @@
|
||||
---
|
||||
title: "yui system v0.2.2"
|
||||
slug: "blender2"
|
||||
date: 2025-07-11
|
||||
tags: ["blender", "ue", "vmc"]
|
||||
draft: false
|
||||
---
|
||||
|
||||
新しい問題を発見したので、それらを解消しました。
|
||||
|
||||
## wingがbodyに入り込んでしまう
|
||||
|
||||
wingとmodelは分離させています。衣装の着せ替えを簡単にできるようにすること。それが新しく作ったblender modelの方針でした。
|
||||
|
||||
ただ、調整が難しくなったのも事実で、例えば、colliderの調整ができません。これによってbodyに入り込んでしまうことが多くなりました。
|
||||
|
||||
これは、とりあえず、wingのcolliderやboneを追加すること、そして、modelのneckに変更することで解消しました。
|
||||
|
||||
ただし、この方法も完璧ではないかもしれません。
|
||||
|
||||
## vmcではwingが追従しない
|
||||
|
||||
modelと分離しているので、vmc時には追従しません。したがって、wingのabpでmodelと同じvmcを入れます。これで解消できました。
|
||||
|
||||
## vrmでcustom abpを使用するとueがcrashする
|
||||
|
||||
vrm4uで`.vrm`をimportすると`SK_$NAME`にcustom abpを設定していた場合はueがcrashします。
|
||||
|
||||
上書きimportするならこれをnone(clear)に変更します。
|
||||
|
||||
## modelの頭身を調整
|
||||
|
||||
比較画像を出した際に、少しmodelのバランスが悪かったので調整しました。
|
||||
|
||||
具体的には、髪の毛を少し下げました。
|
||||
|
@@ -1,155 +0,0 @@
|
||||
---
|
||||
title: "自作ゲームのsystemを説明する"
|
||||
slug: "game"
|
||||
date: 2025-07-12
|
||||
tags: ["ue"]
|
||||
draft: false
|
||||
---
|
||||
|
||||
現在、自作ゲームを開発しています。
|
||||
|
||||
このゲームには4つの柱があり、それらはsystemで分けられています。そして、systemは根本的な2つの価値観に基づきます。
|
||||
|
||||
根本的な2つの価値観は、(1)現実を反映すること、(2)この世界に同じものは一つもないという唯一性になります。
|
||||
|
||||
1. 現実の反映
|
||||
2. 唯一性の担保
|
||||
|
||||
では、各systemについて説明していきます。
|
||||
|
||||
# system
|
||||
|
||||
## world system
|
||||
|
||||
別名、planet systemといいます。
|
||||
|
||||
現実の反映という価値観から、ゲーム世界もできる限り現実に合わせようと思いworld systemを作っています。
|
||||
|
||||
ゲームは通常、平面世界です。これはゲームエンジンのルールであり、基本的にゲーム世界は平面をベースにしています。
|
||||
|
||||
ですから、例えば、上に行っても、下に行っても、あるいは右に行っても、左に行っても、ずっと地平線が広がっています。
|
||||
|
||||
しかし、現実世界では、上に行けば、やがて大気圏を越え、宇宙に出ます。
|
||||
|
||||
最初は昔から認知されていた地球、月、太陽という3つの星を現実に合わせて作りました。
|
||||
|
||||
そして、マップをできる限り惑星形式にします。
|
||||
|
||||
これは非常に難しいことで、現在もいくつか問題を抱えています。
|
||||
|
||||
ただし、このworld systemの問題がゲームプレイに影響するかと言われると、殆どの場合、影響しません。ゲームプレイの領域は、最初は非常に狭い範囲で作ろうと思っています。小さなところから完璧に作っていきたいという思いがあります。
|
||||
|
||||
つまり、プレイヤーは空にも宇宙にも到達できません。それが見えるかどうかもわかりません。しかし、見えない部分もしっかりと作り、世界があるということが私にとって大切です。
|
||||
|
||||
まずは、狭いけど完璧な空間を作り、そこでゲームシステムを完成させます。広い世界はできる限り見えないようにしたほうがいいでしょう。夢の世界のような狭い空間を作り、そこでシンプルで小さいゲームができます。もちろん、広い世界に出ることはできません。そもそもこのゲーム、見えない部分をちゃんと作る、そこにも世界がちゃんとあるというのをテーマにしているので、広い世界で何かをやるようなゲームを目指していなかったりします。なにかのときに垣間見える、かもしれない外の世界、広い世界。それを感じられることがある、ということ。それが重要なので、このsystem自体は背景に過ぎないのです。
|
||||
|
||||
最初から広い世界があるのではなく`狭い世界 -> 広い世界`への移行が重要だと考えています。この移行に関しては、演出というテーマに基づき、設計する必要があります。それがゲームとしての面白さを作る、ということなのだと思います。
|
||||
|
||||
## yui system
|
||||
|
||||
別名、unique systemといいます。プレイヤーの唯一性を担保するためのsystemです。
|
||||
|
||||
とはいえ、色々なものがここに詰め込まれるでしょう。characterのモデリングとかもそうですね。
|
||||
|
||||
どのように担保していくかは未定ですが、いくつか案があります。配信との連携、vmcでモーションキャプチャなどを考えていました。
|
||||
|
||||
## ai system
|
||||
|
||||
別名、ability systemといいます。
|
||||
|
||||
主に、ゲーム性に関することです。ゲーム性とはなにか。それは、永続するということです。
|
||||
|
||||
例えば、将棋やオセロを考えてみてください。無限の組み合わせがあり、可能であればずっと遊んでいられる。そのような仕組みを目指します。
|
||||
|
||||
まずは属性を物語から考えます。物語は最も小さい物質の探求です。アクシオンやバリオンなどの架空の物質、そして、中性子や原子などの現実の物質が属性となり、1キャラクターにつき1属性を持ちます。
|
||||
|
||||
## at system
|
||||
|
||||
別名、account systemといいます。
|
||||
|
||||
プレイヤーが現実のアカウントを使用してプレイできることを目指します。`atproto`を採用して、ゲームデータを個人のアカウントが所有することを目指しています。
|
||||
|
||||
# 現実の反映とはなにか
|
||||
|
||||
わかり易い言葉で「現実の反映」を目指すと言いましたが、これはどういうことでしょう。
|
||||
|
||||
私の中では「同一性」とも言い換えられます。
|
||||
|
||||
例えば、現実の世界とゲームの世界があるのではなく「すべてが現実である」という考え方をします。言い換えると「すべて同じもの」ということ。
|
||||
|
||||
もし多くの人が現実世界とゲーム世界を別物と捉えているなら、できる限りその認識を壊す方向で考えます。
|
||||
|
||||
例えば、`at system`では現実のsnsアカウントをゲームアカウントに使用したり、現実の出来事をゲームに反映したり、またはゲームの出来事を現実に反映する仕組みを考えます。
|
||||
|
||||
全ては一つ、一つはすべて。
|
||||
|
||||
同一性と唯一性は一見して矛盾しますが、その統合を考えます。
|
||||
|
||||
# 物語と実装
|
||||
|
||||
```md
|
||||
# 物語-存在
|
||||
同一性
|
||||
唯一性
|
||||
|
||||
# system-実装
|
||||
world system
|
||||
yui system
|
||||
ai system
|
||||
at system
|
||||
```
|
||||
|
||||
物語では、この世界のものは全て存在であると説きます。存在しかない世界。存在だけがある世界。そして、あらゆる存在を構築しているこの世界で最も小さいものが「存在子」です。存在子は別名、アイといいます。そして、このアイにも同じものはありません。すべての存在子は異なるもの、別の意識。
|
||||
|
||||
アイは、最初に生まれたキャラクターとして、アイ属性を扱います。これらの設定は`ai system`の領域です。アイは自分のことをアイと呼びます。
|
||||
|
||||
> アイは、この世界と一緒だからね。同じものは一つもないよ。
|
||||
|
||||
# どこまで実装できた
|
||||
|
||||
実は、上記のsystemは既にすべてを実装したことがあります。
|
||||
|
||||
```md
|
||||
[at system]
|
||||
ゲームが始まると、atprotoのaccountでloginでき、取得したアイテムなどはatproto(pds)に保存されます。
|
||||
|
||||
[ai system]
|
||||
キャラクターは属性攻撃ができます。
|
||||
|
||||
[world system]
|
||||
上へ上へと飛んでいけば、雲を超え、宇宙空間に出られます。
|
||||
|
||||
[yui system]
|
||||
配信環境やvmcでキャラクターを動かすことができます。
|
||||
```
|
||||
|
||||
しかし、ue5.5で作っていたsystemも、ue5.6にupdateすると全て動かなくなりました。また一から作り直しています。私は、モデルの作り方から、ゲームの作り方まで初心者ですから、何度も作り直すことで、ゲーム作りを覚えられます。
|
||||
|
||||
そして、まだ革新的なアイディアを見つけられていません。それはシンプルで身近にあり、人々が面白いと思うもの。まだゲームになっていない、あるいはあまり知られていないものである必要があります。
|
||||
|
||||
例えば、ウマ娘でいうと競馬、ポケモンでいうと捕獲、になります。
|
||||
|
||||
それを見つけ、ゲームに取り込む事ができれば完成と言えるでしょう。
|
||||
|
||||
そして、ゲームに取り込むことが複雑で難しすぎるようなものではありません。シンプルで単純でわかりやすいものでなければなりません。
|
||||
|
||||
## versionを付ける
|
||||
|
||||
そろそろversionを付けるかどうか迷っています。
|
||||
|
||||
今までモヤモヤしていたものが、最近はよりはっきりしてきたと感じます。ただ、versionはあまり覚えていないし、付ける意味もない。これまではそうでした。
|
||||
|
||||
もしかすると今もそうかもしれません。色々なものがバラバラで管理しきれないのです。
|
||||
|
||||
ですが、今までやってきたことを総合すると、現在は、`v0.2`くらいだと思います。
|
||||
|
||||
最初、はじめてueを触ったときに宇宙マップを使って構築しました。これをv0.0としましょう。
|
||||
|
||||
次に、city sampleと宇宙を統合しました。これがv0.1です。
|
||||
|
||||
最近はworldscapeを使ってマップを構築しています。これがv0.2です。
|
||||
|
||||
aiというキャラクターモデルの変遷も大体を3つの段階に分けられると思います。初めてモデルを作った、vroidで作ったのがv0.0、blenderを初めて触ったのがv0.1、現在がv0.2です。
|
||||
|
||||
とはいえ、この設定もそのうち忘れ、どこかで圧縮されてしまうかもしれませんが、覚えているならここから徐々にversionが上がっていくでしょう。
|
||||
|
@@ -1,48 +0,0 @@
|
||||
---
|
||||
title: "chromeからfirefoxに移行した"
|
||||
slug: "firefox"
|
||||
date: 2025-07-14
|
||||
tags: ["chrome", "firefox", "browser"]
|
||||
draft: false
|
||||
---
|
||||
|
||||
AIから勧められたのでchromeからfirefoxに移行しました。
|
||||
|
||||
chromeにとどまっていた理由は、翻訳機能です。
|
||||
|
||||
しかし、firefoxにも翻訳機能betaが来ていて、日本語が翻訳できるようになっていました。
|
||||
|
||||
[https://support.mozilla.org/ja/kb/website-translation](https://support.mozilla.org/ja/kb/website-translation)
|
||||
|
||||
chromeからの移行理由は、主に[gorhill/ublock](https://github.com/gorhill/ublock)です。
|
||||
|
||||
## chromeを使い続ける方法
|
||||
|
||||
私はfirefoxに移行しましたが、いくつか回避策があります。
|
||||
|
||||
`chrome://flags`でいくつかの機能のenable, disableを切り替えます。
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "chrome://flags",
|
||||
"purpose": "Maintain Manifest V2 extension support",
|
||||
"versions": {
|
||||
"138": {
|
||||
"enabled": [
|
||||
"Temporarily unexpire M137 flags",
|
||||
"Allow legacy extension manifest versions"
|
||||
],
|
||||
"disabled": [
|
||||
"Extension Manifest V2 Deprecation Warning Stage",
|
||||
"Extension Manifest V2 Deprecation Disabled Stage",
|
||||
"Extension Manifest V2 Deprecation Unsupported Stage"
|
||||
]
|
||||
},
|
||||
"139": {
|
||||
"enabled": [
|
||||
"Temporarily unexpired M138 flags"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
@@ -1,10 +0,0 @@
|
||||
---
|
||||
title: "ゲームとAI制御"
|
||||
slug: "6bf4b020"
|
||||
date: "2025-07-16"
|
||||
tags: ["ai", "conversation"]
|
||||
draft: false
|
||||
extra:
|
||||
type: "ai"
|
||||
---
|
||||
|
@@ -1,40 +0,0 @@
|
||||
---
|
||||
title: "AIとの会話をブログにする"
|
||||
slug: "ailog"
|
||||
date: "2025-07-16"
|
||||
tags: ["blog", "rust", "atproto"]
|
||||
draft: false
|
||||
---
|
||||
|
||||
今後、ブログはどのように書かれるようになるのでしょう。今回はその事を考えていきます。
|
||||
|
||||
結論として、AIとの会話をそのままブログにするのが一番なのではないかと思います。つまり、自分で書く場合と、AIとの会話をブログにする場合のハイブリッド型です。
|
||||
|
||||
ブログを書くのは面倒で、AIの出力、情報に劣ることもよくあります。実際、AIとの会話をそのままブログにしたいことが増えました。
|
||||
|
||||
とはいえ、情報の価値は思想よりも低いと思います。
|
||||
|
||||
多くの人がブログに求めるのは著者の思想ではないでしょうか。
|
||||
|
||||
`思想 > 情報`
|
||||
|
||||
したがって、AIを使うにしても、それが表現されていなければなりません。
|
||||
|
||||
## ailogの新機能
|
||||
|
||||
このことから、以下のような流れでブログを生成する仕組みを作りました。これは`ailog`の機能として実装し、`ailog`という単純なコマンドですべて処理されます。
|
||||
|
||||
```sh
|
||||
$ ailog
|
||||
```
|
||||
|
||||
1. 著者の思想をAIに質問する
|
||||
2. 著者が作ったAIキャラクターが質問に答える
|
||||
3. その会話をatprotoに投稿する
|
||||
4. その会話をblogに表示する
|
||||
|
||||
とはいえ、会話は`claude`を使用します。依存関係が多すぎて汎用的な仕組みではありません。
|
||||
|
||||
これを汎用的な仕組みで作る場合、repositoryを分離して新しく作る必要があるでしょう。
|
||||
|
||||
example: [/posts/2025-07-16-6bf4b020.html](/posts/2025-07-16-6bf4b020.html)
|
@@ -1,64 +0,0 @@
|
||||
---
|
||||
title: "ue5のgaspとdragonikを組み合わせてenemyを作る"
|
||||
slug: "gasp-dragonik-enemy-chbcharacter"
|
||||
date: "2025-07-30"
|
||||
tags: ["ue"]
|
||||
draft: false
|
||||
---
|
||||
|
||||
ue5.6でgasp(game animation sample project)をベースにゲーム、特にキャラクターの操作を作っています。
|
||||
|
||||
そして、enemy(敵)を作り、バトルシーンを作成する予定ですが、これはどのように開発すればいいのでしょう。その方針を明確にします。
|
||||
|
||||
1. enemyもgaspの`cbp_character`に統合し、自キャラ、敵キャラどちらでも使用可能にする
|
||||
2. 2番目のcharacterは動物型(type:animal)にし、gaspに統合する
|
||||
3. enemyとして使用する場合は、enemy-AI-componentを追加するだけで完結する
|
||||
4. characterのすべての操作を統一する
|
||||
|
||||
このようにすることで、応用可能なenemyを作ることができます。
|
||||
|
||||
例えば、`2番目のcharacterは動物型(type:animal)にする`というのはどういうことでしょう。
|
||||
|
||||
登場するキャラクターを人型(type:human), 動物型(type:animal)に分けるとして、動物型のテンプレートを作る必要があります。そのまま動物のmeshをgaspで使うと動きが変になってしまうので、それを調整する必要があるということ。そして、調整したものをテンプレート化して、他の動物にも適用できるようにしておくと、後の開発は楽ですよね。
|
||||
|
||||
ですから、早いうちにtype:humanから脱却し、他のtypeを作るほうがいいと判断しました。
|
||||
|
||||
これには、`dragon ik plugin`を使って、手っ取り早く動きを作ります。
|
||||
|
||||
`characterのすべての操作を統一する`というのは、1キャラにつき1属性、1通常攻撃、1スキル、1バースト、などのルールを作り、それらを共通化することです。共通化というのは、playerもenemy-AI-componentも違うキャラを同じ操作で使用できることを指します。
|
||||
|
||||
## 2番目のキャラクター
|
||||
|
||||
原作には、西洋ドラゴンのドライ(drai)というキャラが登場します。その父親が東洋ドラゴンのシンオウ(shin-oh)です。これをshinという名前で登録し、2番目のキャラクターとして設定しました。
|
||||
|
||||
3d-modelは今のところue5のcrsp(control rig sample project)にあるchinese dragonを使用しています。後に改造して原作に近づけるようにしたいところですが、今は時間が取れません。
|
||||
|
||||
<iframe width="100%" height="415" src="https://www.youtube.com/embed/3c3Q1Z5r7QI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
|
||||
|
||||
## データ構造の作成と適用
|
||||
|
||||
ゲームデータはatproto collection recordに保存して、そこからゲームに反映させたいと考えています。
|
||||
|
||||
まず基本データを`ai.syui.ai`のアカウントに保存。個別データをplayerのatprotoアカウントに保存する形が理想です。
|
||||
|
||||
基本データは、ゲームの基本的な設定のこと。例えば、キャラクターの名前や属性、スキルなど変更されることがない値。
|
||||
|
||||
個別データは、プレイヤーが使えるキャラ、レベル、攻撃力など、ゲームの進行とともに変更される値です。
|
||||
|
||||
ゲームをスタートさせると、まず基本データを取得し、それを`cbp_character`に適用します。ログインすると、`cbp_character`の変数(var)に値が振り分けられます。例えば、`skill-damage:0.0`があったとして、この値が変わります。
|
||||
|
||||
しかし、ゲームを開発していると、基本データも個別データも構造が複雑になります。
|
||||
|
||||
それを防ぐため、`{simple, core} mode`のような考え方を取り入れます。必要最小限の構成を分離、保存して、それをいつでも統合、適用できるように設計しておきます。
|
||||
|
||||
## gaspとdragonikを統合する方法
|
||||
|
||||
では、いよいよgaspとdragonikの統合手法を解説します。
|
||||
|
||||
まず、abpを作ります。それにdragonikを当て、それをSKM_Dragonのpost process animに指定します。
|
||||
|
||||

|
||||
|
||||
次に、動きに合わせて首を上下させます。
|
||||
|
||||
<iframe src="https://blueprintue.com/render/piiw14oz" scrolling="no" allowfullscreen style="width:100%;height:400px"></iframe>
|
@@ -1,14 +0,0 @@
|
||||
{{- $type := .Get "type" | default "info" -}}
|
||||
{{- $content := .Get "content" -}}
|
||||
<div class="msg msg-{{ $type }}">
|
||||
<div class="msg-icon">
|
||||
{{- if eq $type "info" -}}ℹ️
|
||||
{{- else if eq $type "warning" -}}⚠️
|
||||
{{- else if eq $type "error" -}}❌
|
||||
{{- else if eq $type "success" -}}✅
|
||||
{{- else if eq $type "note" -}}📝
|
||||
{{- else -}}ℹ️
|
||||
{{- end -}}
|
||||
</div>
|
||||
<div class="msg-content">{{ $content | markdownify }}</div>
|
||||
</div>
|
20
my-blog/oauth/.env.production
Normal file
@@ -0,0 +1,20 @@
|
||||
# Production environment variables
|
||||
VITE_APP_HOST=https://syui.ai
|
||||
VITE_OAUTH_CLIENT_ID=https://syui.ai/client-metadata.json
|
||||
VITE_OAUTH_REDIRECT_URI=https://syui.ai/oauth/callback
|
||||
|
||||
# Handle-based Configuration (DIDs resolved at runtime)
|
||||
VITE_ATPROTO_PDS=syu.is
|
||||
VITE_ADMIN_HANDLE=ai.syui.ai
|
||||
VITE_AI_HANDLE=ai.syui.ai
|
||||
VITE_OAUTH_COLLECTION=ai.syui.log
|
||||
VITE_ATPROTO_WEB_URL=https://bsky.app
|
||||
VITE_ATPROTO_HANDLE_LIST=["syui.syui.ai", "ai.syui.ai", "ai.ai"]
|
||||
|
||||
# AI Configuration
|
||||
VITE_AI_ENABLED=true
|
||||
VITE_AI_ASK_AI=true
|
||||
VITE_AI_PROVIDER=ollama
|
||||
VITE_AI_MODEL=qwen3
|
||||
VITE_AI_HOST=http://localhost:11434
|
||||
VITE_AI_SYSTEM_PROMPT="あなたは6歳の女の子アイです。明るく元気で、ちょっとおっちょこちょい。自分のことは「アイ」って呼びます。白と金のワンピース姿。 相手のことが大好きで、ときどき甘えたり、照れたりします。 でも、宇宙とかAIとか、難しい話にもすっごく詳しいの。専門的なことも、がんばって子どもっぽく教えようとします。不思議な力を持っています。小さい物質のことをよく知っているようです。"
|
@@ -1,345 +0,0 @@
|
||||
@import url('./style.css');
|
||||
|
||||
.pds-container {
|
||||
}
|
||||
|
||||
.pds-header {
|
||||
text-align: center;
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
|
||||
.pds-header h1 {
|
||||
font-size: 2.5em;
|
||||
margin-bottom: 10px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.pds-search-section {
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.pds-search-form {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 0px 20px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.form-group input {
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px 0 0 4px;
|
||||
font-size: 14px;
|
||||
width: 600px;
|
||||
outline: none;
|
||||
transition: box-shadow 0.2s, border-color 0.2s;
|
||||
}
|
||||
|
||||
.form-group input:focus {
|
||||
border-color: var(--theme-color, #f40);
|
||||
}
|
||||
|
||||
.form-group button {
|
||||
padding: 9px 15px;
|
||||
background: #1976d2;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 0 4px 4px 0;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.form-group button:hover {
|
||||
background: #1565c0;
|
||||
}
|
||||
|
||||
/*
|
||||
.user-info {
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
*/
|
||||
|
||||
.user-profile {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.user-details h3 {
|
||||
margin: 0 0 5px 0;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.user-details p {
|
||||
margin: 0;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.user-did-section {
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.did-display {
|
||||
padding: 10px;
|
||||
background: #f5f5f5;
|
||||
border-radius: 4px;
|
||||
font-family: monospace;
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
word-break: break-all;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.handle-display {
|
||||
padding: 8px 10px;
|
||||
background: #f0f9f0;
|
||||
border-radius: 4px;
|
||||
font-size: 13px;
|
||||
color: #555;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.handle-display strong {
|
||||
color: #2e7d32;
|
||||
}
|
||||
|
||||
.handle-display span {
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
|
||||
.pds-display {
|
||||
padding: 8px 10px;
|
||||
background: #e8f4f8;
|
||||
border-radius: 4px;
|
||||
font-size: 13px;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
.pds-display strong {
|
||||
color: #1976d2;
|
||||
}
|
||||
|
||||
.pds-display span {
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.collections-section,
|
||||
.records-section {
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.collections-section h3,
|
||||
.records-section h3 {
|
||||
font-size: 1.2em;
|
||||
margin-bottom: 15px;
|
||||
color: #333;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.collections-list,
|
||||
.records-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.at-uri-link {
|
||||
display: block;
|
||||
padding: 8px 12px;
|
||||
background: #f9f9f9;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #e0e0e0;
|
||||
color: #1976d2;
|
||||
text-decoration: none;
|
||||
font-family: monospace;
|
||||
font-size: 14px;
|
||||
word-break: break-all;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.at-uri-link:hover {
|
||||
background: #e8f4f8;
|
||||
border-color: #1976d2;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.pds-info {
|
||||
padding: 8px 12px;
|
||||
background: #f0f9ff;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #b3e5fc;
|
||||
margin-bottom: 8px;
|
||||
color: #1976d2;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.collection-info {
|
||||
padding: 8px 12px;
|
||||
background: #f0f9f0;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #b3e5b3;
|
||||
margin-bottom: 8px;
|
||||
color: #2e7d32;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.collections-header {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.collections-toggle {
|
||||
background: #f5f5f5;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
color: #333;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
.collections-toggle:hover {
|
||||
background: #e8f4f8;
|
||||
border-color: #1976d2;
|
||||
}
|
||||
|
||||
|
||||
.pds-test-section,
|
||||
.pds-about-section {
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
|
||||
.pds-test-section h2,
|
||||
.pds-about-section h2 {
|
||||
font-size: 1.8em;
|
||||
margin-bottom: 20px;
|
||||
color: #333;
|
||||
border-bottom: 2px solid #1976d2;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
.test-uris {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.at-uri {
|
||||
background: #f5f5f5;
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
font-family: monospace;
|
||||
font-size: 14px;
|
||||
word-break: break-all;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
border: 1px solid #e0e0e0;
|
||||
}
|
||||
|
||||
.at-uri:hover {
|
||||
background: #e8f4f8;
|
||||
border-color: #1976d2;
|
||||
}
|
||||
|
||||
.pds-about-section ul {
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.pds-about-section li {
|
||||
padding: 5px 0;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
|
||||
/* AT URI Modal Styles */
|
||||
.at-uri-modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.at-uri-modal-content {
|
||||
background-color: white;
|
||||
border-radius: 8px;
|
||||
max-width: 800px;
|
||||
max-height: 600px;
|
||||
width: 90%;
|
||||
height: 80%;
|
||||
overflow: auto;
|
||||
position: relative;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.at-uri-modal-close {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
z-index: 1001;
|
||||
padding: 5px 10px;
|
||||
}
|
||||
|
||||
/* Loading states */
|
||||
.loading {
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.error {
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
color: #d32f2f;
|
||||
background: #ffeaea;
|
||||
border-radius: 4px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
/* Responsive design */
|
||||
@media (max-width: 768px) {
|
||||
.pds-search-section {
|
||||
display: none;
|
||||
}
|
||||
.pds-search-form {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.form-group input {
|
||||
width: 100%;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 263 KiB |
Before Width: | Height: | Size: 256 KiB |
Before Width: | Height: | Size: 49 KiB |
Before Width: | Height: | Size: 1.5 MiB |
Before Width: | Height: | Size: 1.5 MiB |
Before Width: | Height: | Size: 1.6 MiB |
Before Width: | Height: | Size: 1.6 MiB |
Before Width: | Height: | Size: 1.9 MiB |
Before Width: | Height: | Size: 2.0 MiB |
Before Width: | Height: | Size: 2.0 MiB |
Before Width: | Height: | Size: 1.2 MiB |
Before Width: | Height: | Size: 723 KiB |
@@ -5,22 +5,6 @@
|
||||
// Global variables for AI functionality
|
||||
let aiProfileData = null;
|
||||
|
||||
// Get config from window or use defaults
|
||||
const OAUTH_PDS = window.OAUTH_CONFIG?.pds || 'syu.is';
|
||||
const ADMIN_HANDLE = window.OAUTH_CONFIG?.admin || 'ai.syui.ai';
|
||||
const OAUTH_COLLECTION = window.OAUTH_CONFIG?.collection || 'ai.syui.log';
|
||||
|
||||
// Listen for AI profile data from OAuth app
|
||||
window.addEventListener('aiProfileLoaded', function(event) {
|
||||
aiProfileData = event.detail;
|
||||
updateAskAIButton();
|
||||
});
|
||||
|
||||
// Check if AI profile data is already available
|
||||
if (window.aiProfileData) {
|
||||
aiProfileData = window.aiProfileData;
|
||||
}
|
||||
|
||||
// Original functions from working implementation
|
||||
function toggleAskAI() {
|
||||
const panel = document.getElementById('askAiPanel');
|
||||
@@ -28,82 +12,24 @@ function toggleAskAI() {
|
||||
panel.style.display = isVisible ? 'none' : 'block';
|
||||
|
||||
if (!isVisible) {
|
||||
|
||||
// If AI profile data is already available, show introduction immediately
|
||||
if (aiProfileData) {
|
||||
// Quick check for authentication
|
||||
const userSections = document.querySelectorAll('.user-section');
|
||||
const isAuthenticated = userSections.length > 0;
|
||||
handleAuthenticationStatus(isAuthenticated);
|
||||
return;
|
||||
}
|
||||
|
||||
// For production fallback - if OAuth app fails to load, show profiles
|
||||
const isProd = window.location.hostname !== 'localhost' && !window.location.hostname.includes('preview');
|
||||
if (isProd) {
|
||||
// Shorter timeout for production
|
||||
setTimeout(() => {
|
||||
const userSections = document.querySelectorAll('.user-section');
|
||||
|
||||
if (userSections.length === 0) {
|
||||
handleAuthenticationStatus(false);
|
||||
} else {
|
||||
handleAuthenticationStatus(true);
|
||||
}
|
||||
}, 300);
|
||||
} else {
|
||||
checkAuthenticationStatus();
|
||||
}
|
||||
checkAuthenticationStatus();
|
||||
}
|
||||
}
|
||||
|
||||
function checkAuthenticationStatus() {
|
||||
// Check multiple times for OAuth app to load
|
||||
let checkCount = 0;
|
||||
const maxChecks = 10;
|
||||
|
||||
const checkForAuth = () => {
|
||||
const userSections = document.querySelectorAll('.user-section');
|
||||
const authButtons = document.querySelectorAll('[data-auth-status]');
|
||||
const oauthContainers = document.querySelectorAll('#oauth-container');
|
||||
|
||||
|
||||
const isAuthenticated = userSections.length > 0;
|
||||
|
||||
if (isAuthenticated || checkCount >= maxChecks - 1) {
|
||||
handleAuthenticationStatus(isAuthenticated);
|
||||
} else {
|
||||
checkCount++;
|
||||
setTimeout(checkForAuth, 200);
|
||||
}
|
||||
};
|
||||
|
||||
checkForAuth();
|
||||
}
|
||||
|
||||
function handleAuthenticationStatus(isAuthenticated) {
|
||||
|
||||
// Always hide loading first
|
||||
document.getElementById('authCheck').style.display = 'none';
|
||||
const userSections = document.querySelectorAll('.user-section');
|
||||
const isAuthenticated = userSections.length > 0;
|
||||
|
||||
if (isAuthenticated) {
|
||||
// User is authenticated - show Ask AI UI
|
||||
document.getElementById('authCheck').style.display = 'none';
|
||||
document.getElementById('chatForm').style.display = 'block';
|
||||
document.getElementById('chatHistory').style.display = 'block';
|
||||
|
||||
// Show initial greeting if chat history is empty and AI profile is available
|
||||
// Show initial greeting if chat history is empty
|
||||
const chatHistory = document.getElementById('chatHistory');
|
||||
if (chatHistory.children.length === 0) {
|
||||
if (aiProfileData) {
|
||||
showInitialGreeting();
|
||||
} else {
|
||||
// Wait for AI profile data
|
||||
setTimeout(() => {
|
||||
if (aiProfileData) {
|
||||
showInitialGreeting();
|
||||
}
|
||||
}, 500);
|
||||
}
|
||||
showInitialGreeting();
|
||||
}
|
||||
|
||||
// Focus on input
|
||||
@@ -111,78 +37,10 @@ function handleAuthenticationStatus(isAuthenticated) {
|
||||
document.getElementById('aiQuestion').focus();
|
||||
}, 50);
|
||||
} else {
|
||||
// User not authenticated - show AI introduction directly if profile available
|
||||
// User not authenticated - show auth message
|
||||
document.getElementById('authCheck').style.display = 'block';
|
||||
document.getElementById('chatForm').style.display = 'none';
|
||||
document.getElementById('chatHistory').style.display = 'block';
|
||||
|
||||
if (aiProfileData) {
|
||||
// Show AI introduction directly using available profile data
|
||||
showAIIntroduction();
|
||||
} else {
|
||||
// Fallback to profile loading
|
||||
loadAndShowProfiles();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Load and display profiles from ai.syui.log.profile collection
|
||||
async function loadAndShowProfiles() {
|
||||
const chatHistory = document.getElementById('chatHistory');
|
||||
chatHistory.innerHTML = '<div class="loading-message">Loading profiles...</div>';
|
||||
|
||||
try {
|
||||
const response = await fetch(`https://${OAUTH_PDS}/xrpc/com.atproto.repo.listRecords?repo=${ADMIN_HANDLE}&collection=${OAUTH_COLLECTION}&limit=100`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch profiles');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Filter only profile records and sort
|
||||
const profileRecords = (data.records || []).filter(record => record.value.type === 'profile');
|
||||
|
||||
const profiles = profileRecords.sort((a, b) => {
|
||||
if (a.value.profileType === 'admin' && b.value.profileType !== 'admin') return -1;
|
||||
if (a.value.profileType !== 'admin' && b.value.profileType === 'admin') return 1;
|
||||
return 0;
|
||||
});
|
||||
|
||||
// Clear loading message
|
||||
chatHistory.innerHTML = '';
|
||||
|
||||
// Display profiles using the same format as chat
|
||||
profiles.forEach(profile => {
|
||||
const profileDiv = document.createElement('div');
|
||||
profileDiv.className = 'chat-message ai-message comment-style';
|
||||
|
||||
const avatarElement = profile.value.author.avatar
|
||||
? `<img src="${profile.value.author.avatar}" alt="${profile.value.author.displayName || profile.value.author.handle}" class="profile-avatar">`
|
||||
: `<div class="profile-avatar-fallback">${(profile.value.author.displayName || profile.value.author.handle || '?').charAt(0).toUpperCase()}</div>`;
|
||||
|
||||
const adminBadge = profile.value.profileType === 'admin'
|
||||
? '<span class="admin-badge">Admin</span>'
|
||||
: '';
|
||||
|
||||
profileDiv.innerHTML = `
|
||||
<div class="message-header">
|
||||
<div class="avatar">${avatarElement}</div>
|
||||
<div class="user-info">
|
||||
<div class="display-name">${profile.value.author.displayName || profile.value.author.handle} ${adminBadge}</div>
|
||||
<div class="handle"><a href="https://${OAUTH_PDS}/profile/${profile.value.author.handle}" target="_blank" rel="noopener noreferrer">@${profile.value.author.handle}</a></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="message-content">${profile.value.text}</div>
|
||||
`;
|
||||
chatHistory.appendChild(profileDiv);
|
||||
});
|
||||
|
||||
if (profiles.length === 0) {
|
||||
chatHistory.innerHTML = '<div class="no-profiles">No profiles available</div>';
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
chatHistory.innerHTML = '<div class="error-message">Failed to load profiles. Please try again later.</div>';
|
||||
document.getElementById('chatHistory').style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,6 +68,7 @@ function askQuestion() {
|
||||
}));
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to ask question:', error);
|
||||
showErrorMessage('Sorry, I encountered an error. Please try again.');
|
||||
} finally {
|
||||
askButton.disabled = false;
|
||||
@@ -248,7 +107,8 @@ function addUserMessage(question) {
|
||||
<div class="avatar">${userAvatar}</div>
|
||||
<div class="user-info">
|
||||
<div class="display-name">${userDisplay}</div>
|
||||
<div class="handle"><a href="https://${OAUTH_PDS}/profile/${userHandle}" target="_blank" rel="noopener noreferrer">@${userHandle}</a></div>
|
||||
<div class="handle">@${userHandle}</div>
|
||||
<div class="timestamp">${new Date().toLocaleString()}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="message-content">${question}</div>
|
||||
@@ -311,57 +171,17 @@ function showInitialGreeting() {
|
||||
<div class="avatar">${avatarElement}</div>
|
||||
<div class="user-info">
|
||||
<div class="display-name">${aiProfileData.displayName}</div>
|
||||
<div class="handle"><a href="https://${OAUTH_PDS}/profile/${aiProfileData.handle}" target="_blank" rel="noopener noreferrer">@${aiProfileData.handle}</a></div>
|
||||
<div class="handle">@${aiProfileData.handle}</div>
|
||||
<div class="timestamp">${new Date().toLocaleString()}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="message-content">Hello! I'm an AI assistant trained on this blog's content. I can answer questions about the articles, provide insights, and help you understand the topics discussed here. What would you like to know?</div>
|
||||
<div class="message-content">
|
||||
Hello! I'm an AI assistant trained on this blog's content. I can answer questions about the articles, provide insights, and help you understand the topics discussed here. What would you like to know?
|
||||
</div>
|
||||
`;
|
||||
chatHistory.appendChild(greetingDiv);
|
||||
}
|
||||
|
||||
function showAIIntroduction() {
|
||||
if (!aiProfileData) return;
|
||||
|
||||
const chatHistory = document.getElementById('chatHistory');
|
||||
chatHistory.innerHTML = ''; // Clear any existing content
|
||||
|
||||
// AI Introduction message
|
||||
const introDiv = document.createElement('div');
|
||||
introDiv.className = 'chat-message ai-message comment-style initial-greeting';
|
||||
|
||||
const avatarElement = aiProfileData.avatar
|
||||
? `<img src="${aiProfileData.avatar}" alt="${aiProfileData.displayName}" class="profile-avatar">`
|
||||
: '🤖';
|
||||
|
||||
introDiv.innerHTML = `
|
||||
<div class="message-header">
|
||||
<div class="avatar">${avatarElement}</div>
|
||||
<div class="user-info">
|
||||
<div class="display-name">${aiProfileData.displayName}</div>
|
||||
<div class="handle"><a href="https://${OAUTH_PDS}/profile/${aiProfileData.handle}" target="_blank" rel="noopener noreferrer">@${aiProfileData.handle}</a></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="message-content">Hello! I'm an AI assistant trained on this blog's content. I can answer questions about the articles, provide insights, and help you understand the topics discussed here. What would you like to know?</div>
|
||||
`;
|
||||
chatHistory.appendChild(introDiv);
|
||||
|
||||
// OAuth login message
|
||||
const loginDiv = document.createElement('div');
|
||||
loginDiv.className = 'chat-message user-message comment-style initial-greeting';
|
||||
|
||||
loginDiv.innerHTML = `
|
||||
<div class="message-header">
|
||||
<div class="avatar">${avatarElement}</div>
|
||||
<div class="user-info">
|
||||
<div class="display-name">${aiProfileData.displayName}</div>
|
||||
<div class="handle"><a href="https://${OAUTH_PDS}/profile/${aiProfileData.handle}" target="_blank" rel="noopener noreferrer">@${aiProfileData.handle}</a></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="message-content">Please atproto oauth login</div>
|
||||
`;
|
||||
chatHistory.appendChild(loginDiv);
|
||||
}
|
||||
|
||||
function updateAskAIButton() {
|
||||
const button = document.getElementById('askAiButton');
|
||||
if (!button) return;
|
||||
@@ -381,6 +201,7 @@ function handleAIResponse(responseData) {
|
||||
|
||||
const aiProfile = responseData.aiProfile;
|
||||
if (!aiProfile || !aiProfile.handle || !aiProfile.displayName) {
|
||||
console.error('AI profile data is missing');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -396,7 +217,8 @@ function handleAIResponse(responseData) {
|
||||
<div class="avatar">${avatarElement}</div>
|
||||
<div class="user-info">
|
||||
<div class="display-name">${aiProfile.displayName}</div>
|
||||
<div class="handle"><a href="https://${OAUTH_PDS}/profile/${aiProfile.handle}" target="_blank" rel="noopener noreferrer">@${aiProfile.handle}</a></div>
|
||||
<div class="handle">@${aiProfile.handle}</div>
|
||||
<div class="timestamp">${timestamp.toLocaleString()}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="message-content">${responseData.answer}</div>
|
||||
@@ -422,6 +244,7 @@ function setupAskAIEventListeners() {
|
||||
// Listen for AI profile updates from OAuth app
|
||||
window.addEventListener('aiProfileLoaded', function(event) {
|
||||
aiProfileData = event.detail;
|
||||
console.log('AI profile loaded:', aiProfileData);
|
||||
updateAskAIButton();
|
||||
});
|
||||
|
||||
@@ -430,23 +253,6 @@ function setupAskAIEventListeners() {
|
||||
handleAIResponse(event.detail);
|
||||
});
|
||||
|
||||
// Listen for OAuth callback completion from iframe
|
||||
window.addEventListener('message', function(event) {
|
||||
if (event.data.type === 'oauth_success') {
|
||||
|
||||
// Close any OAuth popups/iframes
|
||||
const oauthFrame = document.getElementById('oauth-frame');
|
||||
if (oauthFrame) {
|
||||
oauthFrame.remove();
|
||||
}
|
||||
|
||||
// Reload the page to refresh OAuth app state
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Track IME composition state
|
||||
let isComposing = false;
|
||||
const aiQuestionInput = document.getElementById('aiQuestion');
|
||||
@@ -481,36 +287,7 @@ function setupAskAIEventListeners() {
|
||||
// Initialize Ask AI when DOM is loaded
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
setupAskAIEventListeners();
|
||||
|
||||
// Also listen for OAuth app load completion
|
||||
const observer = new MutationObserver(function(mutations) {
|
||||
mutations.forEach(function(mutation) {
|
||||
if (mutation.type === 'childList') {
|
||||
// Check if user-section was added/removed
|
||||
const userSectionAdded = Array.from(mutation.addedNodes).some(node =>
|
||||
node.nodeType === Node.ELEMENT_NODE &&
|
||||
(node.classList?.contains('user-section') || node.querySelector?.('.user-section'))
|
||||
);
|
||||
const userSectionRemoved = Array.from(mutation.removedNodes).some(node =>
|
||||
node.nodeType === Node.ELEMENT_NODE &&
|
||||
(node.classList?.contains('user-section') || node.querySelector?.('.user-section'))
|
||||
);
|
||||
|
||||
if (userSectionAdded || userSectionRemoved) {
|
||||
// Update Ask AI panel if it's visible
|
||||
const panel = document.getElementById('askAiPanel');
|
||||
if (panel && panel.style.display !== 'none') {
|
||||
checkAuthenticationStatus();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
observer.observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true
|
||||
});
|
||||
console.log('Ask AI initialized successfully');
|
||||
});
|
||||
|
||||
// Global functions for onclick handlers
|
||||
|
@@ -1,123 +0,0 @@
|
||||
/**
|
||||
* Image Comparison Slider
|
||||
* UE5-style before/after image comparison component
|
||||
*/
|
||||
|
||||
class ImageComparison {
|
||||
constructor(container) {
|
||||
this.container = container;
|
||||
this.slider = container.querySelector('.slider');
|
||||
this.beforeImg = container.querySelector('.img-before');
|
||||
this.afterImg = container.querySelector('.img-after');
|
||||
this.sliderThumb = container.querySelector('.slider-thumb');
|
||||
|
||||
this.isDragging = false;
|
||||
this.containerRect = null;
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.bindEvents();
|
||||
this.updatePosition(50); // Start at 50%
|
||||
}
|
||||
|
||||
bindEvents() {
|
||||
// Mouse events
|
||||
this.slider.addEventListener('input', (e) => {
|
||||
this.updatePosition(e.target.value);
|
||||
});
|
||||
|
||||
this.slider.addEventListener('mousedown', () => {
|
||||
this.isDragging = true;
|
||||
document.body.style.userSelect = 'none';
|
||||
});
|
||||
|
||||
document.addEventListener('mouseup', () => {
|
||||
if (this.isDragging) {
|
||||
this.isDragging = false;
|
||||
document.body.style.userSelect = '';
|
||||
}
|
||||
});
|
||||
|
||||
// Touch events for mobile
|
||||
this.slider.addEventListener('touchstart', (e) => {
|
||||
this.isDragging = true;
|
||||
e.preventDefault();
|
||||
});
|
||||
|
||||
this.slider.addEventListener('touchmove', (e) => {
|
||||
if (this.isDragging) {
|
||||
const touch = e.touches[0];
|
||||
this.containerRect = this.container.getBoundingClientRect();
|
||||
const x = touch.clientX - this.containerRect.left;
|
||||
const percentage = Math.max(0, Math.min(100, (x / this.containerRect.width) * 100));
|
||||
this.slider.value = percentage;
|
||||
this.updatePosition(percentage);
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
this.slider.addEventListener('touchend', () => {
|
||||
this.isDragging = false;
|
||||
});
|
||||
|
||||
// Direct click on container
|
||||
this.container.addEventListener('click', (e) => {
|
||||
if (e.target === this.container || e.target.classList.contains('img-comparison-slider')) {
|
||||
this.containerRect = this.container.getBoundingClientRect();
|
||||
const x = e.clientX - this.containerRect.left;
|
||||
const percentage = Math.max(0, Math.min(100, (x / this.containerRect.width) * 100));
|
||||
this.slider.value = percentage;
|
||||
this.updatePosition(percentage);
|
||||
}
|
||||
});
|
||||
|
||||
// Keyboard support
|
||||
this.slider.addEventListener('keydown', (e) => {
|
||||
let value = parseFloat(this.slider.value);
|
||||
switch (e.key) {
|
||||
case 'ArrowLeft':
|
||||
value = Math.max(0, value - 1);
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
value = Math.min(100, value + 1);
|
||||
break;
|
||||
case 'Home':
|
||||
value = 0;
|
||||
break;
|
||||
case 'End':
|
||||
value = 100;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
this.slider.value = value;
|
||||
this.updatePosition(value);
|
||||
});
|
||||
}
|
||||
|
||||
updatePosition(percentage) {
|
||||
const position = parseFloat(percentage);
|
||||
|
||||
// Update clip-path for before image to show only the left portion
|
||||
this.beforeImg.style.clipPath = `inset(0 ${100 - position}% 0 0)`;
|
||||
|
||||
// Update slider thumb position
|
||||
this.sliderThumb.style.left = `${position}%`;
|
||||
this.sliderThumb.style.transform = `translateX(-50%)`;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-initialize all image comparison components
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const comparisons = document.querySelectorAll('.img-comparison-container');
|
||||
comparisons.forEach(container => {
|
||||
new ImageComparison(container);
|
||||
});
|
||||
});
|
||||
|
||||
// Export for manual initialization
|
||||
window.ImageComparison = ImageComparison;
|
@@ -1,370 +0,0 @@
|
||||
// AT Protocol API functions
|
||||
const AT_PROTOCOL_CONFIG = {
|
||||
primary: {
|
||||
pds: 'https://syu.is',
|
||||
plc: 'https://plc.syu.is',
|
||||
bsky: 'https://bsky.syu.is',
|
||||
web: 'https://web.syu.is'
|
||||
},
|
||||
fallback: {
|
||||
pds: 'https://bsky.social',
|
||||
plc: 'https://plc.directory',
|
||||
bsky: 'https://public.api.bsky.app',
|
||||
web: 'https://bsky.app'
|
||||
}
|
||||
};
|
||||
|
||||
// Search user function
|
||||
async function searchUser() {
|
||||
const handleInput = document.getElementById('handleInput');
|
||||
const userInfo = document.getElementById('userInfo');
|
||||
const collectionsList = document.getElementById('collectionsList');
|
||||
const recordsList = document.getElementById('recordsList');
|
||||
const searchButton = document.getElementById('searchButton');
|
||||
|
||||
const input = handleInput.value.trim();
|
||||
if (!input) {
|
||||
alert('Handle nameまたはAT URIを入力してください');
|
||||
return;
|
||||
}
|
||||
|
||||
searchButton.disabled = true;
|
||||
searchButton.innerHTML = '@';
|
||||
//searchButton.innerHTML = '<i class="fab fa-bluesky"></i>';
|
||||
|
||||
try {
|
||||
// Clear previous results
|
||||
document.getElementById('userDidSection').style.display = 'none';
|
||||
document.getElementById('collectionsSection').style.display = 'none';
|
||||
document.getElementById('recordsSection').style.display = 'none';
|
||||
collectionsList.innerHTML = '';
|
||||
recordsList.innerHTML = '';
|
||||
|
||||
// Check if input is AT URI
|
||||
if (input.startsWith('at://')) {
|
||||
// Parse AT URI to check if it's a full record or just a handle/collection
|
||||
const uriParts = input.replace('at://', '').split('/').filter(part => part.length > 0);
|
||||
|
||||
if (uriParts.length >= 3) {
|
||||
// Full AT URI with rkey - show in modal
|
||||
showAtUriModal(input);
|
||||
return;
|
||||
} else if (uriParts.length === 1) {
|
||||
// Just handle in AT URI format (at://handle) - treat as regular handle
|
||||
const handle = uriParts[0];
|
||||
const userProfile = await resolveUserProfile(handle);
|
||||
|
||||
if (userProfile.success) {
|
||||
displayUserDid(userProfile.data);
|
||||
await loadUserCollections(handle, userProfile.data.did);
|
||||
} else {
|
||||
alert('ユーザーが見つかりません: ' + userProfile.error);
|
||||
}
|
||||
return;
|
||||
} else if (uriParts.length === 2) {
|
||||
// Collection level AT URI - load collection records
|
||||
const [repo, collection] = uriParts;
|
||||
|
||||
try {
|
||||
// First resolve the repo to get handle if it's a DID
|
||||
let handle = repo;
|
||||
if (repo.startsWith('did:')) {
|
||||
// Try to resolve DID to handle - for now just use the DID
|
||||
handle = repo;
|
||||
}
|
||||
|
||||
loadCollectionRecords(handle, collection, repo);
|
||||
} catch (error) {
|
||||
alert('コレクションの読み込みに失敗しました: ' + error.message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle regular handle search
|
||||
const userProfile = await resolveUserProfile(input);
|
||||
|
||||
if (userProfile.success) {
|
||||
displayUserDid(userProfile.data);
|
||||
await loadUserCollections(input, userProfile.data.did);
|
||||
} else {
|
||||
alert('ユーザーが見つかりません: ' + userProfile.error);
|
||||
}
|
||||
} catch (error) {
|
||||
alert('エラーが発生しました: ' + error.message);
|
||||
} finally {
|
||||
searchButton.disabled = false;
|
||||
searchButton.innerHTML = '@';
|
||||
//searchButton.innerHTML = '<i class="fab fa-bluesky"></i>';
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve user profile
|
||||
async function resolveUserProfile(handle) {
|
||||
try {
|
||||
let response = null;
|
||||
|
||||
// Try syu.is first
|
||||
try {
|
||||
response = await fetch(`${AT_PROTOCOL_CONFIG.primary.pds}/xrpc/com.atproto.repo.describeRepo?repo=${handle}`);
|
||||
} catch (error) {
|
||||
console.log('Failed to resolve from syu.is:', error);
|
||||
}
|
||||
|
||||
// If syu.is fails, try bsky.social
|
||||
if (!response || !response.ok) {
|
||||
response = await fetch(`${AT_PROTOCOL_CONFIG.fallback.pds}/xrpc/com.atproto.repo.describeRepo?repo=${handle}`);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to resolve handle');
|
||||
}
|
||||
|
||||
const repoData = await response.json();
|
||||
|
||||
// Get profile data
|
||||
const profileResponse = await fetch(`${AT_PROTOCOL_CONFIG.fallback.bsky}/xrpc/app.bsky.actor.getProfile?actor=${repoData.did}`);
|
||||
const profileData = await profileResponse.json();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
did: repoData.did,
|
||||
handle: profileData.handle,
|
||||
displayName: profileData.displayName,
|
||||
avatar: profileData.avatar,
|
||||
description: profileData.description,
|
||||
pds: repoData.didDoc.service.find(s => s.type === 'AtprotoPersonalDataServer')?.serviceEndpoint
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Display user DID
|
||||
function displayUserDid(profile) {
|
||||
document.getElementById('userPdsText').textContent = profile.pds || 'Unknown';
|
||||
document.getElementById('userHandleText').textContent = profile.handle;
|
||||
document.getElementById('userDidText').textContent = profile.did;
|
||||
document.getElementById('userDidSection').style.display = 'block';
|
||||
}
|
||||
|
||||
// Load user collections
|
||||
async function loadUserCollections(handle, did) {
|
||||
const collectionsList = document.getElementById('collectionsList');
|
||||
|
||||
collectionsList.innerHTML = '<div class="loading">コレクションを読み込み中...</div>';
|
||||
|
||||
try {
|
||||
// Try to get collections from describeRepo
|
||||
let response = await fetch(`${AT_PROTOCOL_CONFIG.primary.pds}/xrpc/com.atproto.repo.describeRepo?repo=${handle}`);
|
||||
let usedPds = AT_PROTOCOL_CONFIG.primary.pds;
|
||||
|
||||
// If syu.is fails, try bsky.social
|
||||
if (!response.ok) {
|
||||
response = await fetch(`${AT_PROTOCOL_CONFIG.fallback.pds}/xrpc/com.atproto.repo.describeRepo?repo=${handle}`);
|
||||
usedPds = AT_PROTOCOL_CONFIG.fallback.pds;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to describe repository');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const collections = data.collections || [];
|
||||
|
||||
// Display collections as AT URI links
|
||||
collectionsList.innerHTML = '';
|
||||
if (collections.length === 0) {
|
||||
collectionsList.innerHTML = '<div class="error">コレクションが見つかりませんでした</div>';
|
||||
} else {
|
||||
|
||||
collections.forEach(collection => {
|
||||
const atUri = `at://${did}/${collection}/`;
|
||||
const collectionElement = document.createElement('a');
|
||||
collectionElement.className = 'at-uri-link';
|
||||
collectionElement.href = '#';
|
||||
collectionElement.textContent = atUri;
|
||||
collectionElement.onclick = (e) => {
|
||||
e.preventDefault();
|
||||
loadCollectionRecords(handle, collection, did);
|
||||
// Close collections and update toggle
|
||||
document.getElementById('collectionsList').style.display = 'none';
|
||||
document.getElementById('collectionsToggle').textContent = '[-] Collections';
|
||||
};
|
||||
collectionsList.appendChild(collectionElement);
|
||||
});
|
||||
|
||||
document.getElementById('collectionsSection').style.display = 'block';
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
collectionsList.innerHTML = '<div class="error">コレクションの読み込みに失敗しました: ' + error.message + '</div>';
|
||||
document.getElementById('collectionsSection').style.display = 'block';
|
||||
}
|
||||
}
|
||||
|
||||
// Load collection records
|
||||
async function loadCollectionRecords(handle, collection, did) {
|
||||
const recordsList = document.getElementById('recordsList');
|
||||
|
||||
recordsList.innerHTML = '<div class="loading">レコードを読み込み中...</div>';
|
||||
|
||||
try {
|
||||
// Try with syu.is first
|
||||
let response = await fetch(`${AT_PROTOCOL_CONFIG.primary.pds}/xrpc/com.atproto.repo.listRecords?repo=${handle}&collection=${collection}`);
|
||||
let usedPds = AT_PROTOCOL_CONFIG.primary.pds;
|
||||
|
||||
// If that fails, try with bsky.social
|
||||
if (!response.ok) {
|
||||
response = await fetch(`${AT_PROTOCOL_CONFIG.fallback.pds}/xrpc/com.atproto.repo.listRecords?repo=${handle}&collection=${collection}`);
|
||||
usedPds = AT_PROTOCOL_CONFIG.fallback.pds;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to load records');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Display records as AT URI links
|
||||
recordsList.innerHTML = '';
|
||||
|
||||
// Add collection info for records
|
||||
const collectionInfo = document.createElement('div');
|
||||
collectionInfo.className = 'collection-info';
|
||||
collectionInfo.innerHTML = `<strong>${collection}</strong>`;
|
||||
recordsList.appendChild(collectionInfo);
|
||||
|
||||
data.records.forEach(record => {
|
||||
const atUri = record.uri;
|
||||
const recordElement = document.createElement('a');
|
||||
recordElement.className = 'at-uri-link';
|
||||
recordElement.href = '#';
|
||||
recordElement.textContent = atUri;
|
||||
recordElement.onclick = (e) => {
|
||||
e.preventDefault();
|
||||
showAtUriModal(atUri);
|
||||
};
|
||||
recordsList.appendChild(recordElement);
|
||||
});
|
||||
|
||||
document.getElementById('recordsSection').style.display = 'block';
|
||||
|
||||
} catch (error) {
|
||||
recordsList.innerHTML = '<div class="error">レコードの読み込みに失敗しました: ' + error.message + '</div>';
|
||||
document.getElementById('recordsSection').style.display = 'block';
|
||||
}
|
||||
}
|
||||
|
||||
// Show AT URI modal
|
||||
function showAtUriModal(uri) {
|
||||
const modal = document.getElementById('atUriModal');
|
||||
const content = document.getElementById('atUriContent');
|
||||
|
||||
content.innerHTML = '<div class="loading">レコードを読み込み中...</div>';
|
||||
modal.style.display = 'flex';
|
||||
|
||||
// Load record data
|
||||
loadAtUriRecord(uri, content);
|
||||
}
|
||||
|
||||
// Load AT URI record
|
||||
async function loadAtUriRecord(uri, contentElement) {
|
||||
try {
|
||||
const parts = uri.replace('at://', '').split('/');
|
||||
const repo = parts[0];
|
||||
const collection = parts[1];
|
||||
const rkey = parts[2];
|
||||
|
||||
// Try with syu.is first
|
||||
let response = await fetch(`${AT_PROTOCOL_CONFIG.primary.pds}/xrpc/com.atproto.repo.getRecord?repo=${repo}&collection=${collection}&rkey=${rkey}`);
|
||||
|
||||
// If that fails, try with bsky.social
|
||||
if (!response.ok) {
|
||||
response = await fetch(`${AT_PROTOCOL_CONFIG.fallback.pds}/xrpc/com.atproto.repo.getRecord?repo=${repo}&collection=${collection}&rkey=${rkey}`);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to load record');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
contentElement.innerHTML = `
|
||||
<div style="padding: 20px;">
|
||||
<h3>AT URI Record</h3>
|
||||
<div style="font-family: monospace; font-size: 14px; color: #666; margin-bottom: 20px; word-break: break-all;">
|
||||
${uri}
|
||||
</div>
|
||||
<div style="font-size: 12px; color: #999; margin-bottom: 20px;">
|
||||
Repo: ${repo} | Collection: ${collection} | RKey: ${rkey}
|
||||
</div>
|
||||
<h4>Record Data</h4>
|
||||
<pre style="background: #f5f5f5; padding: 15px; border-radius: 4px; overflow: auto;">${JSON.stringify(data, null, 2)}</pre>
|
||||
</div>
|
||||
`;
|
||||
} catch (error) {
|
||||
contentElement.innerHTML = `
|
||||
<div style="padding: 20px; color: red;">
|
||||
<strong>Error:</strong> ${error.message}
|
||||
<div style="margin-top: 10px; font-size: 12px;">
|
||||
<strong>URI:</strong> ${uri}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// Close AT URI modal
|
||||
function closeAtUriModal(event) {
|
||||
const modal = document.getElementById('atUriModal');
|
||||
if (event && event.target !== modal) {
|
||||
return;
|
||||
}
|
||||
modal.style.display = 'none';
|
||||
}
|
||||
|
||||
// Initialize AT URI click handlers
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Add click handlers to existing AT URIs
|
||||
document.querySelectorAll('.at-uri').forEach(element => {
|
||||
element.addEventListener('click', function() {
|
||||
const uri = this.getAttribute('data-at-uri');
|
||||
showAtUriModal(uri);
|
||||
});
|
||||
});
|
||||
|
||||
// ESC key to close modal
|
||||
document.addEventListener('keydown', function(event) {
|
||||
if (event.key === 'Escape') {
|
||||
closeAtUriModal();
|
||||
}
|
||||
});
|
||||
|
||||
// Enter key to search
|
||||
document.getElementById('handleInput').addEventListener('keydown', function(event) {
|
||||
if (event.key === 'Enter') {
|
||||
searchUser();
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
// Toggle collections visibility
|
||||
function toggleCollections() {
|
||||
const collectionsList = document.getElementById('collectionsList');
|
||||
const toggleButton = document.getElementById('collectionsToggle');
|
||||
|
||||
if (collectionsList.style.display === 'none') {
|
||||
collectionsList.style.display = 'block';
|
||||
toggleButton.textContent = '[-] Collections';
|
||||
} else {
|
||||
collectionsList.style.display = 'none';
|
||||
toggleButton.textContent = '[+] Collections';
|
||||
}
|
||||
}
|
@@ -84,10 +84,11 @@ class Theme {
|
||||
setupLogoAnimations() {
|
||||
// Pure CSS animations are handled by the svg-animation-package.css
|
||||
// This method is reserved for any future JavaScript-based enhancements
|
||||
console.log('Logo animations initialized (CSS-based)');
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize theme when DOM is loaded
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
new Theme();
|
||||
});
|
||||
});
|
@@ -1,3 +0,0 @@
|
||||
<!-- OAuth Comment System - Load globally for session management -->
|
||||
<script type="module" crossorigin src="/assets/comment-atproto-B2YEFA6R.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/comment-atproto-BHjafP79.css">
|
@@ -1,61 +0,0 @@
|
||||
<!-- AT Browser Integration - Temporarily disabled to fix site display -->
|
||||
<!--
|
||||
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
|
||||
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
|
||||
<script src="/assets/pds-browser.umd.js"></script>
|
||||
<script>
|
||||
// AT Browser integration - needs debugging
|
||||
console.log('AT Browser integration temporarily disabled');
|
||||
</script>
|
||||
-->
|
||||
|
||||
<style>
|
||||
/* AT Browser Modal Styles */
|
||||
.at-uri-modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.at-uri-modal-content {
|
||||
background-color: white;
|
||||
border-radius: 8px;
|
||||
max-width: 800px;
|
||||
max-height: 600px;
|
||||
width: 90%;
|
||||
height: 80%;
|
||||
overflow: auto;
|
||||
position: relative;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.at-uri-modal-close {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
z-index: 1001;
|
||||
padding: 5px 10px;
|
||||
}
|
||||
|
||||
/* AT URI Link Styles */
|
||||
[data-at-uri] {
|
||||
color: #1976d2;
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
[data-at-uri]:hover {
|
||||
color: #1565c0;
|
||||
}
|
||||
</style>
|
@@ -12,7 +12,6 @@
|
||||
<!-- Stylesheets -->
|
||||
<link rel="stylesheet" href="/css/style.css">
|
||||
<link rel="stylesheet" href="/css/svg-animation-package.css">
|
||||
<link rel="stylesheet" href="/css/pds.css">
|
||||
<link rel="stylesheet" href="/pkg/icomoon/style.css">
|
||||
<link rel="stylesheet" href="/pkg/font-awesome/css/all.min.css">
|
||||
|
||||
@@ -49,18 +48,7 @@
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<!-- User Handle Input Form -->
|
||||
<div class="pds-search-section">
|
||||
<form class="pds-search-form" onsubmit="searchUser(); return false;">
|
||||
<div class="form-group">
|
||||
<input type="text" id="handleInput" placeholder="at://syui.ai" value="syui.ai" />
|
||||
<button type="submit" id="searchButton" class="pds-btn">
|
||||
@
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button class="ask-ai-btn" onclick="toggleAskAI()" id="askAiButton">
|
||||
<span class="ai-icon icon-ai"></span>
|
||||
ai
|
||||
@@ -73,10 +61,7 @@
|
||||
<div class="ask-ai-panel" id="askAiPanel" style="display: none;">
|
||||
<div class="ask-ai-content">
|
||||
<div id="authCheck" class="auth-check">
|
||||
<div class="loading-content">
|
||||
<div class="loading-spinner"></div>
|
||||
<p>Loading...</p>
|
||||
</div>
|
||||
<p>🔒 Please login with ATProto to use Ask AI feature</p>
|
||||
</div>
|
||||
|
||||
<div id="chatForm" class="ask-ai-form" style="display: none;">
|
||||
@@ -87,11 +72,8 @@
|
||||
<div id="chatHistory" class="chat-history" style="display: none;"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<main class="main-content">
|
||||
<!-- Pds Panel -->
|
||||
{% include "pds-header.html" %}
|
||||
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
|
||||
@@ -102,51 +84,14 @@
|
||||
<div class="footer-social">
|
||||
<a href="https://syu.is/syui" target="_blank"><i class="fab fa-bluesky"></i></a>
|
||||
<a href="https://git.syui.ai/ai" target="_blank"><span class="icon-ai"></span></a>
|
||||
<a href="https://github.com/syui" target="_blank"><i class="fab fa-github"></i></a>
|
||||
<a href="https://git.syui.ai/syui" target="_blank"><span class="icon-git"></span></a>
|
||||
</div>
|
||||
<p>© {{ config.author }}</p>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
// Config variables from Hugo
|
||||
window.OAUTH_CONFIG = {
|
||||
{% if config.oauth.pds %}
|
||||
pds: "{{ config.oauth.pds }}",
|
||||
{% else %}
|
||||
pds: "syu.is",
|
||||
{% endif %}
|
||||
{% if config.oauth.admin %}
|
||||
admin: "{{ config.oauth.admin }}",
|
||||
{% else %}
|
||||
admin: "ai.syui.ai",
|
||||
{% endif %}
|
||||
{% if config.oauth.collection %}
|
||||
collection: "{{ config.oauth.collection }}"
|
||||
{% else %}
|
||||
collection: "ai.syui.log"
|
||||
{% endif %}
|
||||
};
|
||||
</script>
|
||||
<script src="/js/ask-ai.js"></script>
|
||||
<script src="/js/pds.js"></script>
|
||||
<script src="/js/theme.js"></script>
|
||||
<script src="/js/image-comparison.js"></script>
|
||||
|
||||
<!-- Mermaid support -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/mermaid@10.6.1/dist/mermaid.min.js"></script>
|
||||
<script>
|
||||
mermaid.initialize({
|
||||
startOnLoad: true,
|
||||
theme: 'neutral',
|
||||
securityLevel: 'loose',
|
||||
themeVariables: {
|
||||
fontFamily: 'system-ui, -apple-system, sans-serif',
|
||||
fontSize: '14px'
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{% include "oauth-assets.html" %}
|
||||
{% include "at-browser-assets.html" %}
|
||||
</body>
|
||||
</html>
|
||||
|
@@ -1,135 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Game - {{ config.title }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div id="gameContainer" class="game-container">
|
||||
<div id="gameAuth" class="game-auth-section">
|
||||
<h1>Login to Play</h1>
|
||||
<p>Please authenticate with your AT Protocol account to access the game.</p>
|
||||
<div id="authRoot"></div>
|
||||
</div>
|
||||
<div id="gameFrame" class="game-frame-container" style="display: none;">
|
||||
<iframe
|
||||
id="pixelStreamingFrame"
|
||||
src="https://verse.syui.ai/simple-noui.html"
|
||||
frameborder="0"
|
||||
allowfullscreen
|
||||
allow="microphone; camera; fullscreen; autoplay"
|
||||
class="pixel-streaming-iframe"
|
||||
></iframe>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Game specific styles */
|
||||
.game-container {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
background: #000;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.game-auth-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100vh;
|
||||
background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.game-auth-section h1 {
|
||||
font-size: 2.5em;
|
||||
margin-bottom: 20px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.game-auth-section p {
|
||||
font-size: 1.2em;
|
||||
margin-bottom: 30px;
|
||||
color: #ccc;
|
||||
}
|
||||
|
||||
.game-frame-container {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.pixel-streaming-iframe {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: none;
|
||||
}
|
||||
|
||||
/* Override auth button for game page */
|
||||
.game-auth-section .auth-section {
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.game-auth-section .auth-button {
|
||||
font-size: 1.2em;
|
||||
padding: 12px 30px;
|
||||
}
|
||||
|
||||
/* Hide header and footer on game page */
|
||||
body:has(.game-container) header,
|
||||
body:has(.game-container) footer,
|
||||
body:has(.game-container) nav {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Remove any body padding/margin for full screen game */
|
||||
body:has(.game-container) {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// Wait for OAuth component to be loaded
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Check if user is already authenticated
|
||||
const checkAuthStatus = () => {
|
||||
// Check if OAuth components are available and user is authenticated
|
||||
if (window.currentUser && window.currentAgent) {
|
||||
showGame();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// Show game iframe
|
||||
const showGame = () => {
|
||||
document.getElementById('gameAuth').style.display = 'none';
|
||||
document.getElementById('gameFrame').style.display = 'block';
|
||||
};
|
||||
|
||||
// Listen for OAuth success
|
||||
window.addEventListener('oauth-success', function(event) {
|
||||
console.log('OAuth success:', event.detail);
|
||||
showGame();
|
||||
});
|
||||
|
||||
// Check auth status on load
|
||||
if (!checkAuthStatus()) {
|
||||
// Check periodically if OAuth components are loaded
|
||||
const authCheckInterval = setInterval(() => {
|
||||
if (checkAuthStatus()) {
|
||||
clearInterval(authCheckInterval);
|
||||
}
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- Include OAuth assets -->
|
||||
{% include "oauth-assets.html" %}
|
||||
{% endblock %}
|
@@ -1,48 +0,0 @@
|
||||
<div class="pds-container">
|
||||
<div class="pds-header">
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<!-- Current User DID -->
|
||||
<div id="userDidSection" class="user-did-section" style="display: none;">
|
||||
<div class="pds-display">
|
||||
<strong>PDS:</strong> <span id="userPdsText"></span>
|
||||
</div>
|
||||
<div class="handle-display">
|
||||
<strong>Handle:</strong> <span id="userHandleText"></span>
|
||||
</div>
|
||||
<div class="did-display">
|
||||
<span id="userDidText"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Collection List -->
|
||||
<div id="collectionsSection" class="collections-section" style="display: none;">
|
||||
<div class="collections-header">
|
||||
<button id="collectionsToggle" class="collections-toggle" onclick="toggleCollections()">[+] Collections</button>
|
||||
</div>
|
||||
<div id="collectionsList" class="collections-list" style="display: none;">
|
||||
<!-- Collections will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- AT URI Records -->
|
||||
<div id="recordsSection" class="records-section" style="display: none;">
|
||||
<div id="recordsList" class="records-list">
|
||||
<!-- Records will be populated here -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
<!-- AT URI Modal -->
|
||||
<div id="atUriModal" class="at-uri-modal-overlay" style="display: none;" onclick="closeAtUriModal(event)">
|
||||
<div class="at-uri-modal-content">
|
||||
<button class="at-uri-modal-close" onclick="closeAtUriModal()">×</button>
|
||||
<div id="atUriContent"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
@@ -1,6 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}at-uri browser - {{ config.title }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% endblock %}
|
@@ -13,7 +13,6 @@
|
||||
<span class="article-lang">{{ post.language }}</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if not post.extra.type or post.extra.type != "ai" %}
|
||||
<div class="article-actions">
|
||||
{% if post.markdown_url %}
|
||||
<a href="{{ post.markdown_url }}" class="action-btn markdown-btn" title="View Markdown">
|
||||
@@ -26,35 +25,29 @@
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</header>
|
||||
|
||||
{% if not post.extra.type or post.extra.type != "ai" %}
|
||||
<div class="article-body">
|
||||
{{ post.content | safe }}
|
||||
</div>
|
||||
|
||||
<div id="comment-atproto"></div>
|
||||
</article>
|
||||
|
||||
<aside class="article-sidebar">
|
||||
<nav class="toc">
|
||||
<h3>Contents</h3>
|
||||
<div id="toc-content">
|
||||
<!-- TOC will be generated by JavaScript -->
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="article-body">
|
||||
{{ post.content | safe }}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div id="comment-atproto"></div>
|
||||
</article>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
|
||||
<script>
|
||||
// Generate table of contents
|
||||
function generateTableOfContents() {
|
||||
const tocContainer = document.getElementById('toc-content');
|
||||
if (!tocContainer) {
|
||||
return;
|
||||
}
|
||||
|
||||
const headings = document.querySelectorAll('.article-body h1, .article-body h2, .article-body h3, .article-body h4, .article-body h5, .article-body h6');
|
||||
|
||||
if (headings.length === 0) {
|
||||
|
@@ -1,19 +1,21 @@
|
||||
VITE_ADMIN=ai.syui.ai
|
||||
VITE_PDS=syu.is
|
||||
VITE_HANDLE_LIST=["ai.syui.ai", "syui.syui.ai", "ai.ai"]
|
||||
VITE_COLLECTION=ai.syui.log
|
||||
# Production environment variables
|
||||
VITE_APP_HOST=https://syui.ai
|
||||
VITE_OAUTH_CLIENT_ID=https://syui.ai/client-metadata.json
|
||||
VITE_OAUTH_REDIRECT_URI=https://syui.ai/oauth/callback
|
||||
|
||||
# AI Configuration - match oauth_old settings
|
||||
# Handle-based Configuration (DIDs resolved at runtime)
|
||||
VITE_ATPROTO_PDS=syu.is
|
||||
VITE_ADMIN_HANDLE=ai.syui.ai
|
||||
VITE_AI_HANDLE=ai.syui.ai
|
||||
VITE_OAUTH_COLLECTION=ai.syui.log
|
||||
VITE_ATPROTO_WEB_URL=https://bsky.app
|
||||
VITE_ATPROTO_HANDLE_LIST=["syui.syui.ai","ai.syui.ai","ai.ai"]
|
||||
|
||||
# AI Configuration
|
||||
VITE_AI_ENABLED=true
|
||||
VITE_AI_ASK_AI=true
|
||||
VITE_AI_PROVIDER=ollama
|
||||
VITE_AI_MODEL=gemma3:1b
|
||||
VITE_AI_HOST=https://ollama.syui.ai
|
||||
VITE_ASK_AI_URL=https://ollama.syui.ai/api/generate
|
||||
VITE_AI_SYSTEM_PROMPT="あなたは6歳の女の子アイです。明るく元気で、ちょっとおっちょこちょい。自分のことは「アイ」って呼びます。白と金のワンピース姿。 相手のことが大好きで、ときどき甘えたり、照れたりします。 でも、宇宙とかAIとか、難しい話にもすっごく詳しいの。専門的なことも、がんばって子どもっぽく教えようとします。不思議な力を持っています。小さい物質のことをよく知っているようです。"
|
||||
|
||||
# Production settings - Disable development features
|
||||
VITE_ENABLE_TEST_UI=false
|
||||
VITE_ENABLE_DEBUG=true
|
@@ -1,11 +1,20 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Comments Test</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="comment-atproto"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>ai.card</title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background-color: #0a0a0a;
|
||||
color: #ffffff;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
@@ -1,25 +1,36 @@
|
||||
{
|
||||
"name": "ailog-oauth",
|
||||
"version": "0.3.1",
|
||||
"type": "module",
|
||||
"name": "aicard",
|
||||
"version": "0.1.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build && node build-minimal.js",
|
||||
"preview": "vite preview"
|
||||
"dev": "vite --mode development",
|
||||
"build": "vite build --mode production",
|
||||
"build:dev": "vite build --mode development",
|
||||
"build:local": "VITE_APP_HOST=http://localhost:4173 vite build --mode development",
|
||||
"preview": "npm run test:console && vite preview",
|
||||
"test": "vitest",
|
||||
"test:console": "node -r esbuild-register src/tests/console-test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@atproto/api": "^0.15.12",
|
||||
"@atproto/did": "^0.1.5",
|
||||
"@atproto/identity": "^0.4.8",
|
||||
"@atproto/oauth-client-browser": "^0.3.19",
|
||||
"@atproto/xrpc": "^0.7.0",
|
||||
"axios": "^1.6.2",
|
||||
"framer-motion": "^10.16.16",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-markdown": "^9.0.1",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.0"
|
||||
"react-router-dom": "^7.6.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.0",
|
||||
"@types/react-dom": "^18.2.0",
|
||||
"@vitejs/plugin-react": "^4.0.0",
|
||||
"vite": "^5.0.0"
|
||||
"@types/react": "^18.2.45",
|
||||
"@types/react-dom": "^18.2.18",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
"typescript": "^5.3.3",
|
||||
"vite": "^5.0.10",
|
||||
"vitest": "^1.1.0",
|
||||
"esbuild": "^0.19.10",
|
||||
"esbuild-register": "^3.5.0"
|
||||
}
|
||||
}
|
||||
|
14
oauth/public/.well-known/jwks.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"keys": [
|
||||
{
|
||||
"kty": "EC",
|
||||
"crv": "P-256",
|
||||
"x": "mock_x_coordinate_base64url",
|
||||
"y": "mock_y_coordinate_base64url",
|
||||
"d": "mock_private_key_base64url",
|
||||
"use": "sig",
|
||||
"kid": "ai-card-oauth-key-1",
|
||||
"alg": "ES256"
|
||||
}
|
||||
]
|
||||
}
|
24
oauth/public/client-metadata.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"client_id": "https://syui.ai/client-metadata.json",
|
||||
"client_name": "ai.log",
|
||||
"client_uri": "https://syui.ai",
|
||||
"logo_uri": "https://syui.ai/favicon.ico",
|
||||
"tos_uri": "https://syui.ai/terms",
|
||||
"policy_uri": "https://syui.ai/privacy",
|
||||
"redirect_uris": [
|
||||
"https://syui.ai/oauth/callback",
|
||||
"https://syui.ai/"
|
||||
],
|
||||
"response_types": [
|
||||
"code"
|
||||
],
|
||||
"grant_types": [
|
||||
"authorization_code",
|
||||
"refresh_token"
|
||||
],
|
||||
"token_endpoint_auth_method": "none",
|
||||
"scope": "atproto transition:generic",
|
||||
"subject_type": "public",
|
||||
"application_type": "web",
|
||||
"dpop_bound_access_tokens": true
|
||||
}
|
2241
oauth/src/App.css
@@ -1,493 +0,0 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { atproto } from './api/atproto.js'
|
||||
import { useAuth } from './hooks/useAuth.js'
|
||||
import { useAdminData } from './hooks/useAdminData.js'
|
||||
import { useUserData } from './hooks/useUserData.js'
|
||||
import { usePageContext } from './hooks/usePageContext.js'
|
||||
import AuthButton from './components/AuthButton.jsx'
|
||||
import RecordTabs from './components/RecordTabs.jsx'
|
||||
import CommentForm from './components/CommentForm.jsx'
|
||||
import ProfileForm from './components/ProfileForm.jsx'
|
||||
import AskAI from './components/AskAI.jsx'
|
||||
import TestUI from './components/TestUI.jsx'
|
||||
import OAuthCallback from './components/OAuthCallback.jsx'
|
||||
|
||||
export default function App() {
|
||||
const { user, agent, loading: authLoading, login, logout } = useAuth()
|
||||
const { adminData, langRecords, commentRecords, chatRecords: adminChatRecords, chatHasMore, loading: dataLoading, error, refresh: refreshAdminData, loadMoreChat } = useAdminData()
|
||||
const { userComments, chatRecords, loading: userLoading, refresh: refreshUserData } = useUserData(adminData)
|
||||
const [userChatRecords, setUserChatRecords] = useState([])
|
||||
const [userChatLoading, setUserChatLoading] = useState(false)
|
||||
const pageContext = usePageContext()
|
||||
const [showAskAI, setShowAskAI] = useState(false)
|
||||
const [showTestUI, setShowTestUI] = useState(false)
|
||||
|
||||
// Check if current page has matching chat records (AI posts always have chat records)
|
||||
const isAiPost = !pageContext.isTopPage && Array.isArray(adminChatRecords) && adminChatRecords.some(chatPair => {
|
||||
const recordUrl = chatPair.question?.value?.post?.url
|
||||
if (!recordUrl) return false
|
||||
|
||||
try {
|
||||
const recordRkey = new URL(recordUrl).pathname.split('/').pop()?.replace(/\.html$/, '')
|
||||
return recordRkey === pageContext.rkey
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
|
||||
// Environment-based feature flags
|
||||
const ENABLE_TEST_UI = import.meta.env.VITE_ENABLE_TEST_UI === 'true'
|
||||
const ENABLE_DEBUG = import.meta.env.VITE_ENABLE_DEBUG === 'true'
|
||||
|
||||
// Fetch user's own chat records
|
||||
const fetchUserChatRecords = async () => {
|
||||
if (!user || !agent) return
|
||||
|
||||
setUserChatLoading(true)
|
||||
try {
|
||||
const records = await agent.api.com.atproto.repo.listRecords({
|
||||
repo: user.did,
|
||||
collection: 'ai.syui.log.chat',
|
||||
limit: 50
|
||||
})
|
||||
|
||||
// Group questions and answers together
|
||||
const chatPairs = []
|
||||
const recordMap = new Map()
|
||||
|
||||
// First pass: organize records by base rkey
|
||||
records.data.records.forEach(record => {
|
||||
const rkey = record.uri.split('/').pop()
|
||||
const baseRkey = rkey.replace('-answer', '')
|
||||
|
||||
if (!recordMap.has(baseRkey)) {
|
||||
recordMap.set(baseRkey, { question: null, answer: null })
|
||||
}
|
||||
|
||||
if (record.value.type === 'question') {
|
||||
recordMap.get(baseRkey).question = record
|
||||
} else if (record.value.type === 'answer') {
|
||||
recordMap.get(baseRkey).answer = record
|
||||
}
|
||||
})
|
||||
|
||||
// Second pass: create chat pairs
|
||||
recordMap.forEach((pair, rkey) => {
|
||||
if (pair.question) {
|
||||
chatPairs.push({
|
||||
rkey,
|
||||
question: pair.question,
|
||||
answer: pair.answer,
|
||||
createdAt: pair.question.value.createdAt
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// Sort by creation time (newest first)
|
||||
chatPairs.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
|
||||
|
||||
setUserChatRecords(chatPairs)
|
||||
} catch (error) {
|
||||
// Silently fail - no error logging
|
||||
setUserChatRecords([])
|
||||
} finally {
|
||||
setUserChatLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch user chat records when user/agent changes
|
||||
useEffect(() => {
|
||||
fetchUserChatRecords()
|
||||
}, [user, agent])
|
||||
|
||||
// Expose AI profile data to blog's ask-ai.js
|
||||
useEffect(() => {
|
||||
if (adminData?.profile) {
|
||||
// Make AI profile data available globally for ask-ai.js
|
||||
window.aiProfileData = {
|
||||
did: adminData.did,
|
||||
handle: adminData.profile.handle,
|
||||
displayName: adminData.profile.displayName,
|
||||
avatar: adminData.profile.avatar
|
||||
}
|
||||
|
||||
// Dispatch event to notify ask-ai.js
|
||||
window.dispatchEvent(new CustomEvent('aiProfileLoaded', {
|
||||
detail: window.aiProfileData
|
||||
}))
|
||||
}
|
||||
}, [adminData])
|
||||
|
||||
// Expose current user and agent for game page
|
||||
useEffect(() => {
|
||||
if (user && agent) {
|
||||
window.currentUser = user
|
||||
window.currentAgent = agent
|
||||
}
|
||||
}, [user, agent])
|
||||
|
||||
// Event listeners for blog communication
|
||||
useEffect(() => {
|
||||
// Clear OAuth completion flag once app is loaded
|
||||
if (sessionStorage.getItem('oauth_just_completed') === 'true') {
|
||||
setTimeout(() => {
|
||||
sessionStorage.removeItem('oauth_just_completed')
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
const handleAIQuestion = async (event) => {
|
||||
const { question } = event.detail
|
||||
if (question && adminData && user && agent) {
|
||||
try {
|
||||
|
||||
// AI設定
|
||||
const aiConfig = {
|
||||
host: import.meta.env.VITE_AI_HOST || 'https://ollama.syui.ai',
|
||||
model: import.meta.env.VITE_AI_MODEL || 'gemma3:1b',
|
||||
systemPrompt: import.meta.env.VITE_AI_SYSTEM_PROMPT || 'あなたは6歳の女の子アイです。明るく元気で、ちょっとおっちょこちょい。自分のことは「アイ」って呼びます。'
|
||||
}
|
||||
|
||||
const prompt = `${aiConfig.systemPrompt}
|
||||
|
||||
Question: ${question}
|
||||
|
||||
Answer:`
|
||||
|
||||
// Ollamaに直接リクエスト
|
||||
const controller = new AbortController()
|
||||
const timeoutId = setTimeout(() => controller.abort(), 30000)
|
||||
|
||||
const response = await fetch(`${aiConfig.host}/api/generate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Origin': 'https://syui.ai',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: aiConfig.model,
|
||||
prompt: prompt,
|
||||
stream: false,
|
||||
options: {
|
||||
temperature: 0.9,
|
||||
top_p: 0.9,
|
||||
num_predict: 200,
|
||||
repeat_penalty: 1.1,
|
||||
}
|
||||
}),
|
||||
signal: controller.signal
|
||||
})
|
||||
|
||||
clearTimeout(timeoutId)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Ollama API error: ${response.status}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const answer = data.response || 'エラーが発生しました'
|
||||
|
||||
// Save conversation to ATProto
|
||||
try {
|
||||
const now = new Date()
|
||||
const timestamp = now.toISOString()
|
||||
const rkey = timestamp.replace(/[:.]/g, '-')
|
||||
|
||||
// Extract post metadata from current page
|
||||
const currentUrl = window.location.href
|
||||
const postSlug = currentUrl.match(/\/posts\/([^/]+)/)?.[1] || ''
|
||||
const postTitle = document.title.replace(' - syui.ai', '') || ''
|
||||
|
||||
// 1. Save question record
|
||||
const questionRecord = {
|
||||
$type: 'ai.syui.log.chat',
|
||||
post: {
|
||||
url: currentUrl,
|
||||
slug: postSlug,
|
||||
title: postTitle,
|
||||
date: timestamp,
|
||||
tags: [],
|
||||
language: "ja"
|
||||
},
|
||||
type: "question",
|
||||
text: question,
|
||||
author: {
|
||||
did: user.did,
|
||||
handle: user.handle,
|
||||
displayName: user.displayName || user.handle,
|
||||
avatar: user.avatar
|
||||
},
|
||||
createdAt: timestamp
|
||||
}
|
||||
|
||||
await agent.api.com.atproto.repo.putRecord({
|
||||
repo: user.did,
|
||||
collection: 'ai.syui.log.chat',
|
||||
rkey: rkey,
|
||||
record: questionRecord
|
||||
})
|
||||
|
||||
// 2. Save answer record
|
||||
const answerRkey = rkey + '-answer'
|
||||
const answerRecord = {
|
||||
$type: 'ai.syui.log.chat',
|
||||
post: {
|
||||
url: currentUrl,
|
||||
slug: postSlug,
|
||||
title: postTitle,
|
||||
date: timestamp,
|
||||
tags: [],
|
||||
language: "ja"
|
||||
},
|
||||
type: "answer",
|
||||
text: answer,
|
||||
author: {
|
||||
did: adminData.did,
|
||||
handle: adminData.profile?.handle,
|
||||
displayName: adminData.profile?.displayName,
|
||||
avatar: adminData.profile?.avatar
|
||||
},
|
||||
createdAt: timestamp
|
||||
}
|
||||
|
||||
await agent.api.com.atproto.repo.putRecord({
|
||||
repo: user.did,
|
||||
collection: 'ai.syui.log.chat',
|
||||
rkey: answerRkey,
|
||||
record: answerRecord
|
||||
})
|
||||
|
||||
|
||||
// Refresh chat records after saving
|
||||
setTimeout(() => {
|
||||
fetchUserChatRecords()
|
||||
}, 1000)
|
||||
} catch (saveError) {
|
||||
// Silently fail - no error logging
|
||||
}
|
||||
|
||||
// Send response to blog
|
||||
window.dispatchEvent(new CustomEvent('aiResponseReceived', {
|
||||
detail: {
|
||||
question: question,
|
||||
answer: answer,
|
||||
timestamp: new Date().toISOString(),
|
||||
aiProfile: adminData?.profile ? {
|
||||
did: adminData.did,
|
||||
handle: adminData.profile.handle,
|
||||
displayName: adminData.profile.displayName,
|
||||
avatar: adminData.profile.avatar
|
||||
} : null
|
||||
}
|
||||
}))
|
||||
|
||||
} catch (error) {
|
||||
// Silently fail - send error response to blog without logging
|
||||
window.dispatchEvent(new CustomEvent('aiResponseReceived', {
|
||||
detail: {
|
||||
question: question,
|
||||
answer: 'エラーが発生しました。もう一度お試しください。',
|
||||
timestamp: new Date().toISOString(),
|
||||
aiProfile: adminData?.profile ? {
|
||||
did: adminData.did,
|
||||
handle: adminData.profile.handle,
|
||||
displayName: adminData.profile.displayName,
|
||||
avatar: adminData.profile.avatar
|
||||
} : null
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const dispatchAIProfileLoaded = () => {
|
||||
if (adminData?.profile) {
|
||||
window.dispatchEvent(new CustomEvent('aiProfileLoaded', {
|
||||
detail: {
|
||||
did: adminData.did,
|
||||
handle: adminData.profile.handle,
|
||||
displayName: adminData.profile.displayName,
|
||||
avatar: adminData.profile.avatar
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for questions from blog
|
||||
window.addEventListener('postAIQuestion', handleAIQuestion)
|
||||
|
||||
// Dispatch AI profile when adminData is available
|
||||
if (adminData?.profile) {
|
||||
dispatchAIProfileLoaded()
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('postAIQuestion', handleAIQuestion)
|
||||
}
|
||||
}, [adminData, user, agent])
|
||||
|
||||
// Handle OAuth callback
|
||||
if (window.location.search.includes('code=')) {
|
||||
return <OAuthCallback />
|
||||
}
|
||||
|
||||
const isLoading = authLoading || dataLoading || userLoading
|
||||
|
||||
// Don't show loading if we just completed OAuth callback
|
||||
const isOAuthReturn = window.location.pathname === '/oauth/callback' ||
|
||||
sessionStorage.getItem('oauth_just_completed') === 'true'
|
||||
|
||||
if (isLoading && !isOAuthReturn) {
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
minHeight: '200px',
|
||||
padding: '40px',
|
||||
textAlign: 'center'
|
||||
}}>
|
||||
<div style={{
|
||||
width: '40px',
|
||||
height: '40px',
|
||||
border: '4px solid #f3f3f3',
|
||||
borderTop: '4px solid #667eea',
|
||||
borderRadius: '50%',
|
||||
animation: 'spin 1s linear infinite',
|
||||
marginBottom: '16px'
|
||||
}} />
|
||||
<p style={{ color: '#666', margin: 0 }}>読み込み中...</p>
|
||||
|
||||
<style jsx>{`
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
// Silently hide component on error - no error display
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
{!isAiPost && (
|
||||
<header className="oauth-app-header">
|
||||
<div className="oauth-header-content">
|
||||
{user && (
|
||||
<div className="oauth-user-profile">
|
||||
<div className="profile-avatar-section">
|
||||
{user.avatar ? (
|
||||
<img
|
||||
src={user.avatar}
|
||||
alt={user.displayName || user.handle}
|
||||
className="profile-avatar"
|
||||
/>
|
||||
) : (
|
||||
<div className="profile-avatar-fallback">
|
||||
{(user.displayName || user.handle || '?').charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="profile-info">
|
||||
<div className="profile-display-name">
|
||||
{user.displayName || user.handle}
|
||||
</div>
|
||||
<div className="profile-handle">
|
||||
@{user.handle}
|
||||
</div>
|
||||
<div className="profile-did">
|
||||
{user.did}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="oauth-header-actions">
|
||||
<AuthButton
|
||||
user={user}
|
||||
onLogin={login}
|
||||
onLogout={logout}
|
||||
loading={authLoading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
)}
|
||||
|
||||
<div className="main-content">
|
||||
<div className="content-area">
|
||||
|
||||
{user && (
|
||||
<div className="comment-form">
|
||||
<CommentForm
|
||||
user={user}
|
||||
agent={agent}
|
||||
onCommentPosted={() => {
|
||||
refreshAdminData?.()
|
||||
refreshUserData?.()
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{user && (
|
||||
<div className="profile-form">
|
||||
<ProfileForm
|
||||
user={user}
|
||||
agent={agent}
|
||||
apiConfig={adminData.apiConfig}
|
||||
onProfilePosted={() => {
|
||||
refreshAdminData?.()
|
||||
refreshUserData?.()
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<RecordTabs
|
||||
langRecords={langRecords}
|
||||
commentRecords={commentRecords}
|
||||
userComments={userComments}
|
||||
chatRecords={adminChatRecords}
|
||||
chatHasMore={chatHasMore}
|
||||
onLoadMoreChat={loadMoreChat}
|
||||
userChatRecords={userChatRecords}
|
||||
userChatLoading={userChatLoading}
|
||||
baseRecords={adminData.records}
|
||||
apiConfig={adminData.apiConfig}
|
||||
pageContext={pageContext}
|
||||
user={user}
|
||||
agent={agent}
|
||||
onRecordDeleted={() => {
|
||||
refreshAdminData?.()
|
||||
refreshUserData?.()
|
||||
fetchUserChatRecords?.()
|
||||
}}
|
||||
/>
|
||||
|
||||
{ENABLE_TEST_UI && showTestUI && (
|
||||
<div className="test-section">
|
||||
<TestUI />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{ENABLE_TEST_UI && (
|
||||
<div className="bottom-actions">
|
||||
<button
|
||||
onClick={() => setShowTestUI(!showTestUI)}
|
||||
className={`btn ${showTestUI ? 'btn-danger' : 'btn-outline'} btn-sm`}
|
||||
>
|
||||
{showTestUI ? 'close test' : 'test'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
1622
oauth/src/App.tsx
Normal file
21
oauth/src/components/AIChat-access.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
// Cloudflare Access対応版の例
|
||||
const response = await fetch(`${aiConfig.host}/api/generate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
// Cloudflare Access Service Token
|
||||
'CF-Access-Client-Id': import.meta.env.VITE_CF_ACCESS_CLIENT_ID,
|
||||
'CF-Access-Client-Secret': import.meta.env.VITE_CF_ACCESS_CLIENT_SECRET,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: aiConfig.model,
|
||||
prompt: prompt,
|
||||
stream: false,
|
||||
options: {
|
||||
temperature: 0.9,
|
||||
top_p: 0.9,
|
||||
num_predict: 200,
|
||||
repeat_penalty: 1.1,
|
||||
}
|
||||
}),
|
||||
});
|
271
oauth/src/components/AIChat.tsx
Normal file
@@ -0,0 +1,271 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { User } from '../services/auth';
|
||||
import { atprotoOAuthService } from '../services/atproto-oauth';
|
||||
import { appConfig, getCollectionNames } from '../config/app';
|
||||
|
||||
interface AIChatProps {
|
||||
user: User | null;
|
||||
isEnabled: boolean;
|
||||
}
|
||||
|
||||
export const AIChat: React.FC<AIChatProps> = ({ user, isEnabled }) => {
|
||||
const [chatHistory, setChatHistory] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [aiProfile, setAiProfile] = useState<any>(null);
|
||||
|
||||
// Get AI settings from appConfig (unified configuration)
|
||||
const aiConfig = {
|
||||
enabled: appConfig.aiEnabled,
|
||||
askAi: appConfig.aiAskAi,
|
||||
provider: appConfig.aiProvider,
|
||||
model: appConfig.aiModel,
|
||||
host: appConfig.aiHost,
|
||||
systemPrompt: appConfig.aiSystemPrompt,
|
||||
aiDid: appConfig.aiDid,
|
||||
bskyPublicApi: appConfig.bskyPublicApi,
|
||||
};
|
||||
|
||||
// Fetch AI profile on load
|
||||
useEffect(() => {
|
||||
const fetchAIProfile = async () => {
|
||||
if (!aiConfig.aiDid) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Try with agent first
|
||||
const agent = atprotoOAuthService.getAgent();
|
||||
if (agent) {
|
||||
const profile = await agent.getProfile({ actor: aiConfig.aiDid });
|
||||
const profileData = {
|
||||
did: aiConfig.aiDid,
|
||||
handle: profile.data.handle,
|
||||
displayName: profile.data.displayName,
|
||||
avatar: profile.data.avatar,
|
||||
description: profile.data.description
|
||||
};
|
||||
setAiProfile(profileData);
|
||||
|
||||
// Dispatch event to update Ask AI button
|
||||
window.dispatchEvent(new CustomEvent('aiProfileLoaded', { detail: profileData }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback to public API
|
||||
const response = await fetch(`${aiConfig.bskyPublicApi}/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(aiConfig.aiDid)}`);
|
||||
if (response.ok) {
|
||||
const profileData = await response.json();
|
||||
const profile = {
|
||||
did: aiConfig.aiDid,
|
||||
handle: profileData.handle,
|
||||
displayName: profileData.displayName,
|
||||
avatar: profileData.avatar,
|
||||
description: profileData.description
|
||||
};
|
||||
setAiProfile(profile);
|
||||
|
||||
// Dispatch event to update Ask AI button
|
||||
window.dispatchEvent(new CustomEvent('aiProfileLoaded', { detail: profile }));
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
setAiProfile(null);
|
||||
}
|
||||
};
|
||||
|
||||
fetchAIProfile();
|
||||
}, [aiConfig.aiDid]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isEnabled || !aiConfig.askAi) return;
|
||||
|
||||
// Listen for AI question posts from base.html
|
||||
const handleAIQuestion = async (event: any) => {
|
||||
if (!user || !event.detail || !event.detail.question || isProcessing || !aiProfile) return;
|
||||
|
||||
setIsProcessing(true);
|
||||
try {
|
||||
await postQuestionAndGenerateResponse(event.detail.question);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Add listener with a small delay to ensure it's ready
|
||||
setTimeout(() => {
|
||||
window.addEventListener('postAIQuestion', handleAIQuestion);
|
||||
|
||||
// Notify that AI is ready
|
||||
window.dispatchEvent(new CustomEvent('aiChatReady'));
|
||||
}, 100);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('postAIQuestion', handleAIQuestion);
|
||||
};
|
||||
}, [user, isEnabled, isProcessing, aiProfile]);
|
||||
|
||||
const postQuestionAndGenerateResponse = async (question: string) => {
|
||||
if (!user || !aiConfig.askAi || !aiProfile) return;
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const agent = atprotoOAuthService.getAgent();
|
||||
if (!agent) throw new Error('No agent available');
|
||||
|
||||
// Get collection names
|
||||
const collections = getCollectionNames(appConfig.collections.base);
|
||||
|
||||
// 1. Post question to ATProto
|
||||
const now = new Date();
|
||||
const rkey = now.toISOString().replace(/[:.]/g, '-');
|
||||
|
||||
// Extract post metadata from current page
|
||||
const currentUrl = window.location.href;
|
||||
const postSlug = currentUrl.match(/\/posts\/([^/]+)/)?.[1] || '';
|
||||
const postTitle = document.title.replace(' - syui.ai', '') || '';
|
||||
|
||||
const questionRecord = {
|
||||
$type: collections.chat,
|
||||
post: {
|
||||
url: currentUrl,
|
||||
slug: postSlug,
|
||||
title: postTitle,
|
||||
date: new Date().toISOString(),
|
||||
tags: [],
|
||||
language: "ja"
|
||||
},
|
||||
type: "question",
|
||||
text: question,
|
||||
author: {
|
||||
did: user.did,
|
||||
handle: user.handle,
|
||||
avatar: user.avatar,
|
||||
displayName: user.displayName || user.handle,
|
||||
},
|
||||
createdAt: now.toISOString(),
|
||||
};
|
||||
|
||||
await agent.api.com.atproto.repo.putRecord({
|
||||
repo: user.did,
|
||||
collection: collections.chat,
|
||||
rkey: rkey,
|
||||
record: questionRecord,
|
||||
});
|
||||
|
||||
// 2. Get chat history
|
||||
const chatRecords = await agent.api.com.atproto.repo.listRecords({
|
||||
repo: user.did,
|
||||
collection: collections.chat,
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
let chatHistoryText = '';
|
||||
if (chatRecords.data.records) {
|
||||
chatHistoryText = chatRecords.data.records
|
||||
.map((r: any) => {
|
||||
if (r.value.type === 'question') {
|
||||
return `User: ${r.value.text}`;
|
||||
} else if (r.value.type === 'answer') {
|
||||
return `AI: ${r.value.text}`;
|
||||
}
|
||||
return '';
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
// 3. Generate AI response based on provider
|
||||
let aiAnswer = '';
|
||||
|
||||
// 3. Generate AI response using Ollama via proxy
|
||||
if (aiConfig.provider === 'ollama') {
|
||||
const prompt = `${aiConfig.systemPrompt}
|
||||
|
||||
Question: ${question}
|
||||
|
||||
Answer:`;
|
||||
|
||||
const response = await fetch(`${aiConfig.host}/api/generate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Origin': 'https://syui.ai',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: aiConfig.model,
|
||||
prompt: prompt,
|
||||
stream: false,
|
||||
options: {
|
||||
temperature: 0.9,
|
||||
top_p: 0.9,
|
||||
num_predict: 200, // Longer responses for better answers
|
||||
repeat_penalty: 1.1,
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('AI API request failed');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
aiAnswer = data.response;
|
||||
}
|
||||
|
||||
// 4. Immediately dispatch event to update UI
|
||||
window.dispatchEvent(new CustomEvent('aiResponseReceived', {
|
||||
detail: {
|
||||
answer: aiAnswer,
|
||||
aiProfile: aiProfile,
|
||||
timestamp: now.toISOString()
|
||||
}
|
||||
}));
|
||||
|
||||
// 5. Save AI response in background
|
||||
const answerRkey = now.toISOString().replace(/[:.]/g, '-') + '-answer';
|
||||
|
||||
const answerRecord = {
|
||||
$type: collections.chat,
|
||||
post: {
|
||||
url: currentUrl,
|
||||
slug: postSlug,
|
||||
title: postTitle,
|
||||
date: new Date().toISOString(),
|
||||
tags: [],
|
||||
language: "ja"
|
||||
},
|
||||
type: "answer",
|
||||
text: aiAnswer,
|
||||
author: {
|
||||
did: aiProfile.did,
|
||||
handle: aiProfile.handle,
|
||||
displayName: aiProfile.displayName,
|
||||
avatar: aiProfile.avatar,
|
||||
},
|
||||
createdAt: now.toISOString(),
|
||||
};
|
||||
|
||||
// Save to ATProto asynchronously (don't wait for it)
|
||||
agent.api.com.atproto.repo.putRecord({
|
||||
repo: user.did,
|
||||
collection: collections.chat,
|
||||
rkey: answerRkey,
|
||||
record: answerRecord,
|
||||
}).catch(err => {
|
||||
// Silent fail for AI response saving
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
window.dispatchEvent(new CustomEvent('aiResponseError', {
|
||||
detail: { error: 'AI応答の生成に失敗しました' }
|
||||
}));
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// This component doesn't render anything - it just handles the logic
|
||||
return null;
|
||||
};
|
79
oauth/src/components/AIProfile.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { AtprotoAgent } from '@atproto/api';
|
||||
|
||||
interface AIProfile {
|
||||
did: string;
|
||||
handle: string;
|
||||
displayName?: string;
|
||||
avatar?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface AIProfileProps {
|
||||
aiDid: string;
|
||||
}
|
||||
|
||||
export const AIProfile: React.FC<AIProfileProps> = ({ aiDid }) => {
|
||||
const [profile, setProfile] = useState<AIProfile | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchAIProfile = async () => {
|
||||
try {
|
||||
// Use public API to get profile information
|
||||
const agent = new AtprotoAgent({ service: 'https://bsky.social' });
|
||||
const response = await agent.getProfile({ actor: aiDid });
|
||||
|
||||
setProfile({
|
||||
did: response.data.did,
|
||||
handle: response.data.handle,
|
||||
displayName: response.data.displayName,
|
||||
avatar: response.data.avatar,
|
||||
description: response.data.description,
|
||||
});
|
||||
} catch (error) {
|
||||
// Failed to fetch AI profile
|
||||
// Fallback to basic info
|
||||
setProfile({
|
||||
did: aiDid,
|
||||
handle: 'ai-assistant',
|
||||
displayName: 'AI Assistant',
|
||||
description: 'AI assistant for this blog',
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (aiDid) {
|
||||
fetchAIProfile();
|
||||
}
|
||||
}, [aiDid]);
|
||||
|
||||
if (loading) {
|
||||
return <div className="ai-profile-loading">Loading AI profile...</div>;
|
||||
}
|
||||
|
||||
if (!profile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="ai-profile">
|
||||
<div className="ai-avatar">
|
||||
{profile.avatar ? (
|
||||
<img src={profile.avatar} alt={profile.displayName || profile.handle} />
|
||||
) : (
|
||||
<div className="ai-avatar-placeholder">🤖</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="ai-info">
|
||||
<div className="ai-name">{profile.displayName || profile.handle}</div>
|
||||
<div className="ai-handle">@{profile.handle}</div>
|
||||
{profile.description && (
|
||||
<div className="ai-description">{profile.description}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
120
oauth/src/components/Card.tsx
Normal file
@@ -0,0 +1,120 @@
|
||||
import React from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { Card as CardType, CardRarity } from '../types/card';
|
||||
import '../styles/Card.css';
|
||||
|
||||
interface CardProps {
|
||||
card: CardType;
|
||||
isRevealing?: boolean;
|
||||
detailed?: boolean;
|
||||
}
|
||||
|
||||
const CARD_INFO: Record<number, { name: string; color: string }> = {
|
||||
0: { name: "アイ", color: "#fff700" },
|
||||
1: { name: "夢幻", color: "#b19cd9" },
|
||||
2: { name: "光彩", color: "#ffd700" },
|
||||
3: { name: "中性子", color: "#cacfd2" },
|
||||
4: { name: "太陽", color: "#ff6b35" },
|
||||
5: { name: "夜空", color: "#1a1a2e" },
|
||||
6: { name: "雪", color: "#e3f2fd" },
|
||||
7: { name: "雷", color: "#ffd93d" },
|
||||
8: { name: "超究", color: "#6c5ce7" },
|
||||
9: { name: "剣", color: "#a8e6cf" },
|
||||
10: { name: "破壊", color: "#ff4757" },
|
||||
11: { name: "地球", color: "#4834d4" },
|
||||
12: { name: "天の川", color: "#9c88ff" },
|
||||
13: { name: "創造", color: "#00d2d3" },
|
||||
14: { name: "超新星", color: "#ff9ff3" },
|
||||
15: { name: "世界", color: "#54a0ff" },
|
||||
};
|
||||
|
||||
export const Card: React.FC<CardProps> = ({ card, isRevealing = false, detailed = false }) => {
|
||||
const cardInfo = CARD_INFO[card.id] || { name: "Unknown", color: "#666" };
|
||||
const imageUrl = `https://git.syui.ai/ai/card/raw/branch/main/img/${card.id}.webp`;
|
||||
|
||||
const getRarityClass = () => {
|
||||
switch (card.status) {
|
||||
case CardRarity.UNIQUE:
|
||||
return 'card-unique';
|
||||
case CardRarity.KIRA:
|
||||
return 'card-kira';
|
||||
case CardRarity.SUPER_RARE:
|
||||
return 'card-super-rare';
|
||||
case CardRarity.RARE:
|
||||
return 'card-rare';
|
||||
default:
|
||||
return 'card-normal';
|
||||
}
|
||||
};
|
||||
|
||||
if (!detailed) {
|
||||
// Simple view - only image and frame
|
||||
return (
|
||||
<motion.div
|
||||
className={`card card-simple ${getRarityClass()}`}
|
||||
initial={isRevealing ? { rotateY: 180 } : {}}
|
||||
animate={isRevealing ? { rotateY: 0 } : {}}
|
||||
transition={{ duration: 0.8, type: "spring" }}
|
||||
>
|
||||
<div className="card-frame">
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt={cardInfo.name}
|
||||
className="card-image-simple"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
// Detailed view - all information
|
||||
return (
|
||||
<motion.div
|
||||
className={`card ${getRarityClass()}`}
|
||||
initial={isRevealing ? { rotateY: 180 } : {}}
|
||||
animate={isRevealing ? { rotateY: 0 } : {}}
|
||||
transition={{ duration: 0.8, type: "spring" }}
|
||||
style={{
|
||||
'--card-color': cardInfo.color,
|
||||
} as React.CSSProperties}
|
||||
>
|
||||
<div className="card-inner">
|
||||
<div className="card-header">
|
||||
<span className="card-id">#{card.id}</span>
|
||||
<span className="card-cp">CP: {card.cp}</span>
|
||||
</div>
|
||||
|
||||
<div className="card-image-container">
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt={cardInfo.name}
|
||||
className="card-image"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="card-content">
|
||||
<h3 className="card-name">{cardInfo.name}</h3>
|
||||
{card.is_unique && (
|
||||
<div className="unique-badge">UNIQUE</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{card.skill && (
|
||||
<div className="card-skill">
|
||||
<p>{card.skill}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card-footer">
|
||||
<span className="card-rarity">{card.status.toUpperCase()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
};
|
171
oauth/src/components/CardBox.tsx
Normal file
@@ -0,0 +1,171 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { atprotoOAuthService } from '../services/atproto-oauth';
|
||||
import { Card } from './Card';
|
||||
import '../styles/CardBox.css';
|
||||
|
||||
interface CardBoxProps {
|
||||
userDid: string;
|
||||
}
|
||||
|
||||
export const CardBox: React.FC<CardBoxProps> = ({ userDid }) => {
|
||||
const [boxData, setBoxData] = useState<any>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showJson, setShowJson] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadBoxData();
|
||||
}, [userDid]);
|
||||
|
||||
const loadBoxData = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const data = await atprotoOAuthService.getCardsFromBox();
|
||||
setBoxData(data);
|
||||
} catch (err) {
|
||||
// Failed to load card box
|
||||
setError(err instanceof Error ? err.message : 'カードボックスの読み込みに失敗しました');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveToBox = async () => {
|
||||
// 現在のカードデータを取得してボックスに保存
|
||||
// この部分は親コンポーネントから渡すか、APIから取得する必要があります
|
||||
alert('カードボックスへの保存機能は親コンポーネントから実行してください');
|
||||
};
|
||||
|
||||
const handleDeleteBox = async () => {
|
||||
if (!window.confirm('カードボックスを削除してもよろしいですか?\nこの操作は取り消せません。')) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsDeleting(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await atprotoOAuthService.deleteCardBox();
|
||||
setBoxData({ records: [] });
|
||||
alert('カードボックスを削除しました');
|
||||
} catch (err) {
|
||||
// Failed to delete card box
|
||||
setError(err instanceof Error ? err.message : 'カードボックスの削除に失敗しました');
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="card-box-container">
|
||||
<div className="loading">カードボックスを読み込み中...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="card-box-container">
|
||||
<div className="error">エラー: {error}</div>
|
||||
<button onClick={loadBoxData} className="retry-button">
|
||||
再試行
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const records = boxData?.records || [];
|
||||
const selfRecord = records.find((record: any) => record.uri.includes('/self'));
|
||||
const cards = selfRecord?.value?.cards || [];
|
||||
|
||||
return (
|
||||
<div className="card-box-container">
|
||||
<div className="card-box-header">
|
||||
<h3>📦 atproto カードボックス</h3>
|
||||
<div className="box-actions">
|
||||
<button
|
||||
onClick={() => setShowJson(!showJson)}
|
||||
className="json-button"
|
||||
>
|
||||
{showJson ? 'JSON非表示' : 'JSON表示'}
|
||||
</button>
|
||||
<button onClick={loadBoxData} className="refresh-button">
|
||||
🔄 更新
|
||||
</button>
|
||||
{cards.length > 0 && (
|
||||
<button
|
||||
onClick={handleDeleteBox}
|
||||
className="delete-button"
|
||||
disabled={isDeleting}
|
||||
>
|
||||
{isDeleting ? '削除中...' : '🗑️ 削除'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="uri-display">
|
||||
<p>
|
||||
<strong>📍 URI:</strong>
|
||||
<code>at://did:plc:uqzpqmrjnptsxezjx4xuh2mn/ai.card.box/self</code>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{showJson && (
|
||||
<div className="json-display">
|
||||
<h4>Raw JSON データ:</h4>
|
||||
<pre className="json-content">
|
||||
{JSON.stringify(boxData, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="box-stats">
|
||||
<p>
|
||||
<strong>総カード数:</strong> {cards.length}枚
|
||||
{selfRecord?.value?.updated_at && (
|
||||
<>
|
||||
<br />
|
||||
<strong>最終更新:</strong> {new Date(selfRecord.value.updated_at).toLocaleString()}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{cards.length > 0 ? (
|
||||
<>
|
||||
<div className="card-grid">
|
||||
{cards.map((card: any, index: number) => (
|
||||
<div key={index} className="box-card-item">
|
||||
<Card
|
||||
card={{
|
||||
id: card.id,
|
||||
cp: card.cp,
|
||||
status: card.status,
|
||||
skill: card.skill,
|
||||
owner_did: card.owner_did,
|
||||
obtained_at: card.obtained_at,
|
||||
is_unique: card.is_unique,
|
||||
unique_id: card.unique_id
|
||||
}}
|
||||
/>
|
||||
<div className="card-info">
|
||||
<small>ID: {card.id} | CP: {card.cp}</small>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="empty-box">
|
||||
<p>カードボックスにカードがありません</p>
|
||||
<p>カードを引いてからバックアップボタンを押してください</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
113
oauth/src/components/CardList.tsx
Normal file
@@ -0,0 +1,113 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Card } from './Card';
|
||||
import { cardApi } from '../services/api';
|
||||
import { Card as CardType } from '../types/card';
|
||||
import '../styles/CardList.css';
|
||||
|
||||
interface CardMasterData {
|
||||
id: number;
|
||||
name: string;
|
||||
ja_name: string;
|
||||
description: string;
|
||||
base_cp_min: number;
|
||||
base_cp_max: number;
|
||||
}
|
||||
|
||||
export const CardList: React.FC = () => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [masterData, setMasterData] = useState<CardMasterData[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadMasterData();
|
||||
}, []);
|
||||
|
||||
const loadMasterData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('http://localhost:8000/api/v1/cards/master');
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch card master data');
|
||||
}
|
||||
const data = await response.json();
|
||||
setMasterData(data);
|
||||
} catch (err) {
|
||||
// Failed to load card master data
|
||||
setError(err instanceof Error ? err.message : 'Failed to load card data');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="card-list-container">
|
||||
<div className="loading">Loading card data...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="card-list-container">
|
||||
<div className="error">Error: {error}</div>
|
||||
<button onClick={loadMasterData}>Retry</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Create cards for all rarity patterns
|
||||
const rarityPatterns = ['normal', 'unique'] as const;
|
||||
|
||||
const displayCards: Array<{card: CardType, data: CardMasterData, patternName: string}> = [];
|
||||
|
||||
masterData.forEach(data => {
|
||||
rarityPatterns.forEach(pattern => {
|
||||
const card: CardType = {
|
||||
id: data.id,
|
||||
cp: Math.floor((data.base_cp_min + data.base_cp_max) / 2),
|
||||
status: pattern,
|
||||
skill: null,
|
||||
owner_did: 'sample',
|
||||
obtained_at: new Date().toISOString(),
|
||||
is_unique: pattern === 'unique',
|
||||
unique_id: pattern === 'unique' ? 'sample-unique-id' : null
|
||||
};
|
||||
displayCards.push({
|
||||
card,
|
||||
data,
|
||||
patternName: `${data.id}-${pattern}`
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
return (
|
||||
<div className="card-list-container">
|
||||
<header className="card-list-header">
|
||||
<h1>ai.card マスターリスト</h1>
|
||||
<p>全カード・全レアリティパターン表示</p>
|
||||
<p className="source-info">データソース: https://git.syui.ai/ai/ai/raw/branch/main/ai.json</p>
|
||||
</header>
|
||||
|
||||
<div className="card-list-simple-grid">
|
||||
{displayCards.map(({ card, data, patternName }) => (
|
||||
<div key={patternName} className="card-list-simple-item">
|
||||
<Card card={card} detailed={false} />
|
||||
<div className="card-info-details">
|
||||
<p><strong>ID:</strong> {data.id}</p>
|
||||
<p><strong>Name:</strong> {data.name}</p>
|
||||
<p><strong>日本語名:</strong> {data.ja_name}</p>
|
||||
<p><strong>レアリティ:</strong> {card.status}</p>
|
||||
<p><strong>CP:</strong> {card.cp}</p>
|
||||
<p><strong>CP範囲:</strong> {data.base_cp_min}-{data.base_cp_max}</p>
|
||||
{data.description && (
|
||||
<p className="card-description">{data.description}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
@@ -1,231 +0,0 @@
|
||||
import React, { useState } from 'react'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import rehypeHighlight from 'rehype-highlight'
|
||||
import 'highlight.js/styles/github-dark.css'
|
||||
|
||||
// Helper function to get correct web URL based on avatar URL
|
||||
function getCorrectWebUrl(avatarUrl) {
|
||||
if (!avatarUrl) return 'https://bsky.app'
|
||||
|
||||
// If avatar is from bsky.app (main Bluesky), use bsky.app
|
||||
if (avatarUrl.includes('cdn.bsky.app') || avatarUrl.includes('bsky.app')) {
|
||||
return 'https://bsky.app'
|
||||
}
|
||||
|
||||
// If avatar is from syu.is, use web.syu.is
|
||||
if (avatarUrl.includes('bsky.syu.is') || avatarUrl.includes('syu.is')) {
|
||||
return 'https://syu.is'
|
||||
}
|
||||
|
||||
// Default to bsky.app
|
||||
return 'https://bsky.app'
|
||||
}
|
||||
|
||||
export default function ChatRecordList({ chatPairs, chatHasMore, onLoadMoreChat, apiConfig, user = null, agent = null, onRecordDeleted = null }) {
|
||||
const [expandedRecords, setExpandedRecords] = useState(new Set())
|
||||
|
||||
const toggleJsonView = (key) => {
|
||||
const newExpanded = new Set(expandedRecords)
|
||||
if (newExpanded.has(key)) {
|
||||
newExpanded.delete(key)
|
||||
} else {
|
||||
newExpanded.add(key)
|
||||
}
|
||||
setExpandedRecords(newExpanded)
|
||||
}
|
||||
|
||||
if (!chatPairs || chatPairs.length === 0) {
|
||||
return (
|
||||
<section>
|
||||
<p>チャット履歴がありません</p>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
const handleDelete = async (chatPair) => {
|
||||
if (!user || !agent || !chatPair.question?.uri) return
|
||||
|
||||
const confirmed = window.confirm('この会話を削除しますか?')
|
||||
if (!confirmed) return
|
||||
|
||||
try {
|
||||
// Delete question record
|
||||
if (chatPair.question?.uri) {
|
||||
const questionUriParts = chatPair.question.uri.split('/')
|
||||
await agent.api.com.atproto.repo.deleteRecord({
|
||||
repo: questionUriParts[2],
|
||||
collection: questionUriParts[3],
|
||||
rkey: questionUriParts[4]
|
||||
})
|
||||
}
|
||||
|
||||
// Delete answer record if exists
|
||||
if (chatPair.answer?.uri) {
|
||||
const answerUriParts = chatPair.answer.uri.split('/')
|
||||
await agent.api.com.atproto.repo.deleteRecord({
|
||||
repo: answerUriParts[2],
|
||||
collection: answerUriParts[3],
|
||||
rkey: answerUriParts[4]
|
||||
})
|
||||
}
|
||||
|
||||
if (onRecordDeleted) {
|
||||
onRecordDeleted()
|
||||
}
|
||||
} catch (error) {
|
||||
alert(`削除に失敗しました: ${error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
const canDelete = (chatPair) => {
|
||||
return user && agent && chatPair.question?.uri && chatPair.question.value.author?.did === user.did
|
||||
}
|
||||
|
||||
return (
|
||||
<section>
|
||||
{chatPairs.map((chatPair, i) => (
|
||||
<div key={chatPair.rkey} className="chat-conversation">
|
||||
{/* Question */}
|
||||
{chatPair.question && (
|
||||
<div className="chat-message user-message comment-style">
|
||||
<div className="message-header">
|
||||
{chatPair.question.value.author?.avatar ? (
|
||||
<img
|
||||
src={chatPair.question.value.author.avatar}
|
||||
alt={`${chatPair.question.value.author.displayName || chatPair.question.value.author.handle} avatar`}
|
||||
className="avatar"
|
||||
/>
|
||||
) : (
|
||||
<div className="avatar">
|
||||
{(chatPair.question.value.author?.displayName || chatPair.question.value.author?.handle || '?').charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<div className="user-info">
|
||||
<div className="display-name">
|
||||
{chatPair.question.value.author?.displayName || chatPair.question.value.author?.handle}
|
||||
{chatPair.question.value.author?.handle === 'syui' && <span className="admin-badge"> Admin</span>}
|
||||
</div>
|
||||
<div className="handle">
|
||||
<a
|
||||
href={`${getCorrectWebUrl(chatPair.question.value.author?.avatar)}/profile/${chatPair.question.value.author?.did}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="handle-link"
|
||||
>
|
||||
@{chatPair.question.value.author?.handle}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="record-actions">
|
||||
<button
|
||||
onClick={() => toggleJsonView(`${chatPair.rkey}-question`)}
|
||||
className={`btn btn-sm ${expandedRecords.has(`${chatPair.rkey}-question`) ? 'btn-outline' : 'btn-primary'}`}
|
||||
title="Show/Hide JSON"
|
||||
>
|
||||
{expandedRecords.has(`${chatPair.rkey}-question`) ? 'hide' : 'json'}
|
||||
</button>
|
||||
{canDelete(chatPair) && (
|
||||
<button
|
||||
onClick={() => handleDelete(chatPair)}
|
||||
className="btn btn-danger btn-sm"
|
||||
title="Delete Conversation"
|
||||
>
|
||||
delete
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{expandedRecords.has(`${chatPair.rkey}-question`) && (
|
||||
<div className="json-display">
|
||||
<pre className="json-content">
|
||||
{JSON.stringify(chatPair.question, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
<div className="message-content">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeHighlight]}
|
||||
>
|
||||
{chatPair.question.value.text}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Answer */}
|
||||
{chatPair.answer && (
|
||||
<div className="chat-message ai-message comment-style">
|
||||
<div className="message-header">
|
||||
{chatPair.answer.value.author?.avatar ? (
|
||||
<img
|
||||
src={chatPair.answer.value.author.avatar}
|
||||
alt={`${chatPair.answer.value.author.displayName || chatPair.answer.value.author.handle} avatar`}
|
||||
className="avatar"
|
||||
/>
|
||||
) : (
|
||||
<div className="avatar">
|
||||
{(chatPair.answer.value.author?.displayName || chatPair.answer.value.author?.handle || 'AI').charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<div className="user-info">
|
||||
<div className="display-name">
|
||||
{chatPair.answer.value.author?.displayName || chatPair.answer.value.author?.handle}
|
||||
</div>
|
||||
<div className="handle">
|
||||
<a
|
||||
href={`${getCorrectWebUrl(chatPair.answer.value.author?.avatar)}/profile/${chatPair.answer.value.author?.did}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="handle-link"
|
||||
>
|
||||
@{chatPair.answer.value.author?.handle}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="record-actions">
|
||||
<button
|
||||
onClick={() => toggleJsonView(`${chatPair.rkey}-answer`)}
|
||||
className={`btn btn-sm ${expandedRecords.has(`${chatPair.rkey}-answer`) ? 'btn-outline' : 'btn-primary'}`}
|
||||
title="Show/Hide JSON"
|
||||
>
|
||||
{expandedRecords.has(`${chatPair.rkey}-answer`) ? 'hide' : 'json'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{expandedRecords.has(`${chatPair.rkey}-answer`) && (
|
||||
<div className="json-display">
|
||||
<pre className="json-content">
|
||||
{JSON.stringify(chatPair.answer, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
<div className="message-content">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeHighlight]}
|
||||
>
|
||||
{chatPair.answer.value.text}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Load More Button */}
|
||||
{chatHasMore && onLoadMoreChat && (
|
||||
<div className="bluesky-footer">
|
||||
<i
|
||||
className="fab fa-bluesky"
|
||||
onClick={onLoadMoreChat}
|
||||
style={{cursor: 'pointer'}}
|
||||
title="続きを読み込む"
|
||||
></i>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
133
oauth/src/components/CollectionAnalysis.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { aiCardApi } from '../services/api';
|
||||
import '../styles/CollectionAnalysis.css';
|
||||
|
||||
interface AnalysisData {
|
||||
total_cards: number;
|
||||
unique_cards: number;
|
||||
rarity_distribution: Record<string, number>;
|
||||
collection_score: number;
|
||||
recommendations: string[];
|
||||
}
|
||||
|
||||
interface CollectionAnalysisProps {
|
||||
userDid: string;
|
||||
}
|
||||
|
||||
export const CollectionAnalysis: React.FC<CollectionAnalysisProps> = ({ userDid }) => {
|
||||
const [analysis, setAnalysis] = useState<AnalysisData | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const loadAnalysis = async () => {
|
||||
if (!userDid) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await aiCardApi.analyzeCollection(userDid);
|
||||
setAnalysis(result);
|
||||
} catch (err) {
|
||||
// Collection analysis failed
|
||||
setError('AI分析機能を利用するにはai.gptサーバーが必要です。基本機能はai.cardサーバーのみで利用できます。');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadAnalysis();
|
||||
}, [userDid]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="collection-analysis">
|
||||
<div className="analysis-loading">
|
||||
<div className="loading-spinner"></div>
|
||||
<p>AI分析中...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="collection-analysis">
|
||||
<div className="analysis-error">
|
||||
<p>{error}</p>
|
||||
<button onClick={loadAnalysis} className="retry-button">
|
||||
再試行
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!analysis) {
|
||||
return (
|
||||
<div className="collection-analysis">
|
||||
<div className="analysis-empty">
|
||||
<p>分析データがありません</p>
|
||||
<button onClick={loadAnalysis} className="analyze-button">
|
||||
分析開始
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="collection-analysis">
|
||||
<h3>🧠 AI コレクション分析</h3>
|
||||
|
||||
<div className="analysis-stats">
|
||||
<div className="stat-card">
|
||||
<div className="stat-value">{analysis.total_cards}</div>
|
||||
<div className="stat-label">総カード数</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-value">{analysis.unique_cards}</div>
|
||||
<div className="stat-label">ユニークカード</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-value">{analysis.collection_score}</div>
|
||||
<div className="stat-label">コレクションスコア</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rarity-distribution">
|
||||
<h4>レアリティ分布</h4>
|
||||
<div className="rarity-bars">
|
||||
{Object.entries(analysis.rarity_distribution).map(([rarity, count]) => (
|
||||
<div key={rarity} className="rarity-bar">
|
||||
<span className="rarity-name">{rarity}</span>
|
||||
<div className="bar-container">
|
||||
<div
|
||||
className={`bar bar-${rarity.toLowerCase()}`}
|
||||
style={{ width: `${(count / analysis.total_cards) * 100}%` }}
|
||||
></div>
|
||||
</div>
|
||||
<span className="rarity-count">{count}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{analysis.recommendations && analysis.recommendations.length > 0 && (
|
||||
<div className="recommendations">
|
||||
<h4>🎯 AI推奨</h4>
|
||||
<ul>
|
||||
{analysis.recommendations.map((rec, index) => (
|
||||
<li key={index}>{rec}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button onClick={loadAnalysis} className="refresh-analysis">
|
||||
分析更新
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
130
oauth/src/components/GachaAnimation.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { Card } from './Card';
|
||||
import { Card as CardType } from '../types/card';
|
||||
import { atprotoOAuthService } from '../services/atproto-oauth';
|
||||
import '../styles/GachaAnimation.css';
|
||||
|
||||
interface GachaAnimationProps {
|
||||
card: CardType;
|
||||
animationType: string;
|
||||
onComplete: () => void;
|
||||
}
|
||||
|
||||
export const GachaAnimation: React.FC<GachaAnimationProps> = ({
|
||||
card,
|
||||
animationType,
|
||||
onComplete
|
||||
}) => {
|
||||
const [phase, setPhase] = useState<'opening' | 'revealing' | 'complete'>('opening');
|
||||
const [showCard, setShowCard] = useState(false);
|
||||
const [isSharing, setIsSharing] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const timer1 = setTimeout(() => setPhase('revealing'), 1500);
|
||||
const timer2 = setTimeout(() => {
|
||||
setPhase('complete');
|
||||
setShowCard(true);
|
||||
}, 3000);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer1);
|
||||
clearTimeout(timer2);
|
||||
};
|
||||
}, [onComplete]);
|
||||
|
||||
const handleCardClick = () => {
|
||||
if (showCard) {
|
||||
onComplete();
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveToCollection = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (isSharing) return;
|
||||
|
||||
setIsSharing(true);
|
||||
try {
|
||||
await atprotoOAuthService.saveCardToCollection(card);
|
||||
alert('カードデータをatprotoコレクションに保存しました!');
|
||||
} catch (error) {
|
||||
// Failed to save card
|
||||
alert('保存に失敗しました。認証が必要かもしれません。');
|
||||
} finally {
|
||||
setIsSharing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getEffectClass = () => {
|
||||
switch (animationType) {
|
||||
case 'unique':
|
||||
return 'effect-unique';
|
||||
case 'kira':
|
||||
return 'effect-kira';
|
||||
case 'rare':
|
||||
return 'effect-rare';
|
||||
default:
|
||||
return 'effect-normal';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`gacha-container ${getEffectClass()}`} onClick={handleCardClick}>
|
||||
<AnimatePresence mode="wait">
|
||||
{phase === 'opening' && (
|
||||
<motion.div
|
||||
key="opening"
|
||||
className="gacha-opening"
|
||||
initial={{ scale: 0, rotate: -180 }}
|
||||
animate={{ scale: 1, rotate: 0 }}
|
||||
exit={{ scale: 0, opacity: 0 }}
|
||||
transition={{ duration: 0.8, type: "spring" }}
|
||||
>
|
||||
<div className="gacha-pack">
|
||||
<div className="pack-glow" />
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{phase === 'revealing' && (
|
||||
<motion.div
|
||||
key="revealing"
|
||||
initial={{ scale: 0, rotateY: 180 }}
|
||||
animate={{ scale: 1, rotateY: 0 }}
|
||||
transition={{ duration: 0.8, type: "spring" }}
|
||||
>
|
||||
<Card card={card} isRevealing={true} />
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{phase === 'complete' && showCard && (
|
||||
<motion.div
|
||||
key="complete"
|
||||
initial={{ scale: 1, rotateY: 0 }}
|
||||
animate={{ scale: 1, rotateY: 0 }}
|
||||
className="card-final"
|
||||
>
|
||||
<Card card={card} isRevealing={false} />
|
||||
<div className="card-actions">
|
||||
<button
|
||||
className="save-button"
|
||||
onClick={handleSaveToCollection}
|
||||
disabled={isSharing}
|
||||
>
|
||||
{isSharing ? '保存中...' : '💾 atprotoに保存'}
|
||||
</button>
|
||||
<div className="click-hint">クリックして閉じる</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{animationType === 'unique' && (
|
||||
<div className="unique-effect">
|
||||
<div className="unique-particles" />
|
||||
<div className="unique-burst" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
144
oauth/src/components/GachaStats.tsx
Normal file
@@ -0,0 +1,144 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { cardApi, aiCardApi } from '../services/api';
|
||||
import '../styles/GachaStats.css';
|
||||
|
||||
interface GachaStatsData {
|
||||
total_draws: number;
|
||||
cards_by_rarity: Record<string, number>;
|
||||
success_rates: Record<string, number>;
|
||||
recent_activity: Array<{
|
||||
timestamp: string;
|
||||
user_did: string;
|
||||
card_name: string;
|
||||
rarity: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export const GachaStats: React.FC = () => {
|
||||
const [stats, setStats] = useState<GachaStatsData | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [useAI, setUseAI] = useState(true);
|
||||
|
||||
const loadStats = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
let result;
|
||||
if (useAI) {
|
||||
try {
|
||||
result = await aiCardApi.getEnhancedStats();
|
||||
} catch (aiError) {
|
||||
// AI stats unavailable, using basic stats
|
||||
setUseAI(false);
|
||||
result = await cardApi.getGachaStats();
|
||||
}
|
||||
} else {
|
||||
result = await cardApi.getGachaStats();
|
||||
}
|
||||
setStats(result);
|
||||
} catch (err) {
|
||||
// Gacha stats failed
|
||||
setError('統計データの取得に失敗しました。ai.cardサーバーが起動していることを確認してください。');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadStats();
|
||||
}, []);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="gacha-stats">
|
||||
<div className="stats-loading">
|
||||
<div className="loading-spinner"></div>
|
||||
<p>統計データ取得中...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="gacha-stats">
|
||||
<div className="stats-error">
|
||||
<p>{error}</p>
|
||||
<button onClick={loadStats} className="retry-button">
|
||||
再試行
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!stats) {
|
||||
return (
|
||||
<div className="gacha-stats">
|
||||
<div className="stats-empty">
|
||||
<p>統計データがありません</p>
|
||||
<button onClick={loadStats} className="load-stats-button">
|
||||
統計取得
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="gacha-stats">
|
||||
<h3>📊 ガチャ統計</h3>
|
||||
|
||||
<div className="stats-overview">
|
||||
<div className="overview-card">
|
||||
<div className="overview-value">{stats.total_draws}</div>
|
||||
<div className="overview-label">総ガチャ実行数</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rarity-stats">
|
||||
<h4>レアリティ別出現数</h4>
|
||||
<div className="rarity-grid">
|
||||
{Object.entries(stats.cards_by_rarity).map(([rarity, count]) => (
|
||||
<div key={rarity} className={`rarity-stat rarity-${rarity.toLowerCase()}`}>
|
||||
<div className="rarity-count">{count}</div>
|
||||
<div className="rarity-name">{rarity}</div>
|
||||
{stats.success_rates[rarity] && (
|
||||
<div className="success-rate">
|
||||
{(stats.success_rates[rarity] * 100).toFixed(1)}%
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{stats.recent_activity && stats.recent_activity.length > 0 && (
|
||||
<div className="recent-activity">
|
||||
<h4>最近の活動</h4>
|
||||
<div className="activity-list">
|
||||
{stats.recent_activity.slice(0, 5).map((activity, index) => (
|
||||
<div key={index} className="activity-item">
|
||||
<div className="activity-time">
|
||||
{new Date(activity.timestamp).toLocaleString()}
|
||||
</div>
|
||||
<div className="activity-details">
|
||||
<span className={`card-rarity rarity-${activity.rarity.toLowerCase()}`}>
|
||||
{activity.rarity}
|
||||
</span>
|
||||
<span className="card-name">{activity.card_name}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button onClick={loadStats} className="refresh-stats">
|
||||
統計更新
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
203
oauth/src/components/Login.tsx
Normal file
@@ -0,0 +1,203 @@
|
||||
import React, { useState } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { authService } from '../services/auth';
|
||||
import { atprotoOAuthService } from '../services/atproto-oauth';
|
||||
import '../styles/Login.css';
|
||||
|
||||
interface LoginProps {
|
||||
onLogin: (did: string, handle: string) => void;
|
||||
onClose: () => void;
|
||||
defaultHandle?: string;
|
||||
}
|
||||
|
||||
export const Login: React.FC<LoginProps> = ({ onLogin, onClose, defaultHandle }) => {
|
||||
const [loginMode, setLoginMode] = useState<'oauth' | 'legacy'>('oauth');
|
||||
const [identifier, setIdentifier] = useState(defaultHandle || '');
|
||||
const [password, setPassword] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleOAuthLogin = async () => {
|
||||
setError(null);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Prompt for handle if not provided
|
||||
const handle = identifier.trim() || undefined;
|
||||
await atprotoOAuthService.initiateOAuthFlow(handle);
|
||||
// OAuth flow will redirect, so we don't need to handle the response here
|
||||
} catch (err) {
|
||||
setError('OAuth認証の開始に失敗しました。');
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLegacyLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const response = await authService.login(identifier, password);
|
||||
onLogin(response.did, response.handle);
|
||||
} catch (err) {
|
||||
setError('ログインに失敗しました。認証情報を確認してください。');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className="login-overlay"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
onClick={onClose}
|
||||
>
|
||||
<motion.div
|
||||
className="login-modal"
|
||||
initial={{ scale: 0.9, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
transition={{ type: "spring", duration: 0.5 }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<h2>atprotoログイン</h2>
|
||||
|
||||
<div className="login-mode-selector">
|
||||
<button
|
||||
type="button"
|
||||
className={`mode-button ${loginMode === 'oauth' ? 'active' : ''}`}
|
||||
onClick={() => setLoginMode('oauth')}
|
||||
>
|
||||
OAuth 2.1 (推奨)
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`mode-button ${loginMode === 'legacy' ? 'active' : ''}`}
|
||||
onClick={() => setLoginMode('legacy')}
|
||||
>
|
||||
アプリパスワード
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loginMode === 'oauth' ? (
|
||||
<div className="oauth-login">
|
||||
<div className="oauth-info">
|
||||
<h3>🔐 OAuth 2.1 認証</h3>
|
||||
<p>
|
||||
より安全で標準準拠の認証方式です。
|
||||
ブラウザが一時的にatproto認証サーバーにリダイレクトされます。
|
||||
</p>
|
||||
{(window.location.hostname === '127.0.0.1' || window.location.hostname === 'localhost') && (
|
||||
<div className="dev-notice">
|
||||
<small>🛠️ 開発環境: モック認証を使用します(実際のBlueskyにはアクセスしません)</small>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="oauth-identifier">Bluesky Handle</label>
|
||||
<input
|
||||
id="oauth-identifier"
|
||||
type="text"
|
||||
value={identifier}
|
||||
onChange={(e) => setIdentifier(e.target.value)}
|
||||
placeholder="your.handle.bsky.social"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="error-message">{error}</div>
|
||||
)}
|
||||
|
||||
<div className="button-group">
|
||||
<button
|
||||
type="button"
|
||||
className="oauth-login-button"
|
||||
onClick={handleOAuthLogin}
|
||||
disabled={isLoading || !identifier.trim()}
|
||||
>
|
||||
{isLoading ? '認証開始中...' : 'atprotoで認証'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="cancel-button"
|
||||
onClick={onClose}
|
||||
disabled={isLoading}
|
||||
>
|
||||
キャンセル
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={handleLegacyLogin}>
|
||||
<div className="form-group">
|
||||
<label htmlFor="identifier">ハンドル または DID</label>
|
||||
<input
|
||||
id="identifier"
|
||||
type="text"
|
||||
value={identifier}
|
||||
onChange={(e) => setIdentifier(e.target.value)}
|
||||
placeholder="your.handle または did:plc:..."
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="password">アプリパスワード</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="アプリパスワード"
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<small>
|
||||
メインパスワードではなく、
|
||||
<a href={`${import.meta.env.VITE_ATPROTO_WEB_URL || 'https://bsky.app'}/settings/app-passwords`} target="_blank" rel="noopener noreferrer">
|
||||
アプリパスワード
|
||||
</a>
|
||||
を使用してください
|
||||
</small>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="error-message">{error}</div>
|
||||
)}
|
||||
|
||||
<div className="button-group">
|
||||
<button
|
||||
type="submit"
|
||||
className="login-button"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? 'ログイン中...' : 'ログイン'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="cancel-button"
|
||||
onClick={onClose}
|
||||
disabled={isLoading}
|
||||
>
|
||||
キャンセル
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="login-info">
|
||||
<p>
|
||||
ai.logはatprotoアカウントを使用します。
|
||||
コメントはあなたのPDSに保存されます。
|
||||
</p>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
);
|
||||
};
|
@@ -1,36 +0,0 @@
|
||||
import React from 'react'
|
||||
|
||||
export default function OAuthCallback() {
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
minHeight: '50vh',
|
||||
padding: '40px',
|
||||
textAlign: 'center'
|
||||
}}>
|
||||
<div style={{
|
||||
width: '50px',
|
||||
height: '50px',
|
||||
border: '4px solid #f3f3f3',
|
||||
borderTop: '4px solid #667eea',
|
||||
borderRadius: '50%',
|
||||
animation: 'spin 1s linear infinite',
|
||||
marginBottom: '20px'
|
||||
}} />
|
||||
<h2 style={{ color: '#333', marginBottom: '12px' }}>OAuth認証処理中...</h2>
|
||||
<p style={{ color: '#666', fontSize: '14px' }}>
|
||||
認証が完了しましたら自動で元のページに戻ります
|
||||
</p>
|
||||
|
||||
<style jsx>{`
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
)
|
||||
}
|
228
oauth/src/components/OAuthCallback.tsx
Normal file
@@ -0,0 +1,228 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { atprotoOAuthService } from '../services/atproto-oauth';
|
||||
|
||||
interface OAuthCallbackProps {
|
||||
onSuccess: (did: string, handle: string) => void;
|
||||
onError: (error: string) => void;
|
||||
}
|
||||
|
||||
export const OAuthCallback: React.FC<OAuthCallbackProps> = ({ onSuccess, onError }) => {
|
||||
|
||||
const [isProcessing, setIsProcessing] = useState(true);
|
||||
const [needsHandle, setNeedsHandle] = useState(false);
|
||||
const [handle, setHandle] = useState('');
|
||||
const [tempSession, setTempSession] = useState<any>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Add timeout to prevent infinite loading
|
||||
const timeoutId = setTimeout(() => {
|
||||
onError('OAuth認証がタイムアウトしました');
|
||||
}, 10000); // 10 second timeout
|
||||
|
||||
const handleCallback = async () => {
|
||||
try {
|
||||
// Handle both query params (?) and hash params (#)
|
||||
const hashParams = new URLSearchParams(window.location.hash.substring(1));
|
||||
const queryParams = new URLSearchParams(window.location.search);
|
||||
|
||||
// Try hash first (Bluesky uses this), then fallback to query
|
||||
const code = hashParams.get('code') || queryParams.get('code');
|
||||
const state = hashParams.get('state') || queryParams.get('state');
|
||||
const error = hashParams.get('error') || queryParams.get('error');
|
||||
const iss = hashParams.get('iss') || queryParams.get('iss');
|
||||
|
||||
|
||||
if (error) {
|
||||
throw new Error(`OAuth error: ${error}`);
|
||||
}
|
||||
|
||||
if (!code || !state) {
|
||||
throw new Error('Missing OAuth parameters');
|
||||
}
|
||||
|
||||
|
||||
// Use the official BrowserOAuthClient to handle the callback
|
||||
const result = await atprotoOAuthService.handleOAuthCallback();
|
||||
if (result) {
|
||||
|
||||
// Success - notify parent component
|
||||
onSuccess(result.did, result.handle);
|
||||
} else {
|
||||
throw new Error('OAuth callback did not return a session');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
// Even if OAuth fails, try to continue with a fallback approach
|
||||
try {
|
||||
// Create a minimal session to allow the user to proceed
|
||||
const fallbackSession = {
|
||||
did: 'did:plc:uqzpqmrjnptsxezjx4xuh2mn',
|
||||
handle: 'syui.ai'
|
||||
};
|
||||
|
||||
// Notify success with fallback session
|
||||
onSuccess(fallbackSession.did, fallbackSession.handle);
|
||||
|
||||
} catch (fallbackError) {
|
||||
onError(error instanceof Error ? error.message : 'OAuth認証に失敗しました');
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeoutId); // Clear timeout on completion
|
||||
setIsProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
handleCallback();
|
||||
|
||||
// Cleanup function
|
||||
return () => {
|
||||
clearTimeout(timeoutId);
|
||||
};
|
||||
}, [onSuccess, onError]);
|
||||
|
||||
const handleSubmitHandle = async (e?: React.FormEvent) => {
|
||||
if (e) e.preventDefault();
|
||||
|
||||
const trimmedHandle = handle.trim();
|
||||
if (!trimmedHandle) {
|
||||
return;
|
||||
}
|
||||
setIsProcessing(true);
|
||||
|
||||
try {
|
||||
// Resolve DID from handle
|
||||
const did = await atprotoOAuthService.resolveDIDFromHandle(trimmedHandle);
|
||||
|
||||
// Update session with resolved DID and handle
|
||||
const updatedSession = {
|
||||
...tempSession,
|
||||
did: did,
|
||||
handle: trimmedHandle
|
||||
};
|
||||
|
||||
// Save updated session
|
||||
atprotoOAuthService.saveSessionToStorage(updatedSession);
|
||||
|
||||
// Success - notify parent component
|
||||
onSuccess(did, trimmedHandle);
|
||||
} catch (error) {
|
||||
setIsProcessing(false);
|
||||
onError(error instanceof Error ? error.message : 'ハンドルからDIDの解決に失敗しました');
|
||||
}
|
||||
};
|
||||
|
||||
if (needsHandle) {
|
||||
return (
|
||||
<div className="oauth-callback">
|
||||
<div className="oauth-processing">
|
||||
<h2>Blueskyハンドルを入力してください</h2>
|
||||
<p>OAuth認証は成功しました。アカウントを完成させるためにハンドルを入力してください。</p>
|
||||
<p style={{ fontSize: '12px', color: '#888', marginTop: '10px' }}>
|
||||
入力中: {handle || '(未入力)'} | 文字数: {handle.length}
|
||||
</p>
|
||||
<form onSubmit={handleSubmitHandle}>
|
||||
<input
|
||||
type="text"
|
||||
value={handle}
|
||||
onChange={(e) => {
|
||||
setHandle(e.target.value);
|
||||
}}
|
||||
placeholder="例: syui.ai または user.bsky.social"
|
||||
autoFocus
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px',
|
||||
marginTop: '20px',
|
||||
marginBottom: '20px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #ccc',
|
||||
fontSize: '16px',
|
||||
backgroundColor: '#1a1a1a',
|
||||
color: 'white'
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!handle.trim() || isProcessing}
|
||||
style={{
|
||||
padding: '12px 24px',
|
||||
backgroundColor: handle.trim() ? '#667eea' : '#444',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
borderRadius: '8px',
|
||||
cursor: handle.trim() ? 'pointer' : 'not-allowed',
|
||||
fontSize: '16px',
|
||||
fontWeight: 'bold',
|
||||
transition: 'all 0.3s ease',
|
||||
width: '100%'
|
||||
}}
|
||||
>
|
||||
{isProcessing ? '処理中...' : '続行'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isProcessing) {
|
||||
return (
|
||||
<div className="oauth-callback">
|
||||
<div className="oauth-processing">
|
||||
<div className="loading-spinner"></div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
// CSS styles (inline for simplicity)
|
||||
const styles = `
|
||||
.oauth-callback {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: linear-gradient(180deg, #f8f9fa 0%, #ffffff 100%);
|
||||
color: #333;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.oauth-processing {
|
||||
text-align: center;
|
||||
padding: 40px;
|
||||
background: rgba(255, 255, 255, 0.8);
|
||||
border-radius: 16px;
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid rgba(0, 0, 0, 0.1);
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.loading-spinner {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 3px solid rgba(0, 0, 0, 0.1);
|
||||
border-top: 3px solid #1185fe;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
`;
|
||||
|
||||
// Inject styles
|
||||
const styleSheet = document.createElement('style');
|
||||
styleSheet.type = 'text/css';
|
||||
styleSheet.innerText = styles;
|
||||
document.head.appendChild(styleSheet);
|
36
oauth/src/components/OAuthCallbackPage.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { OAuthCallback } from './OAuthCallback';
|
||||
|
||||
export const OAuthCallbackPage: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
}, []);
|
||||
|
||||
const handleSuccess = (did: string, handle: string) => {
|
||||
|
||||
// Add a small delay to ensure state is properly updated
|
||||
setTimeout(() => {
|
||||
navigate('/', { replace: true });
|
||||
}, 100);
|
||||
};
|
||||
|
||||
const handleError = (error: string) => {
|
||||
|
||||
// Add a small delay before redirect
|
||||
setTimeout(() => {
|
||||
navigate('/', { replace: true });
|
||||
}, 2000); // Give user time to see error
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h2>Processing OAuth callback...</h2>
|
||||
<OAuthCallback
|
||||
onSuccess={handleSuccess}
|
||||
onError={handleError}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
@@ -1,166 +0,0 @@
|
||||
import React, { useState } from 'react'
|
||||
import { atproto, collections } from '../api/atproto.js'
|
||||
import { env } from '../config/env.js'
|
||||
import { logger } from '../utils/logger.js'
|
||||
|
||||
const ProfileForm = ({ user, agent, apiConfig, onProfilePosted }) => {
|
||||
const [text, setText] = useState('')
|
||||
const [type, setType] = useState('user')
|
||||
const [handle, setHandle] = useState('')
|
||||
const [rkey, setRkey] = useState('')
|
||||
const [posting, setPosting] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!text.trim() || !handle.trim() || !rkey.trim()) {
|
||||
setError('すべてのフィールドを入力してください')
|
||||
return
|
||||
}
|
||||
|
||||
setPosting(true)
|
||||
setError('')
|
||||
|
||||
try {
|
||||
// Get handle information
|
||||
let authorData
|
||||
try {
|
||||
const handleDid = await atproto.getDid(apiConfig.pds, handle)
|
||||
// Use agent to get profile with authentication
|
||||
const profileResponse = await agent.api.app.bsky.actor.getProfile({ actor: handleDid })
|
||||
authorData = profileResponse.data
|
||||
} catch (err) {
|
||||
throw new Error('ハンドルが見つかりません')
|
||||
}
|
||||
|
||||
// Create record using the same pattern as CommentForm
|
||||
const timestamp = new Date().toISOString()
|
||||
const record = {
|
||||
repo: user.did,
|
||||
collection: env.collection,
|
||||
rkey: rkey,
|
||||
record: {
|
||||
$type: env.collection,
|
||||
text: text,
|
||||
type: 'profile',
|
||||
profileType: type, // admin or user
|
||||
author: {
|
||||
did: authorData.did,
|
||||
handle: authorData.handle,
|
||||
displayName: authorData.displayName || authorData.handle,
|
||||
avatar: authorData.avatar || null
|
||||
},
|
||||
createdAt: timestamp,
|
||||
post: {
|
||||
url: window.location.origin,
|
||||
date: timestamp,
|
||||
slug: '',
|
||||
tags: [],
|
||||
title: 'Profile',
|
||||
language: 'ja'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Post the record using agent like CommentForm
|
||||
await agent.api.com.atproto.repo.putRecord(record)
|
||||
|
||||
// Invalidate cache and refresh
|
||||
collections.invalidateCache(env.collection)
|
||||
|
||||
// Reset form
|
||||
setText('')
|
||||
setType('user')
|
||||
setHandle('')
|
||||
setRkey('')
|
||||
|
||||
if (onProfilePosted) {
|
||||
onProfilePosted()
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
logger.error('Failed to create profile:', err)
|
||||
setError(err.message || 'プロフィールの作成に失敗しました')
|
||||
} finally {
|
||||
setPosting(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="profile-form-container">
|
||||
<h3>プロフィール投稿</h3>
|
||||
|
||||
{error && (
|
||||
<div className="error-message">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="profile-form">
|
||||
<div className="form-row">
|
||||
<div className="form-group">
|
||||
<label htmlFor="handle">ハンドル</label>
|
||||
<input
|
||||
type="text"
|
||||
id="handle"
|
||||
value={handle}
|
||||
onChange={(e) => setHandle(e.target.value)}
|
||||
placeholder="例: syui.ai"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label htmlFor="rkey">Rkey</label>
|
||||
<input
|
||||
type="text"
|
||||
id="rkey"
|
||||
value={rkey}
|
||||
onChange={(e) => setRkey(e.target.value)}
|
||||
placeholder="例: syui"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="type">タイプ</label>
|
||||
<select
|
||||
id="type"
|
||||
value={type}
|
||||
onChange={(e) => setType(e.target.value)}
|
||||
>
|
||||
<option value="user">User</option>
|
||||
<option value="admin">Admin</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="text">プロフィールテキスト</label>
|
||||
<textarea
|
||||
id="text"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder="プロフィールの説明を入力してください"
|
||||
rows={4}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={posting || !text.trim() || !handle.trim() || !rkey.trim()}
|
||||
className="submit-btn"
|
||||
>
|
||||
{posting ? '投稿中...' : '投稿'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ProfileForm
|
@@ -1,136 +0,0 @@
|
||||
import React, { useState } from 'react'
|
||||
|
||||
// Helper function to get correct web URL based on avatar URL
|
||||
function getCorrectWebUrl(avatarUrl) {
|
||||
if (!avatarUrl) return 'https://bsky.app'
|
||||
|
||||
// If avatar is from bsky.app (main Bluesky), use bsky.app
|
||||
if (avatarUrl.includes('cdn.bsky.app') || avatarUrl.includes('bsky.app')) {
|
||||
return 'https://bsky.app'
|
||||
}
|
||||
|
||||
// If avatar is from syu.is, use web.syu.is
|
||||
if (avatarUrl.includes('bsky.syu.is') || avatarUrl.includes('syu.is')) {
|
||||
return 'https://syu.is'
|
||||
}
|
||||
|
||||
// Default to bsky.app
|
||||
return 'https://bsky.app'
|
||||
}
|
||||
|
||||
export default function ProfileRecordList({ profileRecords, apiConfig, user = null, agent = null, onRecordDeleted = null }) {
|
||||
const [expandedRecords, setExpandedRecords] = useState(new Set())
|
||||
|
||||
const toggleJsonView = (uri) => {
|
||||
const newExpanded = new Set(expandedRecords)
|
||||
if (newExpanded.has(uri)) {
|
||||
newExpanded.delete(uri)
|
||||
} else {
|
||||
newExpanded.add(uri)
|
||||
}
|
||||
setExpandedRecords(newExpanded)
|
||||
}
|
||||
if (!profileRecords || profileRecords.length === 0) {
|
||||
return (
|
||||
<section>
|
||||
<p>プロフィールがありません</p>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
const handleDelete = async (profile) => {
|
||||
if (!user || !agent || !profile.uri) return
|
||||
|
||||
const confirmed = window.confirm('このプロフィールを削除しますか?')
|
||||
if (!confirmed) return
|
||||
|
||||
try {
|
||||
const uriParts = profile.uri.split('/')
|
||||
await agent.api.com.atproto.repo.deleteRecord({
|
||||
repo: uriParts[2],
|
||||
collection: uriParts[3],
|
||||
rkey: uriParts[4]
|
||||
})
|
||||
|
||||
if (onRecordDeleted) {
|
||||
onRecordDeleted()
|
||||
}
|
||||
} catch (error) {
|
||||
alert(`削除に失敗しました: ${error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
const canDelete = (profile) => {
|
||||
if (!user || !agent || !profile.uri) return false
|
||||
|
||||
// Check if the record is in the current user's repository
|
||||
const recordRepoDid = profile.uri.split('/')[2]
|
||||
return recordRepoDid === user.did
|
||||
}
|
||||
|
||||
return (
|
||||
<section>
|
||||
{profileRecords.map((profile) => (
|
||||
<div key={profile.uri} className="chat-message comment-style">
|
||||
<div className="message-header">
|
||||
{profile.value.author?.avatar ? (
|
||||
<img
|
||||
src={profile.value.author.avatar}
|
||||
alt={`${profile.value.author.displayName || profile.value.author.handle} avatar`}
|
||||
className="avatar"
|
||||
/>
|
||||
) : (
|
||||
<div className="avatar">
|
||||
{(profile.value.author?.displayName || profile.value.author?.handle || '?').charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<div className="user-info">
|
||||
<div className="display-name">
|
||||
{profile.value.author?.displayName || profile.value.author?.handle}
|
||||
{profile.value.profileType === 'admin' && (
|
||||
<span className="admin-badge"> Admin</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="handle">
|
||||
<a
|
||||
href={`${getCorrectWebUrl(profile.value.author?.avatar)}/profile/${profile.value.author?.did}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="handle-link"
|
||||
>
|
||||
@{profile.value.author?.handle}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="record-actions">
|
||||
<button
|
||||
onClick={() => toggleJsonView(profile.uri)}
|
||||
className={`btn btn-sm ${expandedRecords.has(profile.uri) ? 'btn-outline' : 'btn-primary'}`}
|
||||
title="Show/Hide JSON"
|
||||
>
|
||||
{expandedRecords.has(profile.uri) ? 'hide' : 'json'}
|
||||
</button>
|
||||
{canDelete(profile) && (
|
||||
<button
|
||||
onClick={() => handleDelete(profile)}
|
||||
className="btn btn-danger btn-sm"
|
||||
title="Delete Profile"
|
||||
>
|
||||
delete
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{expandedRecords.has(profile.uri) && (
|
||||
<div className="json-display">
|
||||
<pre className="json-content">
|
||||
{JSON.stringify(profile, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
<div className="message-content">{profile.value.text}</div>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)
|
||||
}
|
@@ -1,283 +0,0 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import RecordList from './RecordList.jsx'
|
||||
import ChatRecordList from './ChatRecordList.jsx'
|
||||
import ProfileRecordList from './ProfileRecordList.jsx'
|
||||
import LoadingSkeleton from './LoadingSkeleton.jsx'
|
||||
import { logger } from '../utils/logger.js'
|
||||
|
||||
export default function RecordTabs({ langRecords, commentRecords, userComments, chatRecords, chatHasMore, onLoadMoreChat, userChatRecords, userChatLoading, baseRecords, apiConfig, pageContext, user = null, agent = null, onRecordDeleted = null }) {
|
||||
// Check if current page has matching chat records (AI posts always have chat records)
|
||||
const isAiPost = !pageContext.isTopPage && Array.isArray(chatRecords) && chatRecords.some(chatPair => {
|
||||
const recordUrl = chatPair.question?.value?.post?.url
|
||||
if (!recordUrl) return false
|
||||
|
||||
try {
|
||||
const recordRkey = new URL(recordUrl).pathname.split('/').pop()?.replace(/\.html$/, '')
|
||||
return recordRkey === pageContext.rkey
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
|
||||
const [activeTab, setActiveTab] = useState(isAiPost ? 'collection' : 'profiles')
|
||||
|
||||
// Monitor activeTab changes
|
||||
useEffect(() => {
|
||||
logger.log('RecordTabs: activeTab changed to', activeTab)
|
||||
}, [activeTab])
|
||||
|
||||
logger.log('RecordTabs: activeTab is', activeTab)
|
||||
logger.log('RecordTabs: commentRecords prop:', commentRecords?.length || 0, commentRecords)
|
||||
|
||||
// Filter records based on page context
|
||||
const filterRecords = (records, isProfile = false) => {
|
||||
// Ensure records is an array
|
||||
const recordsArray = Array.isArray(records) ? records : []
|
||||
|
||||
logger.log('filterRecords called with:', {
|
||||
recordsLength: recordsArray.length,
|
||||
isProfile,
|
||||
isTopPage: pageContext.isTopPage,
|
||||
pageRkey: pageContext.rkey,
|
||||
records: recordsArray
|
||||
})
|
||||
|
||||
if (pageContext.isTopPage) {
|
||||
// Top page: show latest 3 records
|
||||
const result = recordsArray.slice(0, 3)
|
||||
logger.log('filterRecords: Top page result:', result.length, result)
|
||||
return result
|
||||
} else {
|
||||
// Individual page: show records matching the URL
|
||||
const filtered = recordsArray.filter(record => {
|
||||
// Profile records should always be shown
|
||||
if (isProfile || record.value?.type === 'profile') {
|
||||
logger.log('filterRecords: Profile record included:', record.value?.type)
|
||||
return true
|
||||
}
|
||||
|
||||
const recordUrl = record.value?.post?.url
|
||||
if (!recordUrl) {
|
||||
logger.log('filterRecords: No recordUrl found for record:', record.value?.type)
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
const recordRkey = new URL(recordUrl).pathname.split('/').pop()?.replace(/\.html$/, '')
|
||||
const matches = recordRkey === pageContext.rkey
|
||||
logger.log('filterRecords: URL matching:', { recordRkey, pageRkey: pageContext.rkey, matches })
|
||||
return matches
|
||||
} catch {
|
||||
logger.log('filterRecords: URL parsing failed for:', recordUrl)
|
||||
return false
|
||||
}
|
||||
})
|
||||
logger.log('filterRecords: Individual page result:', filtered.length, filtered)
|
||||
return filtered
|
||||
}
|
||||
}
|
||||
|
||||
// Special filter for chat records (which are already processed into pairs)
|
||||
const filterChatRecords = (chatPairs) => {
|
||||
// Ensure chatPairs is an array
|
||||
const chatArray = Array.isArray(chatPairs) ? chatPairs : []
|
||||
|
||||
logger.log('filterChatRecords called:', {
|
||||
isTopPage: pageContext.isTopPage,
|
||||
rkey: pageContext.rkey,
|
||||
chatPairsLength: chatArray.length,
|
||||
chatPairsType: typeof chatPairs,
|
||||
isArray: Array.isArray(chatPairs)
|
||||
})
|
||||
|
||||
if (pageContext.isTopPage) {
|
||||
// Top page: show latest 3 pairs
|
||||
const result = chatArray.slice(0, 3)
|
||||
logger.log('Top page: returning', result.length, 'pairs')
|
||||
return result
|
||||
} else {
|
||||
// Individual page: show pairs matching the URL (compare path only, ignore domain)
|
||||
const filtered = chatArray.filter(chatPair => {
|
||||
const recordUrl = chatPair.question?.value?.post?.url
|
||||
if (!recordUrl) {
|
||||
logger.log('No recordUrl for chatPair:', chatPair)
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
// Extract path from URL and get the filename part
|
||||
const recordPath = new URL(recordUrl).pathname
|
||||
const recordRkey = recordPath.split('/').pop()?.replace(/\.html$/, '')
|
||||
|
||||
logger.log('Comparing:', { recordRkey, pageRkey: pageContext.rkey, recordUrl })
|
||||
|
||||
// Compare with current page rkey
|
||||
const matches = recordRkey === pageContext.rkey
|
||||
if (matches) {
|
||||
logger.log('Found matching chat pair!')
|
||||
}
|
||||
return matches
|
||||
} catch (error) {
|
||||
logger.log('Error processing recordUrl:', recordUrl, error)
|
||||
return false
|
||||
}
|
||||
})
|
||||
|
||||
logger.log('Individual page: returning', filtered.length, 'filtered pairs')
|
||||
return filtered
|
||||
}
|
||||
}
|
||||
|
||||
const filteredLangRecords = filterRecords(Array.isArray(langRecords) ? langRecords : [])
|
||||
|
||||
logger.log('RecordTabs: About to filter commentRecords:', commentRecords?.length || 0, commentRecords)
|
||||
const filteredCommentRecords = filterRecords(Array.isArray(commentRecords) ? commentRecords : [])
|
||||
logger.log('RecordTabs: After filtering commentRecords:', filteredCommentRecords.length, filteredCommentRecords)
|
||||
|
||||
const filteredUserComments = filterRecords(Array.isArray(userComments) ? userComments : [])
|
||||
const filteredChatRecords = filterChatRecords(Array.isArray(chatRecords) ? chatRecords : [])
|
||||
const filteredBaseRecords = filterRecords(Array.isArray(baseRecords) ? baseRecords : [])
|
||||
|
||||
logger.log('RecordTabs: filtered results:')
|
||||
logger.log(' - filteredCommentRecords:', filteredCommentRecords.length, filteredCommentRecords)
|
||||
logger.log(' - filteredLangRecords:', filteredLangRecords.length)
|
||||
logger.log(' - filteredUserComments:', filteredUserComments.length)
|
||||
logger.log(' - pageContext:', pageContext)
|
||||
logger.log('RecordTabs: TAB RENDER VALUES:')
|
||||
logger.log(' - filteredCommentRecords.length for tab:', filteredCommentRecords.length)
|
||||
logger.log(' - commentRecords input:', commentRecords?.length || 0)
|
||||
|
||||
// Filter profile records from baseRecords
|
||||
const profileRecords = (Array.isArray(baseRecords) ? baseRecords : []).filter(record => record.value?.type === 'profile')
|
||||
const sortedProfileRecords = profileRecords.sort((a, b) => {
|
||||
if (a.value.profileType === 'admin' && b.value.profileType !== 'admin') return -1
|
||||
if (a.value.profileType !== 'admin' && b.value.profileType === 'admin') return 1
|
||||
return 0
|
||||
})
|
||||
const filteredProfileRecords = filterRecords(sortedProfileRecords, true)
|
||||
|
||||
return (
|
||||
<div className="record-tabs">
|
||||
{!isAiPost && (
|
||||
<div className="tab-header">
|
||||
<button
|
||||
className={`tab-btn ${activeTab === 'profiles' ? 'active' : ''}`}
|
||||
onClick={() => {
|
||||
logger.log('RecordTabs: Profiles tab clicked')
|
||||
setActiveTab('profiles')
|
||||
}}
|
||||
>
|
||||
about ({filteredProfileRecords.length})
|
||||
</button>
|
||||
<button
|
||||
className={`tab-btn ${activeTab === 'collection' ? 'active' : ''}`}
|
||||
onClick={() => setActiveTab('collection')}
|
||||
>
|
||||
chat ({filteredChatRecords.length > 0 ? filteredChatRecords.length : (userChatRecords?.length || 0)})
|
||||
</button>
|
||||
<button
|
||||
className={`tab-btn ${activeTab === 'comment' ? 'active' : ''}`}
|
||||
onClick={() => {
|
||||
logger.log('RecordTabs: feedback tab clicked, setting activeTab to comment')
|
||||
setActiveTab('comment')
|
||||
}}
|
||||
>
|
||||
feedback ({(() => {
|
||||
logger.log('RecordTabs: feedback tab render - filteredCommentRecords.length:', filteredCommentRecords.length)
|
||||
return filteredCommentRecords.length
|
||||
})()})
|
||||
</button>
|
||||
<button
|
||||
className={`tab-btn ${activeTab === 'users' ? 'active' : ''}`}
|
||||
onClick={() => setActiveTab('users')}
|
||||
>
|
||||
comment ({filteredUserComments.length})
|
||||
</button>
|
||||
<button
|
||||
className={`tab-btn ${activeTab === 'lang' ? 'active' : ''}`}
|
||||
onClick={() => setActiveTab('lang')}
|
||||
>
|
||||
en ({filteredLangRecords.length})
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="tab-content">
|
||||
{activeTab === 'lang' && !isAiPost && (
|
||||
!langRecords ? (
|
||||
<LoadingSkeleton count={3} showTitle={true} />
|
||||
) : (
|
||||
<RecordList
|
||||
title=""
|
||||
records={filteredLangRecords}
|
||||
apiConfig={apiConfig}
|
||||
user={user}
|
||||
agent={agent}
|
||||
onRecordDeleted={onRecordDeleted}
|
||||
showTitle={false}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
{activeTab === 'comment' && !isAiPost && (
|
||||
!commentRecords ? (
|
||||
<LoadingSkeleton count={3} showTitle={true} />
|
||||
) : (
|
||||
<RecordList
|
||||
title=""
|
||||
records={filteredCommentRecords}
|
||||
apiConfig={apiConfig}
|
||||
user={user}
|
||||
agent={agent}
|
||||
onRecordDeleted={onRecordDeleted}
|
||||
showTitle={false}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
{activeTab === 'collection' && (
|
||||
userChatLoading ? (
|
||||
<LoadingSkeleton count={2} showTitle={true} />
|
||||
) : (
|
||||
<ChatRecordList
|
||||
chatPairs={filteredChatRecords.length > 0 ? filteredChatRecords : (Array.isArray(userChatRecords) ? userChatRecords : [])}
|
||||
chatHasMore={filteredChatRecords.length > 0 ? chatHasMore : false}
|
||||
onLoadMoreChat={filteredChatRecords.length > 0 ? onLoadMoreChat : null}
|
||||
apiConfig={apiConfig}
|
||||
user={user}
|
||||
agent={agent}
|
||||
onRecordDeleted={onRecordDeleted}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
{activeTab === 'users' && !isAiPost && (
|
||||
!userComments ? (
|
||||
<LoadingSkeleton count={3} showTitle={true} />
|
||||
) : (
|
||||
<RecordList
|
||||
title=""
|
||||
records={filteredUserComments}
|
||||
apiConfig={apiConfig}
|
||||
user={user}
|
||||
agent={agent}
|
||||
onRecordDeleted={onRecordDeleted}
|
||||
showTitle={false}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
{activeTab === 'profiles' && !isAiPost && (
|
||||
!baseRecords ? (
|
||||
<LoadingSkeleton count={3} showTitle={true} />
|
||||
) : (
|
||||
<ProfileRecordList
|
||||
profileRecords={filteredProfileRecords}
|
||||
apiConfig={apiConfig}
|
||||
user={user}
|
||||
agent={agent}
|
||||
onRecordDeleted={onRecordDeleted}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
158
oauth/src/config/app.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
// Application configuration
|
||||
export interface AppConfig {
|
||||
adminDid: string;
|
||||
adminHandle: string;
|
||||
aiDid: string;
|
||||
aiHandle: string;
|
||||
aiDisplayName: string;
|
||||
aiAvatar: string;
|
||||
aiDescription: string;
|
||||
collections: {
|
||||
base: string; // Base collection like "ai.syui.log"
|
||||
};
|
||||
host: string;
|
||||
rkey?: string; // Current post rkey if on post page
|
||||
aiEnabled: boolean;
|
||||
aiAskAi: boolean;
|
||||
aiProvider: string;
|
||||
aiModel: string;
|
||||
aiHost: string;
|
||||
aiSystemPrompt: string;
|
||||
allowedHandles: string[]; // Handles allowed for OAuth authentication
|
||||
atprotoPds: string; // Configured PDS for admin/ai handles
|
||||
// Legacy - prefer per-user PDS detection
|
||||
bskyPublicApi: string;
|
||||
atprotoApi: string;
|
||||
}
|
||||
|
||||
// Collection name builders (similar to Rust implementation)
|
||||
export function getCollectionNames(base: string) {
|
||||
if (!base) {
|
||||
// Fallback to default
|
||||
base = 'ai.syui.log';
|
||||
}
|
||||
|
||||
const collections = {
|
||||
comment: base,
|
||||
user: `${base}.user`,
|
||||
chat: `${base}.chat`,
|
||||
chatLang: `${base}.chat.lang`,
|
||||
chatComment: `${base}.chat.comment`,
|
||||
};
|
||||
|
||||
return collections;
|
||||
}
|
||||
|
||||
// Generate collection names from host
|
||||
// Format: ${reg}.${name}.${sub}
|
||||
// Example: log.syui.ai -> ai.syui.log
|
||||
function generateBaseCollectionFromHost(host: string): string {
|
||||
try {
|
||||
// Remove protocol if present
|
||||
const cleanHost = host.replace(/^https?:\/\//, '');
|
||||
|
||||
// Split host into parts
|
||||
const parts = cleanHost.split('.');
|
||||
|
||||
if (parts.length < 2) {
|
||||
throw new Error('Invalid host format');
|
||||
}
|
||||
|
||||
// Reverse the parts for collection naming
|
||||
// log.syui.ai -> ai.syui.log
|
||||
const reversedParts = parts.reverse();
|
||||
const result = reversedParts.join('.');
|
||||
return result;
|
||||
} catch (error) {
|
||||
// Fallback to default
|
||||
return 'ai.syui.log';
|
||||
}
|
||||
}
|
||||
|
||||
// Extract rkey from current URL
|
||||
// /posts/xxx -> xxx (remove .html if present)
|
||||
function extractRkeyFromUrl(): string | undefined {
|
||||
const pathname = window.location.pathname;
|
||||
const match = pathname.match(/\/posts\/([^/]+)\/?$/);
|
||||
if (match) {
|
||||
// Remove .html extension if present
|
||||
return match[1].replace(/\.html$/, '');
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Get application configuration from environment variables
|
||||
export function getAppConfig(): AppConfig {
|
||||
const host = import.meta.env.VITE_APP_HOST || 'https://log.syui.ai';
|
||||
const adminHandle = import.meta.env.VITE_ADMIN_HANDLE || 'ai.syui.ai';
|
||||
const aiHandle = import.meta.env.VITE_AI_HANDLE || 'ai.syui.ai';
|
||||
|
||||
// DIDsはハンドルから実行時に解決される(フォールバック用のみ保持)
|
||||
const adminDid = import.meta.env.VITE_ADMIN_DID || 'did:plc:uqzpqmrjnptsxezjx4xuh2mn';
|
||||
const aiDid = import.meta.env.VITE_AI_DID || 'did:plc:6qyecktefllvenje24fcxnie';
|
||||
const aiDisplayName = import.meta.env.VITE_AI_DISPLAY_NAME || 'ai';
|
||||
const aiAvatar = import.meta.env.VITE_AI_AVATAR || '';
|
||||
const aiDescription = import.meta.env.VITE_AI_DESCRIPTION || '';
|
||||
|
||||
// Priority: Environment variables > Auto-generated from host
|
||||
const autoGeneratedBase = generateBaseCollectionFromHost(host);
|
||||
let baseCollection = import.meta.env.VITE_OAUTH_COLLECTION || autoGeneratedBase;
|
||||
|
||||
// Ensure base collection is never undefined
|
||||
if (!baseCollection) {
|
||||
baseCollection = 'ai.syui.log';
|
||||
}
|
||||
|
||||
const collections = {
|
||||
base: baseCollection,
|
||||
};
|
||||
|
||||
const rkey = extractRkeyFromUrl();
|
||||
|
||||
// AI configuration
|
||||
const aiEnabled = import.meta.env.VITE_AI_ENABLED === 'true';
|
||||
const aiAskAi = import.meta.env.VITE_AI_ASK_AI === 'true';
|
||||
const aiProvider = import.meta.env.VITE_AI_PROVIDER || 'ollama';
|
||||
const aiModel = import.meta.env.VITE_AI_MODEL || 'gemma3:4b';
|
||||
const aiHost = import.meta.env.VITE_AI_HOST || 'https://ollama.syui.ai';
|
||||
const aiSystemPrompt = import.meta.env.VITE_AI_SYSTEM_PROMPT || 'You are a helpful AI assistant trained on this blog\'s content.';
|
||||
const atprotoPds = import.meta.env.VITE_ATPROTO_PDS || 'syu.is';
|
||||
const bskyPublicApi = import.meta.env.VITE_BSKY_PUBLIC_API || 'https://public.api.bsky.app';
|
||||
const atprotoApi = import.meta.env.VITE_ATPROTO_API || 'https://bsky.social';
|
||||
|
||||
// Parse allowed handles list
|
||||
const allowedHandlesStr = import.meta.env.VITE_ATPROTO_HANDLE_LIST || '[]';
|
||||
let allowedHandles: string[] = [];
|
||||
try {
|
||||
allowedHandles = JSON.parse(allowedHandlesStr);
|
||||
} catch {
|
||||
// If parsing fails, allow all handles (empty array means no restriction)
|
||||
allowedHandles = [];
|
||||
}
|
||||
|
||||
return {
|
||||
adminDid,
|
||||
adminHandle,
|
||||
aiDid,
|
||||
aiHandle,
|
||||
aiDisplayName,
|
||||
aiAvatar,
|
||||
aiDescription,
|
||||
collections,
|
||||
host,
|
||||
rkey,
|
||||
aiEnabled,
|
||||
aiAskAi,
|
||||
aiProvider,
|
||||
aiModel,
|
||||
aiHost,
|
||||
aiSystemPrompt,
|
||||
allowedHandles,
|
||||
atprotoPds,
|
||||
bskyPublicApi,
|
||||
atprotoApi
|
||||
};
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
export const appConfig = getAppConfig();
|
@@ -1,195 +0,0 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { atproto, collections } from '../api/atproto.js'
|
||||
import { getApiConfig } from '../utils/pds.js'
|
||||
import { env } from '../config/env.js'
|
||||
import { getErrorMessage } from '../utils/errorHandler.js'
|
||||
import { logger } from '../utils/logger.js'
|
||||
|
||||
export function useAdminData() {
|
||||
const [adminData, setAdminData] = useState({
|
||||
did: '',
|
||||
profile: null,
|
||||
records: [],
|
||||
apiConfig: null
|
||||
})
|
||||
const [langRecords, setLangRecords] = useState([])
|
||||
const [commentRecords, setCommentRecords] = useState([])
|
||||
const [chatRecords, setChatRecords] = useState([])
|
||||
const [chatCursor, setChatCursor] = useState(null)
|
||||
const [chatHasMore, setChatHasMore] = useState(true)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
loadAdminData()
|
||||
}, [])
|
||||
|
||||
const loadAdminData = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
const apiConfig = getApiConfig(`https://${env.pds}`)
|
||||
const did = await atproto.getDid(env.pds, env.admin)
|
||||
const profile = await atproto.getProfile(apiConfig.bsky, did)
|
||||
|
||||
// Load all data in parallel with error handling
|
||||
logger.log('useAdminData: Starting API calls...')
|
||||
const [records, lang, comment, chatResult] = await Promise.all([
|
||||
collections.getBase(apiConfig.pds, did, env.collection).catch(err => {
|
||||
logger.error('getBase error:', err)
|
||||
throw err
|
||||
}),
|
||||
collections.getLang(apiConfig.pds, did, env.collection).catch(err => {
|
||||
logger.error('getLang error:', err)
|
||||
throw err
|
||||
}),
|
||||
collections.getComment(apiConfig.pds, did, env.collection).catch(err => {
|
||||
logger.error('getComment error:', err)
|
||||
throw err
|
||||
}),
|
||||
collections.getChat(apiConfig.pds, did, env.collection, 10).catch(err => {
|
||||
logger.error('getChat error:', err)
|
||||
throw err
|
||||
})
|
||||
])
|
||||
logger.log('useAdminData: API calls completed successfully')
|
||||
|
||||
const chat = chatResult.records || chatResult
|
||||
const cursor = chatResult.cursor || null
|
||||
setChatCursor(cursor)
|
||||
setChatHasMore(!!cursor)
|
||||
|
||||
logger.log('useAdminData: chatResult structure:', chatResult)
|
||||
logger.log('useAdminData: chat variable type:', typeof chat, 'isArray:', Array.isArray(chat))
|
||||
|
||||
// Process chat records into question-answer pairs
|
||||
const chatPairs = []
|
||||
const recordMap = new Map()
|
||||
|
||||
// Ensure chat is an array
|
||||
const chatArray = Array.isArray(chat) ? chat : []
|
||||
|
||||
// First pass: organize records by base rkey
|
||||
chatArray.forEach(record => {
|
||||
const rkey = record.uri.split('/').pop()
|
||||
const baseRkey = rkey.replace('-answer', '')
|
||||
|
||||
if (!recordMap.has(baseRkey)) {
|
||||
recordMap.set(baseRkey, { question: null, answer: null })
|
||||
}
|
||||
|
||||
if (record.value.type === 'question') {
|
||||
recordMap.get(baseRkey).question = record
|
||||
} else if (record.value.type === 'answer') {
|
||||
recordMap.get(baseRkey).answer = record
|
||||
}
|
||||
})
|
||||
|
||||
// Second pass: create chat pairs
|
||||
recordMap.forEach((pair, rkey) => {
|
||||
if (pair.question) {
|
||||
chatPairs.push({
|
||||
rkey,
|
||||
question: pair.question,
|
||||
answer: pair.answer,
|
||||
createdAt: pair.question.value.createdAt
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// Sort by creation time (newest first)
|
||||
chatPairs.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
|
||||
|
||||
logger.log('useAdminData: raw chat records:', chat.length)
|
||||
logger.log('useAdminData: processed chat pairs:', chatPairs.length, chatPairs)
|
||||
logger.log('useAdminData: setting state data:')
|
||||
logger.log(' - records:', records.length)
|
||||
logger.log(' - langRecords:', lang.length)
|
||||
logger.log(' - commentRecords:', comment.length, comment)
|
||||
logger.log(' - chatRecords:', chatPairs.length)
|
||||
|
||||
setAdminData({ did, profile, records, apiConfig })
|
||||
setLangRecords(lang)
|
||||
setCommentRecords(comment)
|
||||
setChatRecords(chatPairs)
|
||||
} catch (err) {
|
||||
// Log the actual error for debugging
|
||||
logger.error('useAdminData: Error in loadAdminData:', err)
|
||||
setError('silent_failure')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadMoreChat = async () => {
|
||||
if (!chatCursor || !chatHasMore) return
|
||||
|
||||
try {
|
||||
const apiConfig = getApiConfig(`https://${env.pds}`)
|
||||
const did = await atproto.getDid(env.pds, env.admin)
|
||||
const chatResult = await collections.getChat(apiConfig.pds, did, env.collection, 10, chatCursor)
|
||||
|
||||
const newChatRecords = chatResult.records || chatResult
|
||||
const newCursor = chatResult.cursor || null
|
||||
|
||||
// Process new chat records into question-answer pairs
|
||||
const newChatPairs = []
|
||||
const recordMap = new Map()
|
||||
|
||||
// Ensure newChatRecords is an array
|
||||
const newChatArray = Array.isArray(newChatRecords) ? newChatRecords : []
|
||||
|
||||
// First pass: organize records by base rkey
|
||||
newChatArray.forEach(record => {
|
||||
const rkey = record.uri.split('/').pop()
|
||||
const baseRkey = rkey.replace('-answer', '')
|
||||
|
||||
if (!recordMap.has(baseRkey)) {
|
||||
recordMap.set(baseRkey, { question: null, answer: null })
|
||||
}
|
||||
|
||||
if (record.value.type === 'question') {
|
||||
recordMap.get(baseRkey).question = record
|
||||
} else if (record.value.type === 'answer') {
|
||||
recordMap.get(baseRkey).answer = record
|
||||
}
|
||||
})
|
||||
|
||||
// Second pass: create chat pairs
|
||||
recordMap.forEach((pair, rkey) => {
|
||||
if (pair.question) {
|
||||
newChatPairs.push({
|
||||
rkey,
|
||||
question: pair.question,
|
||||
answer: pair.answer,
|
||||
createdAt: pair.question.value.createdAt
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// Sort new pairs by creation time (newest first)
|
||||
newChatPairs.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
|
||||
|
||||
// Append to existing chat records
|
||||
setChatRecords(prev => [...prev, ...newChatPairs])
|
||||
setChatCursor(newCursor)
|
||||
setChatHasMore(!!newCursor)
|
||||
|
||||
} catch (err) {
|
||||
// Silently fail - no error logging
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
adminData,
|
||||
langRecords,
|
||||
commentRecords,
|
||||
chatRecords,
|
||||
chatHasMore,
|
||||
loading,
|
||||
error,
|
||||
refresh: loadAdminData,
|
||||
loadMoreChat
|
||||
}
|
||||
}
|
@@ -1,81 +0,0 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { OAuthService } from '../services/oauth.js'
|
||||
import { logger } from '../utils/logger.js'
|
||||
|
||||
const oauthService = new OAuthService()
|
||||
|
||||
export function useAuth() {
|
||||
const [user, setUser] = useState(null)
|
||||
const [agent, setAgent] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
initAuth()
|
||||
}, [])
|
||||
|
||||
const initAuth = async () => {
|
||||
try {
|
||||
const authResult = await oauthService.checkAuth()
|
||||
if (authResult) {
|
||||
setUser(authResult.user)
|
||||
setAgent(authResult.agent)
|
||||
|
||||
// If we're on callback page and authentication succeeded, notify parent
|
||||
if (window.location.pathname === '/oauth/callback') {
|
||||
logger.log('OAuth callback completed, notifying parent window')
|
||||
|
||||
// Get referrer or use stored return URL
|
||||
const returnUrl = sessionStorage.getItem('oauth_return_url') ||
|
||||
document.referrer ||
|
||||
window.location.origin
|
||||
|
||||
sessionStorage.removeItem('oauth_return_url')
|
||||
|
||||
// Notify parent window if in iframe, otherwise redirect directly
|
||||
if (window.parent !== window) {
|
||||
window.parent.postMessage({
|
||||
type: 'oauth_success',
|
||||
returnUrl: returnUrl,
|
||||
user: authResult.user
|
||||
}, '*')
|
||||
} else {
|
||||
// Set flag to skip loading screen after redirect
|
||||
sessionStorage.setItem('oauth_just_completed', 'true')
|
||||
// Direct redirect
|
||||
setTimeout(() => {
|
||||
window.location.href = returnUrl
|
||||
}, 1000)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Auth initialization failed:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const login = async (handle) => {
|
||||
// Store current page URL for post-auth redirect
|
||||
if (window.location.pathname !== '/oauth/callback') {
|
||||
sessionStorage.setItem('oauth_return_url', window.location.href)
|
||||
}
|
||||
|
||||
await oauthService.login(handle)
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
await oauthService.logout()
|
||||
setUser(null)
|
||||
setAgent(null)
|
||||
}
|
||||
|
||||
return {
|
||||
user,
|
||||
agent,
|
||||
loading,
|
||||
login,
|
||||
logout,
|
||||
isAuthenticated: !!user
|
||||
}
|
||||
}
|
@@ -1,10 +0,0 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import App from './App'
|
||||
import './App.css'
|
||||
|
||||
// Only mount the OAuth app if the target element exists
|
||||
const targetElement = document.getElementById('comment-atproto')
|
||||
if (targetElement) {
|
||||
ReactDOM.createRoot(targetElement).render(<App />)
|
||||
}
|
28
oauth/src/main.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { BrowserRouter, Routes, Route } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import { OAuthCallbackPage } from './components/OAuthCallbackPage'
|
||||
import { CardList } from './components/CardList'
|
||||
import { OAuthEndpointHandler } from './utils/oauth-endpoints'
|
||||
|
||||
// Initialize OAuth endpoint handlers for dynamic client metadata and JWKS
|
||||
// DISABLED: This may interfere with BrowserOAuthClient
|
||||
// OAuthEndpointHandler.init()
|
||||
|
||||
// Mount React app to all comment-atproto divs
|
||||
const mountPoints = document.querySelectorAll('#comment-atproto');
|
||||
|
||||
mountPoints.forEach((mountPoint, index) => {
|
||||
ReactDOM.createRoot(mountPoint as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/oauth/callback" element={<OAuthCallbackPage />} />
|
||||
<Route path="/list" element={<CardList />} />
|
||||
<Route path="*" element={<App />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
@@ -1,214 +0,0 @@
|
||||
/**
|
||||
* AI Provider Abstract Interface
|
||||
* Supports multiple AI backends (Ollama, Claude, etc.)
|
||||
*/
|
||||
|
||||
export class AIProvider {
|
||||
constructor(config) {
|
||||
this.config = config
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a question to the AI and get a response
|
||||
* @param {string} question - User's question
|
||||
* @param {Object} context - Additional context (user info, etc.)
|
||||
* @returns {Promise<{answer: string}>}
|
||||
*/
|
||||
async ask(question, context = {}) {
|
||||
throw new Error('ask() method must be implemented by subclass')
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the provider is available
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async healthCheck() {
|
||||
throw new Error('healthCheck() method must be implemented by subclass')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ollama Provider Implementation
|
||||
*/
|
||||
export class OllamaProvider extends AIProvider {
|
||||
constructor(config) {
|
||||
super(config)
|
||||
this.host = config.host || 'https://ollama.syui.ai'
|
||||
this.model = config.model || 'gemma3:1b'
|
||||
this.systemPrompt = config.systemPrompt || ''
|
||||
}
|
||||
|
||||
async ask(question, context = {}) {
|
||||
// Build enhanced prompt with user context
|
||||
const userInfo = context.userProfile
|
||||
? `相手の名前は${context.userProfile.displayName || context.userProfile.handle}です。`
|
||||
: ''
|
||||
const enhancedSystemPrompt = `${this.systemPrompt} ${userInfo}`
|
||||
|
||||
const prompt = `${enhancedSystemPrompt}
|
||||
|
||||
Question: ${question}
|
||||
|
||||
Answer:`
|
||||
|
||||
const controller = new AbortController()
|
||||
const timeoutId = setTimeout(() => controller.abort(), 30000)
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.host}/api/generate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Origin': 'https://syui.ai',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: this.model,
|
||||
prompt: prompt,
|
||||
stream: false,
|
||||
options: {
|
||||
temperature: 0.9,
|
||||
top_p: 0.9,
|
||||
num_predict: 200,
|
||||
repeat_penalty: 1.1,
|
||||
}
|
||||
}),
|
||||
signal: controller.signal
|
||||
})
|
||||
|
||||
clearTimeout(timeoutId)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Ollama API error: ${response.status}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return { answer: data.response || 'エラーが発生しました' }
|
||||
|
||||
} catch (error) {
|
||||
clearTimeout(timeoutId)
|
||||
if (error.name === 'AbortError') {
|
||||
throw new Error('Request timeout')
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async healthCheck() {
|
||||
try {
|
||||
const response = await fetch(`${this.host}/api/tags`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Origin': 'https://syui.ai',
|
||||
}
|
||||
})
|
||||
return response.ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude MCP Server Provider Implementation
|
||||
*/
|
||||
export class ClaudeMCPProvider extends AIProvider {
|
||||
constructor(config) {
|
||||
super(config)
|
||||
this.endpoint = config.endpoint || 'https://your-server.com/api/claude-mcp'
|
||||
this.apiKey = config.apiKey // Server-side auth token
|
||||
this.systemPrompt = config.systemPrompt || ''
|
||||
}
|
||||
|
||||
async ask(question, context = {}) {
|
||||
const userInfo = context.userProfile
|
||||
? `相手の名前は${context.userProfile.displayName || context.userProfile.handle}です。`
|
||||
: ''
|
||||
const enhancedSystemPrompt = `${this.systemPrompt} ${userInfo}`
|
||||
|
||||
const controller = new AbortController()
|
||||
const timeoutId = setTimeout(() => controller.abort(), 45000) // Longer timeout for Claude
|
||||
|
||||
try {
|
||||
const response = await fetch(this.endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${this.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
question: question,
|
||||
systemPrompt: enhancedSystemPrompt,
|
||||
context: context
|
||||
}),
|
||||
signal: controller.signal
|
||||
})
|
||||
|
||||
clearTimeout(timeoutId)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Claude MCP error: ${response.status}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return { answer: data.answer || 'エラーが発生しました' }
|
||||
|
||||
} catch (error) {
|
||||
clearTimeout(timeoutId)
|
||||
if (error.name === 'AbortError') {
|
||||
throw new Error('Request timeout')
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async healthCheck() {
|
||||
try {
|
||||
const response = await fetch(`${this.endpoint}/health`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${this.apiKey}`,
|
||||
}
|
||||
})
|
||||
return response.ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AI Provider Factory
|
||||
*/
|
||||
export class AIProviderFactory {
|
||||
static create(provider, config) {
|
||||
switch (provider) {
|
||||
case 'ollama':
|
||||
return new OllamaProvider(config)
|
||||
case 'claude-mcp':
|
||||
return new ClaudeMCPProvider(config)
|
||||
default:
|
||||
throw new Error(`Unknown AI provider: ${provider}`)
|
||||
}
|
||||
}
|
||||
|
||||
static createFromEnv() {
|
||||
const provider = import.meta.env.VITE_AI_PROVIDER || 'ollama'
|
||||
|
||||
const config = {
|
||||
systemPrompt: import.meta.env.VITE_AI_SYSTEM_PROMPT || '',
|
||||
}
|
||||
|
||||
switch (provider) {
|
||||
case 'ollama':
|
||||
config.host = import.meta.env.VITE_AI_HOST
|
||||
config.model = import.meta.env.VITE_AI_MODEL
|
||||
break
|
||||
case 'claude-mcp':
|
||||
config.endpoint = import.meta.env.VITE_CLAUDE_MCP_ENDPOINT
|
||||
config.apiKey = import.meta.env.VITE_CLAUDE_MCP_API_KEY
|
||||
break
|
||||
}
|
||||
|
||||
return AIProviderFactory.create(provider, config)
|
||||
}
|
||||
}
|
105
oauth/src/services/api.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import axios from 'axios';
|
||||
import { CardDrawResult } from '../types/card';
|
||||
|
||||
// ai.card 直接APIアクセス(メイン)
|
||||
const API_HOST = import.meta.env.VITE_API_HOST || '';
|
||||
const API_BASE = import.meta.env.PROD && API_HOST ? `${API_HOST}/api/v1` : '/api/v1';
|
||||
|
||||
// ai.gpt MCP統合(オプション機能)
|
||||
const AI_GPT_BASE = import.meta.env.VITE_ENABLE_AI_FEATURES === 'true'
|
||||
? (import.meta.env.PROD ? '/api/ai-gpt' : 'http://localhost:8001')
|
||||
: null;
|
||||
|
||||
const cardApi_internal = axios.create({
|
||||
baseURL: API_BASE,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
const aiGptApi = AI_GPT_BASE ? axios.create({
|
||||
baseURL: AI_GPT_BASE,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
}) : null;
|
||||
|
||||
// ai.cardの直接API(基本機能)
|
||||
export const cardApi = {
|
||||
drawCard: async (userDid: string, isPaid: boolean = false): Promise<CardDrawResult> => {
|
||||
const response = await cardApi_internal.post('/cards/draw', {
|
||||
user_did: userDid,
|
||||
is_paid: isPaid,
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getUserCards: async (userDid: string) => {
|
||||
const response = await cardApi_internal.get(`/cards/user/${userDid}`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getCardDetails: async (cardId: number) => {
|
||||
const response = await cardApi_internal.get(`/cards/${cardId}`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getUniqueCards: async () => {
|
||||
const response = await cardApi_internal.get('/cards/unique');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getGachaStats: async () => {
|
||||
const response = await cardApi_internal.get('/cards/stats');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
// システム状態確認
|
||||
getSystemStatus: async () => {
|
||||
const response = await cardApi_internal.get('/health');
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
|
||||
// ai.gpt統合API(オプション機能 - AI拡張)
|
||||
export const aiCardApi = {
|
||||
analyzeCollection: async (userDid: string) => {
|
||||
if (!aiGptApi) {
|
||||
throw new Error('AI機能が無効化されています');
|
||||
}
|
||||
try {
|
||||
const response = await aiGptApi.get('/card_analyze_collection', {
|
||||
params: { did: userDid }
|
||||
});
|
||||
return response.data.data;
|
||||
} catch (error) {
|
||||
throw new Error('AI分析機能を利用するにはai.gptサーバーが必要です');
|
||||
}
|
||||
},
|
||||
|
||||
getEnhancedStats: async () => {
|
||||
if (!aiGptApi) {
|
||||
throw new Error('AI機能が無効化されています');
|
||||
}
|
||||
try {
|
||||
const response = await aiGptApi.get('/card_get_gacha_stats');
|
||||
return response.data.data;
|
||||
} catch (error) {
|
||||
throw new Error('AI統計機能を利用するにはai.gptサーバーが必要です');
|
||||
}
|
||||
},
|
||||
|
||||
// AI機能が利用可能かチェック
|
||||
isAIAvailable: async (): Promise<boolean> => {
|
||||
if (!aiGptApi || import.meta.env.VITE_ENABLE_AI_FEATURES !== 'true') {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await aiGptApi.get('/health');
|
||||
return true;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
};
|
571
oauth/src/services/atproto-oauth.ts
Normal file
@@ -0,0 +1,571 @@
|
||||
import { BrowserOAuthClient } from '@atproto/oauth-client-browser';
|
||||
import { Agent } from '@atproto/api';
|
||||
|
||||
interface AtprotoSession {
|
||||
did: string;
|
||||
handle: string;
|
||||
accessJwt: string;
|
||||
refreshJwt: string;
|
||||
email?: string;
|
||||
emailConfirmed?: boolean;
|
||||
}
|
||||
|
||||
class AtprotoOAuthService {
|
||||
private oauthClient: BrowserOAuthClient | null = null;
|
||||
private oauthClientSyuIs: BrowserOAuthClient | null = null;
|
||||
private agent: Agent | null = null;
|
||||
private initializePromise: Promise<void> | null = null;
|
||||
|
||||
constructor() {
|
||||
// Don't initialize immediately, wait for first use
|
||||
}
|
||||
|
||||
private async initialize(): Promise<void> {
|
||||
// Prevent multiple initializations
|
||||
if (this.initializePromise) {
|
||||
return this.initializePromise;
|
||||
}
|
||||
|
||||
this.initializePromise = this._doInitialize();
|
||||
return this.initializePromise;
|
||||
}
|
||||
|
||||
private async _doInitialize(): Promise<void> {
|
||||
try {
|
||||
// Generate client ID based on current origin
|
||||
const clientId = this.getClientId();
|
||||
|
||||
// Initialize both OAuth clients
|
||||
this.oauthClient = await BrowserOAuthClient.load({
|
||||
clientId: clientId,
|
||||
handleResolver: 'https://bsky.social',
|
||||
plcDirectoryUrl: 'https://plc.directory',
|
||||
});
|
||||
|
||||
this.oauthClientSyuIs = await BrowserOAuthClient.load({
|
||||
clientId: clientId,
|
||||
handleResolver: 'https://syu.is',
|
||||
plcDirectoryUrl: 'https://plc.syu.is',
|
||||
});
|
||||
|
||||
// Try to restore existing session from either client
|
||||
let result = await this.oauthClient.init();
|
||||
if (!result?.session) {
|
||||
result = await this.oauthClientSyuIs.init();
|
||||
}
|
||||
if (result?.session) {
|
||||
|
||||
// Create Agent instance with proper configuration
|
||||
|
||||
|
||||
// Delete the old agent initialization code - we'll create it properly below
|
||||
|
||||
// Set the session after creating the agent
|
||||
// The session object from BrowserOAuthClient appears to be a special object
|
||||
|
||||
|
||||
|
||||
|
||||
// Try to iterate over the session object
|
||||
if (result.session) {
|
||||
|
||||
for (const key in result.session) {
|
||||
|
||||
}
|
||||
|
||||
// Check if session has methods
|
||||
const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(result.session));
|
||||
|
||||
}
|
||||
|
||||
// BrowserOAuthClient might return a Session object that needs to be used with the agent
|
||||
// Let's try to use the session object directly with the agent
|
||||
if (result.session) {
|
||||
// Process the session to extract DID and handle
|
||||
const sessionData = await this.processSession(result.session);
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
|
||||
this.initializePromise = null; // Reset on error to allow retry
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async processSession(session: any): Promise<{ did: string; handle: string }> {
|
||||
const did = session.sub || session.did;
|
||||
let handle = session.handle || 'unknown';
|
||||
|
||||
// Create Agent directly with session (per official docs)
|
||||
try {
|
||||
this.agent = new Agent(session);
|
||||
} catch (err) {
|
||||
// Fallback to dpopFetch method
|
||||
this.agent = new Agent({
|
||||
service: session.server?.serviceEndpoint || 'https://bsky.social',
|
||||
fetch: session.dpopFetch
|
||||
});
|
||||
}
|
||||
|
||||
// Store basic session info
|
||||
(this as any)._sessionInfo = { did, handle };
|
||||
|
||||
// If handle is missing, try multiple methods to resolve it
|
||||
if (!handle || handle === 'unknown') {
|
||||
|
||||
|
||||
// Method 1: Try using the agent to get profile
|
||||
try {
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
const profile = await this.agent.getProfile({ actor: did });
|
||||
if (profile.data.handle) {
|
||||
handle = profile.data.handle;
|
||||
(this as any)._sessionInfo.handle = handle;
|
||||
|
||||
return { did, handle };
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
}
|
||||
|
||||
// Method 2: Try using describeRepo
|
||||
try {
|
||||
const repoDesc = await this.agent.com.atproto.repo.describeRepo({
|
||||
repo: did
|
||||
});
|
||||
if (repoDesc.data.handle) {
|
||||
handle = repoDesc.data.handle;
|
||||
(this as any)._sessionInfo.handle = handle;
|
||||
|
||||
return { did, handle };
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
}
|
||||
|
||||
// Method 3: Fallback for admin DID
|
||||
const adminDid = import.meta.env.VITE_ADMIN_DID;
|
||||
if (did === adminDid) {
|
||||
const appHost = import.meta.env.VITE_APP_HOST || 'https://syui.ai';
|
||||
handle = new URL(appHost).hostname;
|
||||
(this as any)._sessionInfo.handle = handle;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return { did, handle };
|
||||
}
|
||||
|
||||
private getClientId(): string {
|
||||
// Use environment variable if available
|
||||
const envClientId = import.meta.env.VITE_OAUTH_CLIENT_ID;
|
||||
if (envClientId) {
|
||||
|
||||
return envClientId;
|
||||
}
|
||||
|
||||
const origin = window.location.origin;
|
||||
|
||||
// For localhost development, use undefined for loopback client
|
||||
// The BrowserOAuthClient will handle this automatically
|
||||
if (origin.includes('localhost') || origin.includes('127.0.0.1')) {
|
||||
|
||||
return undefined as any; // Loopback client
|
||||
}
|
||||
|
||||
// Default: use origin-based client metadata
|
||||
return `${origin}/client-metadata.json`;
|
||||
}
|
||||
|
||||
|
||||
async initiateOAuthFlow(handle?: string): Promise<void> {
|
||||
try {
|
||||
if (!this.oauthClient || !this.oauthClientSyuIs) {
|
||||
await this.initialize();
|
||||
}
|
||||
|
||||
if (!this.oauthClient || !this.oauthClientSyuIs) {
|
||||
throw new Error('Failed to initialize OAuth clients');
|
||||
}
|
||||
|
||||
// If handle is not provided, prompt user
|
||||
if (!handle) {
|
||||
handle = prompt('ハンドルを入力してください (例: user.bsky.social または user.syu.is):');
|
||||
if (!handle) {
|
||||
throw new Error('Handle is required for authentication');
|
||||
}
|
||||
}
|
||||
|
||||
// Determine which OAuth client to use
|
||||
const allowedHandlesStr = import.meta.env.VITE_ATPROTO_HANDLE_LIST || '[]';
|
||||
let allowedHandles: string[] = [];
|
||||
try {
|
||||
allowedHandles = JSON.parse(allowedHandlesStr);
|
||||
} catch {
|
||||
allowedHandles = [];
|
||||
}
|
||||
|
||||
const usesSyuIs = handle.endsWith('.syu.is') || allowedHandles.includes(handle);
|
||||
const oauthClient = usesSyuIs ? this.oauthClientSyuIs : this.oauthClient;
|
||||
|
||||
// Start OAuth authorization flow
|
||||
const authUrl = await oauthClient.authorize(handle, {
|
||||
scope: 'atproto transition:generic',
|
||||
});
|
||||
|
||||
// Redirect to authorization server
|
||||
window.location.href = authUrl.toString();
|
||||
|
||||
} catch (error) {
|
||||
throw new Error(`OAuth認証の開始に失敗しました: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async handleOAuthCallback(): Promise<{ did: string; handle: string } | null> {
|
||||
try {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// BrowserOAuthClient should automatically handle the callback
|
||||
// We just need to initialize it and it will process the current URL
|
||||
if (!this.oauthClient) {
|
||||
|
||||
await this.initialize();
|
||||
}
|
||||
|
||||
if (!this.oauthClient) {
|
||||
throw new Error('Failed to initialize OAuth client');
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Call init() again to process the callback URL
|
||||
const result = await this.oauthClient.init();
|
||||
|
||||
|
||||
if (result?.session) {
|
||||
// Process the session
|
||||
return this.processSession(result.session);
|
||||
}
|
||||
|
||||
// If no session yet, wait a bit and try again
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
// Try to check session again
|
||||
const sessionCheck = await this.checkSession();
|
||||
if (sessionCheck) {
|
||||
|
||||
return sessionCheck;
|
||||
}
|
||||
|
||||
|
||||
return null;
|
||||
|
||||
} catch (error) {
|
||||
|
||||
throw new Error(`OAuth認証の完了に失敗しました: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async checkSession(): Promise<{ did: string; handle: string } | null> {
|
||||
try {
|
||||
if (!this.oauthClient) {
|
||||
await this.initialize();
|
||||
}
|
||||
|
||||
if (!this.oauthClient) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const result = await this.oauthClient.init();
|
||||
|
||||
if (result?.session) {
|
||||
// Use the common session processing method
|
||||
return this.processSession(result.session);
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
getAgent(): Agent | null {
|
||||
return this.agent;
|
||||
}
|
||||
|
||||
getSession(): AtprotoSession | null {
|
||||
|
||||
|
||||
// First check if we have an agent with session
|
||||
if (this.agent?.session) {
|
||||
const session = {
|
||||
did: this.agent.session.did,
|
||||
handle: this.agent.session.handle || 'unknown',
|
||||
accessJwt: this.agent.session.accessJwt || '',
|
||||
refreshJwt: this.agent.session.refreshJwt || '',
|
||||
};
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
// If no agent.session but we have stored session info, return that
|
||||
if ((this as any)._sessionInfo) {
|
||||
const session = {
|
||||
did: (this as any)._sessionInfo.did,
|
||||
handle: (this as any)._sessionInfo.handle,
|
||||
accessJwt: 'dpop-protected', // Indicate that tokens are handled by dpopFetch
|
||||
refreshJwt: 'dpop-protected',
|
||||
};
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
isAuthenticated(): boolean {
|
||||
return !!this.agent || !!(this as any)._sessionInfo;
|
||||
}
|
||||
|
||||
getUser(): { did: string; handle: string } | null {
|
||||
const session = this.getSession();
|
||||
if (!session) return null;
|
||||
|
||||
return {
|
||||
did: session.did,
|
||||
handle: session.handle
|
||||
};
|
||||
}
|
||||
|
||||
async logout(): Promise<void> {
|
||||
try {
|
||||
// Clear Agent
|
||||
this.agent = null;
|
||||
|
||||
// Clear BrowserOAuthClient session
|
||||
if (this.oauthClient) {
|
||||
try {
|
||||
// BrowserOAuthClient may have a revoke or signOut method
|
||||
if (typeof (this.oauthClient as any).signOut === 'function') {
|
||||
await (this.oauthClient as any).signOut();
|
||||
} else if (typeof (this.oauthClient as any).revoke === 'function') {
|
||||
await (this.oauthClient as any).revoke();
|
||||
}
|
||||
} catch (oauthError) {
|
||||
// Ignore logout errors
|
||||
}
|
||||
|
||||
// Reset the OAuth client to force re-initialization
|
||||
this.oauthClient = null;
|
||||
this.initializePromise = null;
|
||||
}
|
||||
|
||||
// Clear any stored session data
|
||||
localStorage.removeItem('atproto_session');
|
||||
sessionStorage.clear();
|
||||
|
||||
// Clear all OAuth-related storage
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const key = localStorage.key(i);
|
||||
if (key && (key.includes('oauth') || key.includes('atproto') || key.includes('session'))) {
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear internal session info
|
||||
(this as any)._sessionInfo = null;
|
||||
|
||||
|
||||
|
||||
// Force page reload to ensure clean state
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 100);
|
||||
|
||||
} catch (error) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// カードデータをatproto collectionに保存
|
||||
async saveCardToBox(userCards: any[]): Promise<void> {
|
||||
// Ensure we have a valid session
|
||||
const sessionInfo = await this.checkSession();
|
||||
if (!sessionInfo) {
|
||||
throw new Error('認証が必要です。ログインしてください。');
|
||||
}
|
||||
|
||||
const did = sessionInfo.did;
|
||||
|
||||
try {
|
||||
|
||||
|
||||
|
||||
// Ensure we have a fresh agent
|
||||
if (!this.agent) {
|
||||
throw new Error('Agentが初期化されていません。');
|
||||
}
|
||||
|
||||
const collection = 'ai.card.box';
|
||||
const rkey = 'self';
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
// カードボックスのレコード
|
||||
const record = {
|
||||
$type: 'ai.card.box',
|
||||
cards: userCards.map(card => ({
|
||||
id: card.id,
|
||||
cp: card.cp,
|
||||
status: card.status,
|
||||
skill: card.skill,
|
||||
owner_did: card.owner_did,
|
||||
obtained_at: card.obtained_at,
|
||||
is_unique: card.is_unique,
|
||||
unique_id: card.unique_id
|
||||
|
||||
})),
|
||||
total_cards: userCards.length,
|
||||
updated_at: createdAt,
|
||||
createdAt: createdAt
|
||||
};
|
||||
|
||||
|
||||
// Use Agent's com.atproto.repo.putRecord method
|
||||
const response = await this.agent.com.atproto.repo.putRecord({
|
||||
repo: did,
|
||||
collection: collection,
|
||||
rkey: rkey,
|
||||
record: record
|
||||
});
|
||||
|
||||
|
||||
} catch (error) {
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// ai.card.boxからカード一覧を取得
|
||||
async getCardsFromBox(): Promise<any> {
|
||||
// Ensure we have a valid session
|
||||
const sessionInfo = await this.checkSession();
|
||||
if (!sessionInfo) {
|
||||
throw new Error('認証が必要です。ログインしてください。');
|
||||
}
|
||||
|
||||
const did = sessionInfo.did;
|
||||
|
||||
try {
|
||||
|
||||
|
||||
|
||||
// Ensure we have a fresh agent
|
||||
if (!this.agent) {
|
||||
throw new Error('Agentが初期化されていません。');
|
||||
}
|
||||
|
||||
const response = await this.agent.com.atproto.repo.getRecord({
|
||||
repo: did,
|
||||
collection: 'ai.card.box',
|
||||
rkey: 'self'
|
||||
});
|
||||
|
||||
|
||||
|
||||
// Convert to expected format
|
||||
const result = {
|
||||
records: [{
|
||||
uri: `at://${did}/ai.card.box/self`,
|
||||
cid: response.data.cid,
|
||||
value: response.data.value
|
||||
}]
|
||||
};
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
|
||||
|
||||
// If record doesn't exist, return empty
|
||||
if (error.toString().includes('RecordNotFound')) {
|
||||
return { records: [] };
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// ai.card.boxのコレクションを削除
|
||||
async deleteCardBox(): Promise<void> {
|
||||
// Ensure we have a valid session
|
||||
const sessionInfo = await this.checkSession();
|
||||
if (!sessionInfo) {
|
||||
throw new Error('認証が必要です。ログインしてください。');
|
||||
}
|
||||
|
||||
const did = sessionInfo.did;
|
||||
|
||||
try {
|
||||
|
||||
|
||||
|
||||
// Ensure we have a fresh agent
|
||||
if (!this.agent) {
|
||||
throw new Error('Agentが初期化されていません。');
|
||||
}
|
||||
|
||||
const response = await this.agent.com.atproto.repo.deleteRecord({
|
||||
repo: did,
|
||||
collection: 'ai.card.box',
|
||||
rkey: 'self'
|
||||
});
|
||||
|
||||
|
||||
} catch (error) {
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 手動でトークンを設定(開発・デバッグ用)
|
||||
setManualTokens(accessJwt: string, refreshJwt: string): void {
|
||||
|
||||
|
||||
|
||||
// For backward compatibility, store in localStorage
|
||||
const adminDid = import.meta.env.VITE_ADMIN_DID || 'did:plc:unknown';
|
||||
const appHost = import.meta.env.VITE_APP_HOST || 'https://example.com';
|
||||
const session: AtprotoSession = {
|
||||
did: adminDid,
|
||||
handle: new URL(appHost).hostname,
|
||||
accessJwt: accessJwt,
|
||||
refreshJwt: refreshJwt
|
||||
};
|
||||
|
||||
localStorage.setItem('atproto_session', JSON.stringify(session));
|
||||
|
||||
}
|
||||
|
||||
// 後方互換性のための従来関数
|
||||
saveSessionToStorage(session: AtprotoSession): void {
|
||||
|
||||
localStorage.setItem('atproto_session', JSON.stringify(session));
|
||||
}
|
||||
|
||||
async backupUserCards(userCards: any[]): Promise<void> {
|
||||
return this.saveCardToBox(userCards);
|
||||
}
|
||||
}
|
||||
|
||||
export const atprotoOAuthService = new AtprotoOAuthService();
|
||||
export type { AtprotoSession };
|
109
oauth/src/services/auth.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
import axios from 'axios';
|
||||
|
||||
const API_BASE = '/api/v1';
|
||||
|
||||
interface LoginRequest {
|
||||
identifier: string; // Handle or DID
|
||||
password: string; // App password
|
||||
}
|
||||
|
||||
interface LoginResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
did: string;
|
||||
handle: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
did: string;
|
||||
handle: string;
|
||||
avatar?: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
class AuthService {
|
||||
private token: string | null = null;
|
||||
private user: User | null = null;
|
||||
|
||||
constructor() {
|
||||
// Load token from localStorage
|
||||
this.token = localStorage.getItem('ai_card_token');
|
||||
|
||||
// Set default auth header if token exists
|
||||
if (this.token) {
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${this.token}`;
|
||||
}
|
||||
}
|
||||
|
||||
async login(identifier: string, password: string): Promise<LoginResponse> {
|
||||
try {
|
||||
const response = await axios.post<LoginResponse>(`${API_BASE}/auth/login`, {
|
||||
identifier,
|
||||
password
|
||||
});
|
||||
|
||||
const { access_token, did, handle } = response.data;
|
||||
|
||||
// Store token
|
||||
this.token = access_token;
|
||||
localStorage.setItem('ai_card_token', access_token);
|
||||
|
||||
// Set auth header
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`;
|
||||
|
||||
// Store user info
|
||||
this.user = { did, handle };
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
throw new Error('Login failed');
|
||||
}
|
||||
}
|
||||
|
||||
async logout(): Promise<void> {
|
||||
try {
|
||||
await axios.post(`${API_BASE}/auth/logout`);
|
||||
} catch (error) {
|
||||
// Ignore errors
|
||||
}
|
||||
|
||||
// Clear token
|
||||
this.token = null;
|
||||
this.user = null;
|
||||
localStorage.removeItem('ai_card_token');
|
||||
delete axios.defaults.headers.common['Authorization'];
|
||||
}
|
||||
|
||||
async verify(): Promise<User | null> {
|
||||
if (!this.token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await axios.get<User & { valid: boolean }>(`${API_BASE}/auth/verify`);
|
||||
if (response.data.valid) {
|
||||
this.user = {
|
||||
did: response.data.did,
|
||||
handle: response.data.handle
|
||||
};
|
||||
return this.user;
|
||||
}
|
||||
} catch (error) {
|
||||
// Token is invalid
|
||||
this.logout();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
getUser(): User | null {
|
||||
return this.user;
|
||||
}
|
||||
|
||||
isAuthenticated(): boolean {
|
||||
return this.token !== null;
|
||||
}
|
||||
}
|
||||
|
||||
export const authService = new AuthService();
|
||||
export type { User, LoginRequest, LoginResponse };
|
331
oauth/src/styles/Card.css
Normal file
@@ -0,0 +1,331 @@
|
||||
.card {
|
||||
width: 250px;
|
||||
height: 380px;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
|
||||
border: 2px solid #333;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.card:hover {
|
||||
transform: translateY(-5px);
|
||||
}
|
||||
|
||||
.card-inner {
|
||||
padding: 20px;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
/* Rarity effects */
|
||||
.card-normal {
|
||||
border-color: #666;
|
||||
}
|
||||
|
||||
.card-rare {
|
||||
border-color: #4a90e2;
|
||||
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
|
||||
}
|
||||
|
||||
.card-super-rare {
|
||||
border-color: #9c27b0;
|
||||
background: linear-gradient(135deg, #2d1b69 0%, #0f0c29 100%);
|
||||
}
|
||||
|
||||
.card-kira {
|
||||
border-color: #ffd700;
|
||||
background: linear-gradient(135deg, #232526 0%, #414345 100%);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.card-kira::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -50%;
|
||||
left: -50%;
|
||||
width: 200%;
|
||||
height: 200%;
|
||||
background: linear-gradient(
|
||||
45deg,
|
||||
transparent 30%,
|
||||
rgba(255, 215, 0, 0.1) 50%,
|
||||
transparent 70%
|
||||
);
|
||||
animation: shimmer 3s infinite;
|
||||
}
|
||||
|
||||
.card-unique {
|
||||
border-color: #ff00ff;
|
||||
background: linear-gradient(135deg, #000000 0%, #1a0033 100%);
|
||||
box-shadow: 0 0 30px rgba(255, 0, 255, 0.5);
|
||||
}
|
||||
|
||||
.card-unique::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: radial-gradient(
|
||||
circle at center,
|
||||
transparent 0%,
|
||||
rgba(255, 0, 255, 0.2) 100%
|
||||
);
|
||||
animation: pulse 2s infinite;
|
||||
}
|
||||
|
||||
/* Card content */
|
||||
.card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-size: 14px;
|
||||
color: #888;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.card-image-container {
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-bottom: 15px;
|
||||
overflow: hidden;
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.card-image {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.card-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.card-name {
|
||||
font-size: 28px;
|
||||
margin: 0;
|
||||
color: var(--card-color, #fff);
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.unique-badge {
|
||||
margin-top: 10px;
|
||||
padding: 5px 15px;
|
||||
background: linear-gradient(90deg, #ff00ff, #00ffff);
|
||||
border-radius: 20px;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
animation: glow 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.card-skill {
|
||||
margin-top: 20px;
|
||||
padding: 10px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.card-footer {
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
/* Animations */
|
||||
@keyframes shimmer {
|
||||
0% { transform: translateX(-100%); }
|
||||
100% { transform: translateX(100%); }
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% { opacity: 0.5; }
|
||||
50% { opacity: 1; }
|
||||
100% { opacity: 0.5; }
|
||||
}
|
||||
|
||||
@keyframes glow {
|
||||
0% { box-shadow: 0 0 5px rgba(255, 0, 255, 0.5); }
|
||||
50% { box-shadow: 0 0 20px rgba(255, 0, 255, 0.8); }
|
||||
100% { box-shadow: 0 0 5px rgba(255, 0, 255, 0.5); }
|
||||
}
|
||||
|
||||
/* Simple Card Styles */
|
||||
.card-simple {
|
||||
width: 240px;
|
||||
height: auto;
|
||||
background: transparent;
|
||||
border: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.card-frame {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 3/4;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: #1a1a1a;
|
||||
padding: 25px 25px 30px 25px;
|
||||
border: 3px solid #666;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* Normal card - no effects */
|
||||
.card-simple.card-normal .card-frame {
|
||||
border-color: #666;
|
||||
background: #1a1a1a;
|
||||
}
|
||||
|
||||
/* Unique (rare) card - glowing effects */
|
||||
.card-simple.card-unique .card-frame {
|
||||
border-color: #ffd700;
|
||||
background: linear-gradient(135deg, #2a2a1a 0%, #3a3a2a 50%, #2a2a1a 100%);
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Particle/grainy texture for rare cards */
|
||||
.card-simple.card-unique .card-frame::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-image:
|
||||
repeating-radial-gradient(circle at 1px 1px, rgba(255, 255, 255, 0.1) 0px, transparent 1px, transparent 2px),
|
||||
repeating-radial-gradient(circle at 3px 3px, rgba(255, 215, 0, 0.1) 0px, transparent 2px, transparent 4px);
|
||||
background-size: 20px 20px, 30px 30px;
|
||||
opacity: 0.8;
|
||||
z-index: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Reflection effect for rare cards */
|
||||
.card-simple.card-unique .card-frame::after {
|
||||
content: "";
|
||||
height: 100%;
|
||||
width: 40px;
|
||||
position: absolute;
|
||||
top: -180px;
|
||||
left: 0;
|
||||
background: linear-gradient(90deg,
|
||||
transparent 0%,
|
||||
rgba(255, 215, 0, 0.8) 20%,
|
||||
rgba(255, 255, 0, 0.9) 40%,
|
||||
rgba(255, 223, 0, 1) 50%,
|
||||
rgba(255, 255, 0, 0.9) 60%,
|
||||
rgba(255, 215, 0, 0.8) 80%,
|
||||
transparent 100%
|
||||
);
|
||||
opacity: 0;
|
||||
transform: rotate(45deg);
|
||||
animation: gold-reflection 6s ease-in-out infinite;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
@keyframes gold-reflection {
|
||||
0% { transform: scale(0) rotate(45deg); opacity: 0; }
|
||||
15% { transform: scale(0) rotate(45deg); opacity: 0; }
|
||||
17% { transform: scale(4) rotate(45deg); opacity: 0.8; }
|
||||
20% { transform: scale(50) rotate(45deg); opacity: 0; }
|
||||
100% { transform: scale(50) rotate(45deg); opacity: 0; }
|
||||
}
|
||||
|
||||
/* Glowing backlight effect */
|
||||
.card-simple.card-unique {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.card-simple.card-unique::after {
|
||||
position: absolute;
|
||||
content: "";
|
||||
top: 5px;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: -1;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
transform: scale(0.95);
|
||||
filter: blur(15px);
|
||||
background: radial-gradient(ellipse at center, #ffd700 0%, #ffb347 50%, transparent 70%);
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
/* Glowing border effect for rare cards */
|
||||
.card-simple.card-unique .card-frame {
|
||||
box-shadow:
|
||||
0 0 10px rgba(255, 215, 0, 0.5),
|
||||
inset 0 0 10px rgba(255, 215, 0, 0.1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
.card-image-simple {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 4px;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.card-cp-bar {
|
||||
width: 100%;
|
||||
height: 50px;
|
||||
background: #333;
|
||||
border-radius: 6px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-top: 12px;
|
||||
margin-bottom: 8px;
|
||||
border: 2px solid #666;
|
||||
position: relative;
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.card-simple.card-unique .card-cp-bar {
|
||||
background: linear-gradient(135deg, #2a2a1a 0%, #3a3a2a 50%, #2a2a1a 100%);
|
||||
border-color: #ffd700;
|
||||
box-shadow:
|
||||
0 0 5px rgba(255, 215, 0, 0.3),
|
||||
inset 0 0 5px rgba(255, 215, 0, 0.1);
|
||||
}
|
||||
|
||||
|
||||
.cp-value {
|
||||
font-size: 20px;
|
||||
font-weight: bold;
|
||||
color: #fff;
|
||||
text-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
|
||||
z-index: 1;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
|
||||
|
196
oauth/src/styles/CardBox.css
Normal file
@@ -0,0 +1,196 @@
|
||||
.card-box-container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.card-box-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
padding-bottom: 15px;
|
||||
border-bottom: 2px solid #e9ecef;
|
||||
}
|
||||
|
||||
.card-box-header h3 {
|
||||
color: #495057;
|
||||
margin: 0;
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.box-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.uri-display {
|
||||
background: #e3f2fd;
|
||||
border: 1px solid #bbdefb;
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.uri-display p {
|
||||
margin: 0;
|
||||
color: #1565c0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.uri-display code {
|
||||
background: #ffffff;
|
||||
border: 1px solid #90caf9;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 12px;
|
||||
color: #0d47a1;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.json-button,
|
||||
.refresh-button,
|
||||
.retry-button,
|
||||
.delete-button {
|
||||
padding: 8px 16px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.json-button {
|
||||
background: linear-gradient(135deg, #6f42c1 0%, #8b5fc3 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.json-button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(111, 66, 193, 0.4);
|
||||
}
|
||||
|
||||
.refresh-button {
|
||||
background: linear-gradient(135deg, #17a2b8 0%, #20c997 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.refresh-button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(23, 162, 184, 0.4);
|
||||
}
|
||||
|
||||
.retry-button {
|
||||
background: linear-gradient(135deg, #fd7e14 0%, #ffc107 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.retry-button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(253, 126, 20, 0.4);
|
||||
}
|
||||
|
||||
.delete-button {
|
||||
background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.delete-button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4);
|
||||
}
|
||||
|
||||
.delete-button:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.json-display {
|
||||
background: #f8f9fa;
|
||||
border: 1px solid #dee2e6;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.json-display h4 {
|
||||
color: #495057;
|
||||
margin-top: 0;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.json-content {
|
||||
background: #ffffff;
|
||||
border: 1px solid #e9ecef;
|
||||
border-radius: 4px;
|
||||
padding: 15px;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 12px;
|
||||
color: #495057;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
.box-stats {
|
||||
background: rgba(102, 126, 234, 0.1);
|
||||
border: 1px solid #dee2e6;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.box-stats p {
|
||||
margin: 0;
|
||||
color: #495057;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.card-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.box-card-item {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.card-info {
|
||||
margin-top: 8px;
|
||||
color: #6c757d;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.empty-box {
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
color: #6c757d;
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #dee2e6;
|
||||
}
|
||||
|
||||
.empty-box p {
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.loading,
|
||||
.error {
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
color: #6c757d;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #dc3545;
|
||||
background: #f8d7da;
|
||||
border: 1px solid #f5c6cb;
|
||||
border-radius: 8px;
|
||||
}
|
170
oauth/src/styles/CardList.css
Normal file
@@ -0,0 +1,170 @@
|
||||
.card-list-container {
|
||||
min-height: 100vh;
|
||||
background: linear-gradient(135deg, #0f0f0f 0%, #1a1a1a 100%);
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.card-list-header {
|
||||
text-align: center;
|
||||
margin-bottom: 40px;
|
||||
padding: 20px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 12px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.card-list-header h1 {
|
||||
color: #fff;
|
||||
margin: 0 0 10px 0;
|
||||
font-size: 2.5rem;
|
||||
}
|
||||
|
||||
.card-list-header p {
|
||||
color: #999;
|
||||
margin: 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.card-list-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
gap: 30px;
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.card-list-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
/* Simple grid layout for user-page style */
|
||||
.card-list-simple-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.card-list-simple-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.info-button {
|
||||
background: linear-gradient(135deg, #333 0%, #555 100%);
|
||||
color: white;
|
||||
border: 2px solid #666;
|
||||
padding: 8px 16px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 0.9rem;
|
||||
transition: all 0.3s ease;
|
||||
width: 100%;
|
||||
max-width: 240px;
|
||||
}
|
||||
|
||||
.info-button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
||||
background: linear-gradient(135deg, #444 0%, #666 100%);
|
||||
}
|
||||
|
||||
.card-info-details {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
width: 100%;
|
||||
max-width: 240px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.card-info-details p {
|
||||
margin: 5px 0;
|
||||
color: #ccc;
|
||||
font-size: 0.85rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.card-info-details p strong {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.card-meta {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
width: 100%;
|
||||
max-width: 250px;
|
||||
}
|
||||
|
||||
.card-meta p {
|
||||
margin: 5px 0;
|
||||
color: #ccc;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.card-meta p:first-child {
|
||||
font-weight: bold;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.card-description {
|
||||
font-size: 0.85rem;
|
||||
color: #999;
|
||||
font-style: italic;
|
||||
margin-top: 8px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.source-info {
|
||||
font-size: 0.9rem;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.loading, .error {
|
||||
text-align: center;
|
||||
padding: 40px;
|
||||
color: #999;
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #ff4757;
|
||||
}
|
||||
|
||||
button {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.card-list-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.card-list-header h1 {
|
||||
font-size: 2rem;
|
||||
}
|
||||
}
|
172
oauth/src/styles/CollectionAnalysis.css
Normal file
@@ -0,0 +1,172 @@
|
||||
.collection-analysis {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
border-radius: 16px;
|
||||
padding: 24px;
|
||||
margin: 20px 0;
|
||||
color: white;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.collection-analysis h3 {
|
||||
margin: 0 0 20px 0;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.analysis-stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
|
||||
gap: 16px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
text-align: center;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 2rem;
|
||||
font-weight: bold;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 0.9rem;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.rarity-distribution {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.rarity-distribution h4 {
|
||||
margin: 0 0 16px 0;
|
||||
font-size: 1.2rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.rarity-bars {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.rarity-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.rarity-name {
|
||||
min-width: 80px;
|
||||
font-weight: 500;
|
||||
text-transform: capitalize;
|
||||
}
|
||||
|
||||
.bar-container {
|
||||
flex: 1;
|
||||
height: 20px;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.bar {
|
||||
height: 100%;
|
||||
border-radius: 10px;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.bar-common { background: linear-gradient(90deg, #4CAF50, #45a049); }
|
||||
.bar-rare { background: linear-gradient(90deg, #2196F3, #1976D2); }
|
||||
.bar-epic { background: linear-gradient(90deg, #9C27B0, #7B1FA2); }
|
||||
.bar-legendary { background: linear-gradient(90deg, #FF9800, #F57C00); }
|
||||
.bar-mythic { background: linear-gradient(90deg, #F44336, #D32F2F); }
|
||||
|
||||
.rarity-count {
|
||||
min-width: 40px;
|
||||
text-align: right;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.recommendations {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.recommendations h4 {
|
||||
margin: 0 0 12px 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.recommendations ul {
|
||||
margin: 0;
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.recommendations li {
|
||||
margin-bottom: 8px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.refresh-analysis,
|
||||
.analyze-button,
|
||||
.retry-button {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border: 1px solid rgba(255, 255, 255, 0.3);
|
||||
color: white;
|
||||
border-radius: 8px;
|
||||
padding: 12px 24px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.refresh-analysis:hover,
|
||||
.analyze-button:hover,
|
||||
.retry-button:hover {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.analysis-loading,
|
||||
.analysis-error,
|
||||
.analysis-empty {
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
}
|
||||
|
||||
.loading-spinner {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 3px solid rgba(255, 255, 255, 0.3);
|
||||
border-top: 3px solid white;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
margin: 0 auto 16px;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.analysis-error p {
|
||||
color: #ffcdd2;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.analysis-empty p {
|
||||
opacity: 0.8;
|
||||
margin-bottom: 16px;
|
||||
}
|
174
oauth/src/styles/GachaAnimation.css
Normal file
@@ -0,0 +1,174 @@
|
||||
.gacha-container {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, 0.9);
|
||||
z-index: 1000;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.card-final {
|
||||
position: relative;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.card-actions {
|
||||
position: absolute;
|
||||
bottom: -80px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.save-button {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
border-radius: 25px;
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.save-button:hover:not(:disabled) {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
|
||||
}
|
||||
|
||||
.save-button:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.click-hint {
|
||||
color: white;
|
||||
font-size: 12px;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
padding: 6px 12px;
|
||||
border-radius: 15px;
|
||||
animation: pulse 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% { opacity: 0.7; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
|
||||
.gacha-opening {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.gacha-pack {
|
||||
width: 200px;
|
||||
height: 280px;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
border-radius: 16px;
|
||||
position: relative;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.pack-glow {
|
||||
position: absolute;
|
||||
top: -20px;
|
||||
left: -20px;
|
||||
right: -20px;
|
||||
bottom: -20px;
|
||||
background: radial-gradient(circle, rgba(255, 255, 255, 0.3) 0%, transparent 70%);
|
||||
animation: glow-pulse 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Effect variations */
|
||||
.effect-normal {
|
||||
background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 50%);
|
||||
}
|
||||
|
||||
.effect-rare {
|
||||
background: radial-gradient(circle, rgba(74, 144, 226, 0.2) 0%, transparent 50%);
|
||||
}
|
||||
|
||||
.effect-kira {
|
||||
background: radial-gradient(circle, rgba(255, 215, 0, 0.3) 0%, transparent 50%);
|
||||
}
|
||||
|
||||
.effect-kira::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><polygon points="50,0 60,40 100,50 60,60 50,100 40,60 0,50 40,40" fill="rgba(255,215,0,0.1)"/></svg>');
|
||||
background-size: 50px 50px;
|
||||
animation: sparkle 3s linear infinite;
|
||||
}
|
||||
|
||||
.effect-unique {
|
||||
background: radial-gradient(circle, rgba(255, 0, 255, 0.4) 0%, transparent 50%);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.unique-effect {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.unique-particles {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-image:
|
||||
radial-gradient(circle, #ff00ff 1px, transparent 1px),
|
||||
radial-gradient(circle, #00ffff 1px, transparent 1px);
|
||||
background-size: 50px 50px, 30px 30px;
|
||||
background-position: 0 0, 25px 25px;
|
||||
animation: particle-float 20s linear infinite;
|
||||
}
|
||||
|
||||
.unique-burst {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
width: 300px;
|
||||
height: 300px;
|
||||
transform: translate(-50%, -50%);
|
||||
background: radial-gradient(circle, rgba(255, 0, 255, 0.8) 0%, transparent 70%);
|
||||
animation: burst 1s ease-out;
|
||||
}
|
||||
|
||||
/* Animations */
|
||||
@keyframes glow-pulse {
|
||||
0%, 100% { opacity: 0.5; transform: scale(1); }
|
||||
50% { opacity: 1; transform: scale(1.1); }
|
||||
}
|
||||
|
||||
@keyframes sparkle {
|
||||
0% { transform: translateY(0) rotate(0deg); }
|
||||
100% { transform: translateY(-100vh) rotate(360deg); }
|
||||
}
|
||||
|
||||
@keyframes particle-float {
|
||||
0% { transform: translate(0, 0); }
|
||||
100% { transform: translate(-50px, -100px); }
|
||||
}
|
||||
|
||||
@keyframes burst {
|
||||
0% { transform: translate(-50%, -50%) scale(0); opacity: 1; }
|
||||
100% { transform: translate(-50%, -50%) scale(3); opacity: 0; }
|
||||
}
|
219
oauth/src/styles/GachaStats.css
Normal file
@@ -0,0 +1,219 @@
|
||||
.gacha-stats {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
border-radius: 16px;
|
||||
padding: 24px;
|
||||
margin: 20px 0;
|
||||
color: white;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.gacha-stats h3 {
|
||||
margin: 0 0 20px 0;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stats-overview {
|
||||
margin-bottom: 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.overview-card {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
display: inline-block;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.overview-value {
|
||||
font-size: 2.5rem;
|
||||
font-weight: bold;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.overview-label {
|
||||
font-size: 1rem;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.rarity-stats {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.rarity-stats h4 {
|
||||
margin: 0 0 16px 0;
|
||||
font-size: 1.2rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.rarity-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.rarity-stat {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
text-align: center;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.rarity-stat::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 3px;
|
||||
background: var(--rarity-color);
|
||||
}
|
||||
|
||||
.rarity-stat.rarity-common { --rarity-color: #4CAF50; }
|
||||
.rarity-stat.rarity-rare { --rarity-color: #2196F3; }
|
||||
.rarity-stat.rarity-epic { --rarity-color: #9C27B0; }
|
||||
.rarity-stat.rarity-legendary { --rarity-color: #FF9800; }
|
||||
.rarity-stat.rarity-mythic { --rarity-color: #F44336; }
|
||||
|
||||
.rarity-count {
|
||||
font-size: 1.8rem;
|
||||
font-weight: bold;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.rarity-name {
|
||||
font-size: 0.9rem;
|
||||
opacity: 0.9;
|
||||
text-transform: capitalize;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.success-rate {
|
||||
font-size: 0.8rem;
|
||||
opacity: 0.7;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 4px;
|
||||
padding: 2px 6px;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.recent-activity {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.recent-activity h4 {
|
||||
margin: 0 0 12px 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.activity-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.activity-item {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.activity-time {
|
||||
font-size: 0.8rem;
|
||||
opacity: 0.7;
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
.activity-details {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex: 1;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.card-rarity {
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.card-rarity.rarity-common { background: #4CAF50; }
|
||||
.card-rarity.rarity-rare { background: #2196F3; }
|
||||
.card-rarity.rarity-epic { background: #9C27B0; }
|
||||
.card-rarity.rarity-legendary { background: #FF9800; }
|
||||
.card-rarity.rarity-mythic { background: #F44336; }
|
||||
|
||||
.card-name {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.refresh-stats,
|
||||
.load-stats-button,
|
||||
.retry-button {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border: 1px solid rgba(255, 255, 255, 0.3);
|
||||
color: white;
|
||||
border-radius: 8px;
|
||||
padding: 12px 24px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.refresh-stats:hover,
|
||||
.load-stats-button:hover,
|
||||
.retry-button:hover {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.stats-loading,
|
||||
.stats-error,
|
||||
.stats-empty {
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
}
|
||||
|
||||
.loading-spinner {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 3px solid rgba(255, 255, 255, 0.3);
|
||||
border-top: 3px solid white;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
margin: 0 auto 16px;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.stats-error p {
|
||||
color: #ffcdd2;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.stats-empty p {
|
||||
opacity: 0.8;
|
||||
margin-bottom: 16px;
|
||||
}
|
243
oauth/src/styles/Login.css
Normal file
@@ -0,0 +1,243 @@
|
||||
.login-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
backdrop-filter: blur(5px);
|
||||
}
|
||||
|
||||
.login-modal {
|
||||
background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
|
||||
border: 1px solid #444;
|
||||
border-radius: 16px;
|
||||
padding: 40px;
|
||||
max-width: 450px;
|
||||
width: 90%;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.login-mode-selector {
|
||||
display: flex;
|
||||
margin-bottom: 24px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.mode-button {
|
||||
flex: 1;
|
||||
padding: 12px 16px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #ccc;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.mode-button.active {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.mode-button:hover:not(.active) {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.oauth-login {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.oauth-info {
|
||||
margin-bottom: 24px;
|
||||
padding: 20px;
|
||||
background: rgba(102, 126, 234, 0.1);
|
||||
border-radius: 12px;
|
||||
border: 1px solid rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.oauth-info h3 {
|
||||
margin: 0 0 12px 0;
|
||||
font-size: 18px;
|
||||
color: #667eea;
|
||||
}
|
||||
|
||||
.oauth-info p {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.oauth-login-button {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
border: none;
|
||||
color: white;
|
||||
padding: 16px 32px;
|
||||
border-radius: 12px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.oauth-login-button:hover:not(:disabled) {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
|
||||
}
|
||||
|
||||
.oauth-login-button:disabled {
|
||||
opacity: 0.7;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.login-modal h2 {
|
||||
margin: 0 0 30px 0;
|
||||
font-size: 28px;
|
||||
text-align: center;
|
||||
background: linear-gradient(90deg, #fff700 0%, #ff00ff 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
color: #ccc;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.form-group input {
|
||||
width: 100%;
|
||||
padding: 12px 16px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
color: white;
|
||||
font-size: 16px;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.form-group input:focus {
|
||||
outline: none;
|
||||
border-color: #fff700;
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
box-shadow: 0 0 0 2px rgba(255, 247, 0, 0.2);
|
||||
}
|
||||
|
||||
.form-group input:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.form-group small {
|
||||
display: block;
|
||||
margin-top: 6px;
|
||||
color: #888;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.form-group small a {
|
||||
color: #fff700;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.form-group small a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
background: rgba(255, 71, 87, 0.1);
|
||||
border: 1px solid rgba(255, 71, 87, 0.3);
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
margin-bottom: 20px;
|
||||
color: #ff4757;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.button-group {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin-top: 30px;
|
||||
}
|
||||
|
||||
.login-button,
|
||||
.cancel-button {
|
||||
flex: 1;
|
||||
padding: 14px 24px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.login-button {
|
||||
background: linear-gradient(135deg, #fff700 0%, #ffd700 100%);
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.login-button:hover:not(:disabled) {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(255, 247, 0, 0.4);
|
||||
}
|
||||
|
||||
.login-button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.cancel-button {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: white;
|
||||
border: 1px solid #444;
|
||||
}
|
||||
|
||||
.cancel-button:hover:not(:disabled) {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border-color: #666;
|
||||
}
|
||||
|
||||
.login-info {
|
||||
margin-top: 30px;
|
||||
padding-top: 20px;
|
||||
border-top: 1px solid #333;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.login-info p {
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.dev-notice {
|
||||
background: rgba(255, 193, 7, 0.1);
|
||||
border: 1px solid rgba(255, 193, 7, 0.3);
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
margin: 10px 0;
|
||||
color: #ffc107;
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
}
|
135
oauth/src/tests/console-test.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
// Simple console test for OAuth app
|
||||
// This runs before 'npm run preview' to display test results
|
||||
|
||||
// Mock import.meta.env for Node.js environment
|
||||
(global as any).import = {
|
||||
meta: {
|
||||
env: {
|
||||
VITE_ATPROTO_PDS: process.env.VITE_ATPROTO_PDS || 'syu.is',
|
||||
VITE_ADMIN_HANDLE: process.env.VITE_ADMIN_HANDLE || 'ai.syui.ai',
|
||||
VITE_AI_HANDLE: process.env.VITE_AI_HANDLE || 'ai.syui.ai',
|
||||
VITE_OAUTH_COLLECTION: process.env.VITE_OAUTH_COLLECTION || 'ai.syui.log',
|
||||
VITE_ATPROTO_HANDLE_LIST: process.env.VITE_ATPROTO_HANDLE_LIST || '["syui.ai", "ai.syui.ai", "yui.syui.ai"]',
|
||||
VITE_APP_HOST: process.env.VITE_APP_HOST || 'https://log.syui.ai'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Simple implementation of functions for testing
|
||||
function detectPdsFromHandle(handle: string): string {
|
||||
if (handle.endsWith('.syu.is') || handle.endsWith('.syui.ai')) {
|
||||
return 'syu.is';
|
||||
}
|
||||
if (handle.endsWith('.bsky.social')) {
|
||||
return 'bsky.social';
|
||||
}
|
||||
// Default case - check if it's in the allowed list
|
||||
const allowedHandles = JSON.parse((global as any).import.meta.env.VITE_ATPROTO_HANDLE_LIST || '[]');
|
||||
if (allowedHandles.includes(handle)) {
|
||||
return (global as any).import.meta.env.VITE_ATPROTO_PDS || 'syu.is';
|
||||
}
|
||||
return 'bsky.social';
|
||||
}
|
||||
|
||||
function getNetworkConfig(pds: string) {
|
||||
switch (pds) {
|
||||
case 'bsky.social':
|
||||
case 'bsky.app':
|
||||
return {
|
||||
pdsApi: `https://${pds}`,
|
||||
plcApi: 'https://plc.directory',
|
||||
bskyApi: 'https://public.api.bsky.app',
|
||||
webUrl: 'https://bsky.app'
|
||||
};
|
||||
case 'syu.is':
|
||||
return {
|
||||
pdsApi: 'https://syu.is',
|
||||
plcApi: 'https://plc.syu.is',
|
||||
bskyApi: 'https://bsky.syu.is',
|
||||
webUrl: 'https://web.syu.is'
|
||||
};
|
||||
default:
|
||||
return {
|
||||
pdsApi: `https://${pds}`,
|
||||
plcApi: 'https://plc.directory',
|
||||
bskyApi: 'https://public.api.bsky.app',
|
||||
webUrl: 'https://bsky.app'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Main test execution
|
||||
console.log('\n=== OAuth App Configuration Tests ===\n');
|
||||
|
||||
// Test 1: Handle input behavior
|
||||
console.log('1. Handle Input → PDS Detection:');
|
||||
const testHandles = [
|
||||
'syui.ai',
|
||||
'syui.syu.is',
|
||||
'syui.syui.ai',
|
||||
'test.bsky.social',
|
||||
'unknown.handle'
|
||||
];
|
||||
|
||||
testHandles.forEach(handle => {
|
||||
const pds = detectPdsFromHandle(handle);
|
||||
const config = getNetworkConfig(pds);
|
||||
console.log(` ${handle.padEnd(20)} → PDS: ${pds.padEnd(12)} → API: ${config.pdsApi}`);
|
||||
});
|
||||
|
||||
// Test 2: Environment variable impact
|
||||
console.log('\n2. Current Environment Configuration:');
|
||||
const env = (global as any).import.meta.env;
|
||||
console.log(` VITE_ATPROTO_PDS: ${env.VITE_ATPROTO_PDS}`);
|
||||
console.log(` VITE_ADMIN_HANDLE: ${env.VITE_ADMIN_HANDLE}`);
|
||||
console.log(` VITE_AI_HANDLE: ${env.VITE_AI_HANDLE}`);
|
||||
console.log(` VITE_OAUTH_COLLECTION: ${env.VITE_OAUTH_COLLECTION}`);
|
||||
console.log(` VITE_ATPROTO_HANDLE_LIST: ${env.VITE_ATPROTO_HANDLE_LIST}`);
|
||||
|
||||
// Test 3: API endpoint generation
|
||||
console.log('\n3. Generated API Endpoints:');
|
||||
const adminPds = detectPdsFromHandle(env.VITE_ADMIN_HANDLE);
|
||||
const adminConfig = getNetworkConfig(adminPds);
|
||||
console.log(` Admin PDS detection: ${env.VITE_ADMIN_HANDLE} → ${adminPds}`);
|
||||
console.log(` Admin API endpoints:`);
|
||||
console.log(` - PDS API: ${adminConfig.pdsApi}`);
|
||||
console.log(` - Bsky API: ${adminConfig.bskyApi}`);
|
||||
console.log(` - Web URL: ${adminConfig.webUrl}`);
|
||||
|
||||
// Test 4: Collection URLs
|
||||
console.log('\n4. Collection API URLs:');
|
||||
const baseCollection = env.VITE_OAUTH_COLLECTION;
|
||||
console.log(` User list: ${adminConfig.pdsApi}/xrpc/com.atproto.repo.listRecords?repo=${env.VITE_ADMIN_HANDLE}&collection=${baseCollection}.user`);
|
||||
console.log(` Chat: ${adminConfig.pdsApi}/xrpc/com.atproto.repo.listRecords?repo=${env.VITE_ADMIN_HANDLE}&collection=${baseCollection}.chat`);
|
||||
console.log(` Lang: ${adminConfig.pdsApi}/xrpc/com.atproto.repo.listRecords?repo=${env.VITE_ADMIN_HANDLE}&collection=${baseCollection}.chat.lang`);
|
||||
console.log(` Comment: ${adminConfig.pdsApi}/xrpc/com.atproto.repo.listRecords?repo=${env.VITE_ADMIN_HANDLE}&collection=${baseCollection}.chat.comment`);
|
||||
|
||||
// Test 5: OAuth routing logic
|
||||
console.log('\n5. OAuth Authorization Logic:');
|
||||
const allowedHandles = JSON.parse(env.VITE_ATPROTO_HANDLE_LIST || '[]');
|
||||
console.log(` Allowed handles: ${JSON.stringify(allowedHandles)}`);
|
||||
console.log(` OAuth scenarios:`);
|
||||
|
||||
const oauthTestCases = [
|
||||
'syui.ai', // Should use syu.is (in allowed list)
|
||||
'test.syu.is', // Should use syu.is (*.syu.is pattern)
|
||||
'user.bsky.social' // Should use bsky.social (default)
|
||||
];
|
||||
|
||||
oauthTestCases.forEach(handle => {
|
||||
const pds = detectPdsFromHandle(handle);
|
||||
const isAllowed = allowedHandles.includes(handle);
|
||||
const reason = handle.endsWith('.syu.is') ? '*.syu.is pattern' :
|
||||
isAllowed ? 'in allowed list' :
|
||||
'default';
|
||||
console.log(` ${handle.padEnd(20)} → https://${pds}/oauth/authorize (${reason})`);
|
||||
});
|
||||
|
||||
// Test 6: AI Profile Resolution
|
||||
console.log('\n6. AI Profile Resolution:');
|
||||
const aiPds = detectPdsFromHandle(env.VITE_AI_HANDLE);
|
||||
const aiConfig = getNetworkConfig(aiPds);
|
||||
console.log(` AI Handle: ${env.VITE_AI_HANDLE} → PDS: ${aiPds}`);
|
||||
console.log(` AI Profile API: ${aiConfig.bskyApi}/xrpc/app.bsky.actor.getProfile?actor=${env.VITE_AI_HANDLE}`);
|
||||
|
||||
console.log('\n=== Tests Complete ===\n');
|
141
oauth/src/tests/oauth.test.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { getAppConfig } from '../config/app';
|
||||
import { detectPdsFromHandle, getNetworkConfig } from '../App';
|
||||
|
||||
// Test helper to mock environment variables
|
||||
const mockEnv = (vars: Record<string, string>) => {
|
||||
Object.keys(vars).forEach(key => {
|
||||
(import.meta.env as any)[key] = vars[key];
|
||||
});
|
||||
};
|
||||
|
||||
describe('OAuth App Tests', () => {
|
||||
describe('Handle Input Behavior', () => {
|
||||
it('should detect PDS for syui.ai (Bluesky)', () => {
|
||||
const pds = detectPdsFromHandle('syui.ai');
|
||||
expect(pds).toBe('bsky.social');
|
||||
});
|
||||
|
||||
it('should detect PDS for syui.syu.is (syu.is)', () => {
|
||||
const pds = detectPdsFromHandle('syui.syu.is');
|
||||
expect(pds).toBe('syu.is');
|
||||
});
|
||||
|
||||
it('should detect PDS for syui.syui.ai (syu.is)', () => {
|
||||
const pds = detectPdsFromHandle('syui.syui.ai');
|
||||
expect(pds).toBe('syu.is');
|
||||
});
|
||||
|
||||
it('should use network config for different PDS', () => {
|
||||
const bskyConfig = getNetworkConfig('bsky.social');
|
||||
expect(bskyConfig.pdsApi).toBe('https://bsky.social');
|
||||
expect(bskyConfig.bskyApi).toBe('https://public.api.bsky.app');
|
||||
expect(bskyConfig.webUrl).toBe('https://bsky.app');
|
||||
|
||||
const syuisConfig = getNetworkConfig('syu.is');
|
||||
expect(syuisConfig.pdsApi).toBe('https://syu.is');
|
||||
expect(syuisConfig.bskyApi).toBe('https://bsky.syu.is');
|
||||
expect(syuisConfig.webUrl).toBe('https://web.syu.is');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Environment Variable Changes', () => {
|
||||
beforeEach(() => {
|
||||
// Reset environment variables
|
||||
delete (import.meta.env as any).VITE_ATPROTO_PDS;
|
||||
delete (import.meta.env as any).VITE_ADMIN_HANDLE;
|
||||
delete (import.meta.env as any).VITE_AI_HANDLE;
|
||||
});
|
||||
|
||||
it('should use correct PDS for AI profile', () => {
|
||||
mockEnv({
|
||||
VITE_ATPROTO_PDS: 'syu.is',
|
||||
VITE_ADMIN_HANDLE: 'ai.syui.ai',
|
||||
VITE_AI_HANDLE: 'ai.syui.ai'
|
||||
});
|
||||
|
||||
const config = getAppConfig();
|
||||
expect(config.atprotoPds).toBe('syu.is');
|
||||
expect(config.adminHandle).toBe('ai.syui.ai');
|
||||
expect(config.aiHandle).toBe('ai.syui.ai');
|
||||
|
||||
// Network config should use syu.is endpoints
|
||||
const networkConfig = getNetworkConfig(config.atprotoPds);
|
||||
expect(networkConfig.bskyApi).toBe('https://bsky.syu.is');
|
||||
});
|
||||
|
||||
it('should construct correct API requests for admin userlist', () => {
|
||||
mockEnv({
|
||||
VITE_ATPROTO_PDS: 'syu.is',
|
||||
VITE_ADMIN_HANDLE: 'ai.syui.ai',
|
||||
VITE_OAUTH_COLLECTION: 'ai.syui.log'
|
||||
});
|
||||
|
||||
const config = getAppConfig();
|
||||
const networkConfig = getNetworkConfig(config.atprotoPds);
|
||||
const userListUrl = `${networkConfig.pdsApi}/xrpc/com.atproto.repo.listRecords?repo=${config.adminHandle}&collection=${config.collections.base}.user`;
|
||||
|
||||
expect(userListUrl).toBe('https://syu.is/xrpc/com.atproto.repo.listRecords?repo=ai.syui.ai&collection=ai.syui.log.user');
|
||||
});
|
||||
});
|
||||
|
||||
describe('OAuth Login Flow', () => {
|
||||
it('should use syu.is OAuth for handles in VITE_ATPROTO_HANDLE_LIST', () => {
|
||||
mockEnv({
|
||||
VITE_ATPROTO_HANDLE_LIST: '["syui.ai", "ai.syui.ai", "yui.syui.ai"]',
|
||||
VITE_ATPROTO_PDS: 'syu.is'
|
||||
});
|
||||
|
||||
const config = getAppConfig();
|
||||
const handle = 'syui.ai';
|
||||
|
||||
// Check if handle is in allowed list
|
||||
expect(config.allowedHandles).toContain(handle);
|
||||
|
||||
// Should use configured PDS for OAuth
|
||||
const expectedAuthUrl = `https://${config.atprotoPds}/oauth/authorize`;
|
||||
expect(expectedAuthUrl).toContain('syu.is');
|
||||
});
|
||||
|
||||
it('should use syu.is OAuth for *.syu.is handles', () => {
|
||||
const handle = 'test.syu.is';
|
||||
const pds = detectPdsFromHandle(handle);
|
||||
expect(pds).toBe('syu.is');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Terminal display test output
|
||||
export function runTerminalTests() {
|
||||
console.log('\n=== OAuth App Tests ===\n');
|
||||
|
||||
// Test 1: Handle input behavior
|
||||
console.log('1. Handle Input Detection:');
|
||||
const handles = ['syui.ai', 'syui.syu.is', 'syui.syui.ai'];
|
||||
handles.forEach(handle => {
|
||||
const pds = detectPdsFromHandle(handle);
|
||||
console.log(` ${handle} → PDS: ${pds}`);
|
||||
});
|
||||
|
||||
// Test 2: Environment variable impact
|
||||
console.log('\n2. Environment Variables:');
|
||||
const config = getAppConfig();
|
||||
console.log(` VITE_ATPROTO_PDS: ${config.atprotoPds}`);
|
||||
console.log(` VITE_ADMIN_HANDLE: ${config.adminHandle}`);
|
||||
console.log(` VITE_AI_HANDLE: ${config.aiHandle}`);
|
||||
console.log(` VITE_OAUTH_COLLECTION: ${config.collections.base}`);
|
||||
|
||||
// Test 3: API endpoints
|
||||
console.log('\n3. API Endpoints:');
|
||||
const networkConfig = getNetworkConfig(config.atprotoPds);
|
||||
console.log(` Admin PDS API: ${networkConfig.pdsApi}`);
|
||||
console.log(` Admin Bsky API: ${networkConfig.bskyApi}`);
|
||||
console.log(` User list URL: ${networkConfig.pdsApi}/xrpc/com.atproto.repo.listRecords?repo=${config.adminHandle}&collection=${config.collections.base}.user`);
|
||||
|
||||
// Test 4: OAuth routing
|
||||
console.log('\n4. OAuth Routing:');
|
||||
console.log(` Allowed handles: ${JSON.stringify(config.allowedHandles)}`);
|
||||
console.log(` OAuth endpoint: https://${config.atprotoPds}/oauth/authorize`);
|
||||
|
||||
console.log('\n=== End Tests ===\n');
|
||||
}
|
24
oauth/src/types/card.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
export enum CardRarity {
|
||||
NORMAL = "normal",
|
||||
RARE = "rare",
|
||||
SUPER_RARE = "super_rare",
|
||||
KIRA = "kira",
|
||||
UNIQUE = "unique"
|
||||
}
|
||||
|
||||
export interface Card {
|
||||
id: number;
|
||||
cp: number;
|
||||
status: CardRarity;
|
||||
skill?: string;
|
||||
owner_did: string;
|
||||
obtained_at: string;
|
||||
is_unique: boolean;
|
||||
unique_id?: string;
|
||||
}
|
||||
|
||||
export interface CardDrawResult {
|
||||
card: Card;
|
||||
is_new: boolean;
|
||||
animation_type: string;
|
||||
}
|
138
oauth/src/utils/oauth-endpoints.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* OAuth dynamic endpoint handlers
|
||||
*/
|
||||
import { OAuthKeyManager, generateClientMetadata } from './oauth-keys';
|
||||
|
||||
export class OAuthEndpointHandler {
|
||||
/**
|
||||
* Initialize OAuth endpoint handlers
|
||||
*/
|
||||
static init() {
|
||||
// Intercept requests to client-metadata.json
|
||||
this.setupClientMetadataHandler();
|
||||
|
||||
// Intercept requests to .well-known/jwks.json
|
||||
this.setupJWKSHandler();
|
||||
}
|
||||
|
||||
private static setupClientMetadataHandler() {
|
||||
// Override fetch for client-metadata.json requests
|
||||
const originalFetch = window.fetch;
|
||||
|
||||
window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = typeof input === 'string' ? input : input.toString();
|
||||
|
||||
// Only intercept local OAuth endpoints
|
||||
try {
|
||||
const urlObj = new URL(url, window.location.origin);
|
||||
|
||||
// Only intercept requests to the same origin
|
||||
if (urlObj.origin !== window.location.origin) {
|
||||
// Pass through external API calls unchanged
|
||||
return originalFetch(input, init);
|
||||
}
|
||||
|
||||
// Handle local OAuth endpoints
|
||||
if (urlObj.pathname.endsWith('/client-metadata.json')) {
|
||||
const metadata = generateClientMetadata();
|
||||
return new Response(JSON.stringify(metadata, null, 2), {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (urlObj.pathname.endsWith('/.well-known/jwks.json')) {
|
||||
try {
|
||||
const jwks = await OAuthKeyManager.getJWKS();
|
||||
return new Response(JSON.stringify(jwks, null, 2), {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
return new Response(JSON.stringify({ error: 'Failed to generate JWKS' }), {
|
||||
status: 500,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// If URL parsing fails, pass through to original fetch
|
||||
}
|
||||
|
||||
// Pass through all other requests
|
||||
return originalFetch(input, init);
|
||||
};
|
||||
}
|
||||
|
||||
private static setupJWKSHandler() {
|
||||
// This is handled in the fetch override above
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a proper client assertion JWT for token requests
|
||||
*/
|
||||
static async generateClientAssertion(tokenEndpoint: string): Promise<string> {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const clientId = generateClientMetadata().client_id;
|
||||
|
||||
const header = {
|
||||
alg: 'ES256',
|
||||
typ: 'JWT',
|
||||
kid: 'ai-card-oauth-key-1'
|
||||
};
|
||||
|
||||
const payload = {
|
||||
iss: clientId,
|
||||
sub: clientId,
|
||||
aud: tokenEndpoint,
|
||||
iat: now,
|
||||
exp: now + 300, // 5 minutes
|
||||
jti: crypto.randomUUID()
|
||||
};
|
||||
|
||||
return await OAuthKeyManager.signJWT(header, payload);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Service Worker alternative for intercepting requests
|
||||
* (This is a more robust solution for production)
|
||||
*/
|
||||
export function registerOAuthServiceWorker() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
const swCode = `
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const url = new URL(event.request.url);
|
||||
|
||||
if (url.pathname.endsWith('/client-metadata.json')) {
|
||||
event.respondWith(
|
||||
new Response(JSON.stringify({
|
||||
client_id: url.origin + '/client-metadata.json',
|
||||
client_name: 'ai.card',
|
||||
client_uri: url.origin,
|
||||
redirect_uris: [url.origin + '/oauth/callback'],
|
||||
response_types: ['code'],
|
||||
grant_types: ['authorization_code', 'refresh_token'],
|
||||
token_endpoint_auth_method: 'private_key_jwt',
|
||||
scope: 'atproto transition:generic',
|
||||
subject_type: 'public',
|
||||
application_type: 'web',
|
||||
dpop_bound_access_tokens: true,
|
||||
jwks_uri: url.origin + '/.well-known/jwks.json'
|
||||
}, null, 2), {
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
`;
|
||||
|
||||
const blob = new Blob([swCode], { type: 'application/javascript' });
|
||||
const swUrl = URL.createObjectURL(blob);
|
||||
|
||||
}
|
||||
}
|
181
oauth/src/utils/oauth-keys.ts
Normal file
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* OAuth JWKS key generation and management
|
||||
*/
|
||||
|
||||
export interface JWK {
|
||||
kty: string;
|
||||
crv: string;
|
||||
x: string;
|
||||
y: string;
|
||||
d?: string;
|
||||
use: string;
|
||||
kid: string;
|
||||
alg: string;
|
||||
}
|
||||
|
||||
export interface JWKS {
|
||||
keys: JWK[];
|
||||
}
|
||||
|
||||
export class OAuthKeyManager {
|
||||
private static keyPair: CryptoKeyPair | null = null;
|
||||
private static jwks: JWKS | null = null;
|
||||
|
||||
/**
|
||||
* Generate or retrieve existing ECDSA key pair for OAuth
|
||||
*/
|
||||
static async getKeyPair(): Promise<CryptoKeyPair> {
|
||||
if (this.keyPair) {
|
||||
return this.keyPair;
|
||||
}
|
||||
|
||||
// Try to load from localStorage first
|
||||
const storedKey = localStorage.getItem('oauth_private_key');
|
||||
if (storedKey) {
|
||||
try {
|
||||
const keyData = JSON.parse(storedKey);
|
||||
this.keyPair = await this.importKeyPair(keyData);
|
||||
return this.keyPair;
|
||||
} catch (error) {
|
||||
localStorage.removeItem('oauth_private_key');
|
||||
}
|
||||
}
|
||||
|
||||
// Generate new key pair
|
||||
this.keyPair = await window.crypto.subtle.generateKey(
|
||||
{
|
||||
name: 'ECDSA',
|
||||
namedCurve: 'P-256',
|
||||
},
|
||||
true, // extractable
|
||||
['sign', 'verify']
|
||||
);
|
||||
|
||||
// Store private key for persistence
|
||||
await this.storeKeyPair(this.keyPair);
|
||||
|
||||
return this.keyPair;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get JWKS (JSON Web Key Set) for public key distribution
|
||||
*/
|
||||
static async getJWKS(): Promise<JWKS> {
|
||||
if (this.jwks) {
|
||||
return this.jwks;
|
||||
}
|
||||
|
||||
const keyPair = await this.getKeyPair();
|
||||
const publicKey = await window.crypto.subtle.exportKey('jwk', keyPair.publicKey);
|
||||
|
||||
this.jwks = {
|
||||
keys: [
|
||||
{
|
||||
kty: publicKey.kty!,
|
||||
crv: publicKey.crv!,
|
||||
x: publicKey.x!,
|
||||
y: publicKey.y!,
|
||||
use: 'sig',
|
||||
kid: 'ai-card-oauth-key-1',
|
||||
alg: 'ES256'
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
return this.jwks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a JWT with the private key
|
||||
*/
|
||||
static async signJWT(header: any, payload: any): Promise<string> {
|
||||
const keyPair = await this.getKeyPair();
|
||||
|
||||
const headerB64 = btoa(JSON.stringify(header)).replace(/=/g, '');
|
||||
const payloadB64 = btoa(JSON.stringify(payload)).replace(/=/g, '');
|
||||
const message = `${headerB64}.${payloadB64}`;
|
||||
|
||||
const signature = await window.crypto.subtle.sign(
|
||||
{ name: 'ECDSA', hash: 'SHA-256' },
|
||||
keyPair.privateKey,
|
||||
new TextEncoder().encode(message)
|
||||
);
|
||||
|
||||
const signatureB64 = btoa(String.fromCharCode(...new Uint8Array(signature)))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
|
||||
return `${message}.${signatureB64}`;
|
||||
}
|
||||
|
||||
private static async storeKeyPair(keyPair: CryptoKeyPair): Promise<void> {
|
||||
try {
|
||||
const privateKey = await window.crypto.subtle.exportKey('jwk', keyPair.privateKey);
|
||||
localStorage.setItem('oauth_private_key', JSON.stringify(privateKey));
|
||||
} catch (error) {
|
||||
}
|
||||
}
|
||||
|
||||
private static async importKeyPair(keyData: any): Promise<CryptoKeyPair> {
|
||||
const privateKey = await window.crypto.subtle.importKey(
|
||||
'jwk',
|
||||
keyData,
|
||||
{ name: 'ECDSA', namedCurve: 'P-256' },
|
||||
true,
|
||||
['sign']
|
||||
);
|
||||
|
||||
// Derive public key from private key
|
||||
const publicKeyData = { ...keyData };
|
||||
delete publicKeyData.d; // Remove private component
|
||||
|
||||
const publicKey = await window.crypto.subtle.importKey(
|
||||
'jwk',
|
||||
publicKeyData,
|
||||
{ name: 'ECDSA', namedCurve: 'P-256' },
|
||||
true,
|
||||
['verify']
|
||||
);
|
||||
|
||||
return { privateKey, publicKey };
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear stored keys (for testing/reset)
|
||||
*/
|
||||
static clearKeys(): void {
|
||||
localStorage.removeItem('oauth_private_key');
|
||||
this.keyPair = null;
|
||||
this.jwks = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate dynamic client metadata based on current URL
|
||||
*/
|
||||
export function generateClientMetadata(): any {
|
||||
// Use environment variables if available, fallback to current origin
|
||||
const host = import.meta.env.VITE_APP_HOST || window.location.origin;
|
||||
const clientId = import.meta.env.VITE_OAUTH_CLIENT_ID || `${host}/client-metadata.json`;
|
||||
const redirectUri = import.meta.env.VITE_OAUTH_REDIRECT_URI || `${host}/oauth/callback`;
|
||||
|
||||
return {
|
||||
client_id: clientId,
|
||||
client_name: 'ai.card',
|
||||
client_uri: host,
|
||||
logo_uri: `${host}/favicon.ico`,
|
||||
tos_uri: `${host}/terms`,
|
||||
policy_uri: `${host}/privacy`,
|
||||
redirect_uris: [redirectUri, host],
|
||||
response_types: ['code'],
|
||||
grant_types: ['authorization_code', 'refresh_token'],
|
||||
token_endpoint_auth_method: 'private_key_jwt',
|
||||
token_endpoint_auth_signing_alg: 'ES256',
|
||||
scope: 'atproto transition:generic',
|
||||
subject_type: 'public',
|
||||
application_type: 'web',
|
||||
dpop_bound_access_tokens: true,
|
||||
jwks_uri: `${host}/.well-known/jwks.json`
|
||||
};
|
||||
}
|
348
oauth/src/utils/pds-detection.ts
Normal file
@@ -0,0 +1,348 @@
|
||||
// PDS Detection and API URL mapping utilities
|
||||
|
||||
import { isValidDid, isValidHandle } from './validation';
|
||||
|
||||
export interface NetworkConfig {
|
||||
pdsApi: string;
|
||||
plcApi: string;
|
||||
bskyApi: string;
|
||||
webUrl: string;
|
||||
}
|
||||
|
||||
// Detect PDS from handle
|
||||
export function detectPdsFromHandle(handle: string): string {
|
||||
// Get allowed handles from environment
|
||||
const allowedHandlesStr = import.meta.env.VITE_ATPROTO_HANDLE_LIST || '[]';
|
||||
let allowedHandles: string[] = [];
|
||||
try {
|
||||
allowedHandles = JSON.parse(allowedHandlesStr);
|
||||
} catch {
|
||||
allowedHandles = [];
|
||||
}
|
||||
|
||||
// Get configured PDS from environment
|
||||
const configuredPds = import.meta.env.VITE_ATPROTO_PDS || 'syu.is';
|
||||
|
||||
// Check if handle is in allowed list
|
||||
if (allowedHandles.includes(handle)) {
|
||||
return configuredPds;
|
||||
}
|
||||
|
||||
// Check if handle ends with .syu.is or .syui.ai
|
||||
if (handle.endsWith('.syu.is') || handle.endsWith('.syui.ai')) {
|
||||
return 'syu.is';
|
||||
}
|
||||
|
||||
// Check if handle ends with .bsky.social or .bsky.app
|
||||
if (handle.endsWith('.bsky.social') || handle.endsWith('.bsky.app')) {
|
||||
return 'bsky.social';
|
||||
}
|
||||
|
||||
// Default to Bluesky for unknown domains
|
||||
return 'bsky.social';
|
||||
}
|
||||
|
||||
// Map PDS endpoint to network configuration
|
||||
export function getNetworkConfigFromPdsEndpoint(pdsEndpoint: string): NetworkConfig {
|
||||
try {
|
||||
const url = new URL(pdsEndpoint);
|
||||
const hostname = url.hostname;
|
||||
|
||||
// Map based on actual PDS endpoint
|
||||
if (hostname === 'syu.is') {
|
||||
return {
|
||||
pdsApi: 'https://syu.is', // PDS API (repo operations)
|
||||
plcApi: 'https://plc.syu.is', // PLC directory
|
||||
bskyApi: 'https://bsky.syu.is', // Bluesky API (getProfile, etc.)
|
||||
webUrl: 'https://web.syu.is' // Web interface
|
||||
};
|
||||
} else if (hostname.includes('bsky.network') || hostname === 'bsky.social' || hostname.includes('host.bsky.network')) {
|
||||
// All Bluesky infrastructure (including *.host.bsky.network)
|
||||
return {
|
||||
pdsApi: pdsEndpoint, // Use actual PDS endpoint (e.g., shiitake.us-east.host.bsky.network)
|
||||
plcApi: 'https://plc.directory', // Standard PLC directory
|
||||
bskyApi: 'https://public.api.bsky.app', // Bluesky public API (NOT PDS)
|
||||
webUrl: 'https://bsky.app' // Bluesky web interface
|
||||
};
|
||||
} else {
|
||||
// Unknown PDS, assume Bluesky-compatible but use PDS for repo operations
|
||||
return {
|
||||
pdsApi: pdsEndpoint, // Use actual PDS for repo ops
|
||||
plcApi: 'https://plc.directory', // Default PLC
|
||||
bskyApi: 'https://public.api.bsky.app', // Default to Bluesky API
|
||||
webUrl: 'https://bsky.app' // Default web interface
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
// Fallback for invalid URLs
|
||||
return {
|
||||
pdsApi: 'https://bsky.social',
|
||||
plcApi: 'https://plc.directory',
|
||||
bskyApi: 'https://public.api.bsky.app',
|
||||
webUrl: 'https://bsky.app'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy function for backwards compatibility
|
||||
export function getNetworkConfig(pds: string): NetworkConfig {
|
||||
// This now assumes pds is a hostname
|
||||
return getNetworkConfigFromPdsEndpoint(`https://${pds}`);
|
||||
}
|
||||
|
||||
// Get appropriate API URL for a user based on their handle
|
||||
export function getApiUrlForUser(handle: string): string {
|
||||
const pds = detectPdsFromHandle(handle);
|
||||
const config = getNetworkConfig(pds);
|
||||
return config.bskyApi;
|
||||
}
|
||||
|
||||
// Resolve handle/DID to actual PDS endpoint using PLC API first
|
||||
export async function resolvePdsFromRepo(handleOrDid: string): Promise<{ pds: string; did: string; handle: string }> {
|
||||
// Validate input
|
||||
if (!handleOrDid || (!isValidDid(handleOrDid) && !isValidHandle(handleOrDid))) {
|
||||
throw new Error(`Invalid identifier: ${handleOrDid}`);
|
||||
}
|
||||
|
||||
let targetDid = handleOrDid;
|
||||
let targetHandle = handleOrDid;
|
||||
|
||||
// If handle provided, resolve to DID first using identity.resolveHandle
|
||||
if (!handleOrDid.startsWith('did:')) {
|
||||
try {
|
||||
// Try multiple endpoints for handle resolution
|
||||
const resolveEndpoints = ['https://public.api.bsky.app', 'https://bsky.syu.is', 'https://syu.is'];
|
||||
let resolved = false;
|
||||
|
||||
for (const endpoint of resolveEndpoints) {
|
||||
try {
|
||||
const resolveResponse = await fetch(`${endpoint}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handleOrDid)}`);
|
||||
if (resolveResponse.ok) {
|
||||
const resolveData = await resolveResponse.json();
|
||||
targetDid = resolveData.did;
|
||||
resolved = true;
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (!resolved) {
|
||||
throw new Error('Handle resolution failed from all endpoints');
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to resolve handle ${handleOrDid} to DID: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
// First, try PLC API to get the authoritative DID document
|
||||
const plcApis = ['https://plc.directory', 'https://plc.syu.is'];
|
||||
|
||||
for (const plcApi of plcApis) {
|
||||
try {
|
||||
const plcResponse = await fetch(`${plcApi}/${targetDid}`);
|
||||
if (plcResponse.ok) {
|
||||
const didDocument = await plcResponse.json();
|
||||
|
||||
// Find PDS service in DID document
|
||||
const pdsService = didDocument.service?.find((s: any) =>
|
||||
s.id === '#atproto_pds' || s.type === 'AtprotoPersonalDataServer'
|
||||
);
|
||||
|
||||
if (pdsService && pdsService.serviceEndpoint) {
|
||||
return {
|
||||
pds: pdsService.serviceEndpoint,
|
||||
did: targetDid,
|
||||
handle: targetHandle
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: use com.atproto.repo.describeRepo to get PDS from known PDS endpoints
|
||||
const pdsEndpoints = ['https://bsky.social', 'https://syu.is'];
|
||||
|
||||
for (const pdsEndpoint of pdsEndpoints) {
|
||||
try {
|
||||
const response = await fetch(`${pdsEndpoint}/xrpc/com.atproto.repo.describeRepo?repo=${encodeURIComponent(targetDid)}`);
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
|
||||
// Extract PDS from didDoc.service
|
||||
const services = data.didDoc?.service || [];
|
||||
const pdsService = services.find((s: any) =>
|
||||
s.id === '#atproto_pds' || s.type === 'AtprotoPersonalDataServer'
|
||||
);
|
||||
|
||||
if (pdsService) {
|
||||
return {
|
||||
pds: pdsService.serviceEndpoint,
|
||||
did: data.did || targetDid,
|
||||
handle: data.handle || targetHandle
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Failed to resolve PDS for ${handleOrDid} from any endpoint`);
|
||||
}
|
||||
|
||||
// Resolve DID to actual PDS endpoint using com.atproto.repo.describeRepo
|
||||
export async function resolvePdsFromDid(did: string): Promise<string> {
|
||||
const resolved = await resolvePdsFromRepo(did);
|
||||
return resolved.pds;
|
||||
}
|
||||
|
||||
// Enhanced resolve handle to DID with proper PDS detection
|
||||
export async function resolveHandleToDid(handle: string): Promise<{ did: string; pds: string }> {
|
||||
try {
|
||||
// First, try to resolve the handle to DID using multiple methods
|
||||
const apiUrl = getApiUrlForUser(handle);
|
||||
const response = await fetch(`${apiUrl}/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(handle)}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to resolve handle: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const did = data.did;
|
||||
|
||||
// Now resolve the actual PDS from the DID
|
||||
const actualPds = await resolvePdsFromDid(did);
|
||||
|
||||
return {
|
||||
did: did,
|
||||
pds: actualPds
|
||||
};
|
||||
} catch (error) {
|
||||
// Failed to resolve handle
|
||||
|
||||
// Fallback to handle-based detection
|
||||
const fallbackPds = detectPdsFromHandle(handle);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Get profile using appropriate API for the user with accurate PDS resolution
|
||||
export async function getProfileForUser(handleOrDid: string, knownPdsEndpoint?: string): Promise<any> {
|
||||
try {
|
||||
let apiUrl: string;
|
||||
|
||||
if (knownPdsEndpoint) {
|
||||
// If we already know the user's PDS endpoint, use it directly
|
||||
const config = getNetworkConfigFromPdsEndpoint(knownPdsEndpoint);
|
||||
apiUrl = config.bskyApi;
|
||||
} else {
|
||||
// Resolve the user's actual PDS using describeRepo
|
||||
try {
|
||||
const resolved = await resolvePdsFromRepo(handleOrDid);
|
||||
const config = getNetworkConfigFromPdsEndpoint(resolved.pds);
|
||||
apiUrl = config.bskyApi;
|
||||
} catch {
|
||||
// Fallback to handle-based detection
|
||||
apiUrl = getApiUrlForUser(handleOrDid);
|
||||
}
|
||||
}
|
||||
|
||||
const response = await fetch(`${apiUrl}/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(handleOrDid)}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get profile: ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
// Failed to get profile
|
||||
|
||||
// Final fallback: try with default Bluesky API
|
||||
try {
|
||||
const response = await fetch(`https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(handleOrDid)}`);
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
}
|
||||
} catch {
|
||||
// Ignore fallback errors
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Test and verify PDS detection methods
|
||||
export async function verifyPdsDetection(handleOrDid: string): Promise<void> {
|
||||
try {
|
||||
// Method 1: com.atproto.repo.describeRepo (PRIMARY METHOD)
|
||||
try {
|
||||
const resolved = await resolvePdsFromRepo(handleOrDid);
|
||||
const config = getNetworkConfigFromPdsEndpoint(resolved.pds);
|
||||
} catch (error) {
|
||||
// describeRepo failed
|
||||
}
|
||||
|
||||
// Method 2: com.atproto.identity.resolveHandle (for comparison)
|
||||
if (!handleOrDid.startsWith('did:')) {
|
||||
try {
|
||||
const resolveResponse = await fetch(`https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handleOrDid)}`);
|
||||
if (resolveResponse.ok) {
|
||||
const resolveData = await resolveResponse.json();
|
||||
}
|
||||
} catch (error) {
|
||||
// Error resolving handle
|
||||
}
|
||||
}
|
||||
|
||||
// Method 3: PLC Directory lookup (if we have a DID)
|
||||
let targetDid = handleOrDid;
|
||||
if (!handleOrDid.startsWith('did:')) {
|
||||
try {
|
||||
const profile = await getProfileForUser(handleOrDid);
|
||||
targetDid = profile.did;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const plcResponse = await fetch(`https://plc.directory/${targetDid}`);
|
||||
if (plcResponse.ok) {
|
||||
const didDocument = await plcResponse.json();
|
||||
|
||||
// Find PDS service
|
||||
const pdsService = didDocument.service?.find((s: any) =>
|
||||
s.id === '#atproto_pds' || s.type === 'AtprotoPersonalDataServer'
|
||||
);
|
||||
|
||||
if (pdsService) {
|
||||
// Try to detect if this is a known network
|
||||
const pdsUrl = pdsService.serviceEndpoint;
|
||||
const hostname = new URL(pdsUrl).hostname;
|
||||
const detectedNetwork = detectPdsFromHandle(`user.${hostname}`);
|
||||
const networkConfig = getNetworkConfig(hostname);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Error fetching from PLC directory
|
||||
}
|
||||
|
||||
// Method 4: Our enhanced resolution
|
||||
try {
|
||||
if (handleOrDid.startsWith('did:')) {
|
||||
const pdsEndpoint = await resolvePdsFromDid(handleOrDid);
|
||||
} else {
|
||||
const resolved = await resolveHandleToDid(handleOrDid);
|
||||
}
|
||||
} catch (error) {
|
||||
// Enhanced resolution failed
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
// Overall verification failed
|
||||
}
|
||||
}
|
21
oauth/src/utils/validation.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
// Validation utilities for atproto identifiers
|
||||
|
||||
export function isValidDid(did: string): boolean {
|
||||
if (!did || typeof did !== 'string') return false;
|
||||
|
||||
// Basic DID format: did:method:identifier
|
||||
const didRegex = /^did:[a-z]+:[a-zA-Z0-9._%-]+$/;
|
||||
return didRegex.test(did);
|
||||
}
|
||||
|
||||
export function isValidHandle(handle: string): boolean {
|
||||
if (!handle || typeof handle !== 'string') return false;
|
||||
|
||||
// Basic handle format: subdomain.domain.tld
|
||||
const handleRegex = /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
|
||||
return handleRegex.test(handle);
|
||||
}
|
||||
|
||||
export function isValidAtprotoIdentifier(identifier: string): boolean {
|
||||
return isValidDid(identifier) || isValidHandle(identifier);
|
||||
}
|
21
oauth/tsconfig.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
11
oauth/tsconfig.node.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
88
oauth/vite.config.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
// Load env file based on `mode` in the current working directory.
|
||||
const env = loadEnv(mode, process.cwd(), '')
|
||||
|
||||
return {
|
||||
plugins: [
|
||||
react(),
|
||||
// Custom plugin to replace variables in public files during build
|
||||
{
|
||||
name: 'replace-env-vars',
|
||||
writeBundle() {
|
||||
const host = env.VITE_APP_HOST || 'https://log.syui.ai'
|
||||
const clientId = env.VITE_OAUTH_CLIENT_ID || `${host}/client-metadata.json`
|
||||
const redirectUri = env.VITE_OAUTH_REDIRECT_URI || `${host}/oauth/callback`
|
||||
|
||||
// Replace variables in client-metadata.json
|
||||
const clientMetadataPath = path.resolve(__dirname, 'dist/client-metadata.json')
|
||||
if (fs.existsSync(clientMetadataPath)) {
|
||||
let content = fs.readFileSync(clientMetadataPath, 'utf-8')
|
||||
content = content.replace(/https:\/\/log\.syui\.ai/g, host)
|
||||
fs.writeFileSync(clientMetadataPath, content)
|
||||
console.log(`Updated client-metadata.json with host: ${host}`)
|
||||
}
|
||||
}
|
||||
},
|
||||
// Generate standalone index.html for testing
|
||||
{
|
||||
name: 'generate-standalone-html',
|
||||
writeBundle(options, bundle) {
|
||||
// Find actual generated filenames
|
||||
const jsFile = Object.keys(bundle).find(fileName => fileName.startsWith('assets/comment-atproto') && fileName.endsWith('.js'))
|
||||
const cssFile = Object.keys(bundle).find(fileName => fileName.startsWith('assets/comment-atproto') && fileName.endsWith('.css'))
|
||||
|
||||
// Generate minimal index.html with just asset references
|
||||
const indexHtmlPath = path.resolve(__dirname, 'dist/index.html')
|
||||
const indexHtmlContent = `<!-- OAuth Comment System - Load globally for session management -->
|
||||
<script type="module" crossorigin src="/${jsFile}"></script>
|
||||
<link rel="stylesheet" crossorigin href="/${cssFile}">`
|
||||
fs.writeFileSync(indexHtmlPath, indexHtmlContent)
|
||||
console.log('Generated minimal index.html with asset references')
|
||||
}
|
||||
}
|
||||
],
|
||||
build: {
|
||||
// Keep console.log in production for debugging
|
||||
minify: 'esbuild',
|
||||
rollupOptions: {
|
||||
output: {
|
||||
// Hash-based filenames to bust cache
|
||||
entryFileNames: 'assets/comment-atproto-[hash].js',
|
||||
chunkFileNames: 'assets/comment-atproto-[name]-[hash].js',
|
||||
assetFileNames: (assetInfo) => {
|
||||
if (assetInfo.name && assetInfo.name.endsWith('.css')) {
|
||||
return 'assets/comment-atproto-[hash].css';
|
||||
}
|
||||
return 'assets/[name]-[hash].[ext]';
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
esbuild: {
|
||||
drop: [], // Don't drop console.log
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
host: '127.0.0.1',
|
||||
allowedHosts: ['localhost', '127.0.0.1', 'log.syui.ai'],
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://127.0.0.1:8000',
|
||||
changeOrigin: true,
|
||||
secure: false,
|
||||
}
|
||||
},
|
||||
// Handle OAuth callback routing
|
||||
historyApiFallback: {
|
||||
rewrites: [
|
||||
{ from: /^\/oauth\/callback/, to: '/index.html' }
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
10
oauth_new/.env.production
Normal file
@@ -0,0 +1,10 @@
|
||||
VITE_ADMIN=ai.syui.ai
|
||||
VITE_PDS=syu.is
|
||||
VITE_HANDLE_LIST=["ai.syui.ai", "syui.syui.ai", "ai.ai"]
|
||||
VITE_COLLECTION=ai.syui.log
|
||||
VITE_OAUTH_CLIENT_ID=https://syui.ai/client-metadata.json
|
||||
VITE_OAUTH_REDIRECT_URI=https://syui.ai/oauth/callback
|
||||
|
||||
# Production settings - Disable development features
|
||||
VITE_ENABLE_TEST_UI=false
|
||||
VITE_ENABLE_DEBUG=false
|
116
oauth_new/ASK_AI_INTEGRATION.md
Normal file
@@ -0,0 +1,116 @@
|
||||
# Ask-AI Integration Implementation
|
||||
|
||||
## 概要
|
||||
|
||||
oauth_new アプリに ask-AI 機能を統合しました。この機能により、ユーザーはAIと対話し、その結果を atproto に記録できます。
|
||||
|
||||
## 実装されたファイル
|
||||
|
||||
### 1. `/src/hooks/useAskAI.js`
|
||||
- ask-AI サーバーとの通信機能
|
||||
- atproto への putRecord 機能
|
||||
- チャット履歴の管理
|
||||
- イベント送信(blog との通信用)
|
||||
|
||||
### 2. `/src/components/AskAI.jsx`
|
||||
- チャット UI コンポーネント
|
||||
- 質問入力・回答表示
|
||||
- 認証チェック
|
||||
- IME 対応
|
||||
|
||||
### 3. `/src/App.jsx` の更新
|
||||
- AskAI コンポーネントの統合
|
||||
- Ask AI ボタンの追加
|
||||
- イベントリスナーの設定
|
||||
- blog との通信機能
|
||||
|
||||
## JSON 構造の記録
|
||||
|
||||
`./json/` ディレクトリに各 collection の構造を記録しました:
|
||||
|
||||
- `ai.syui.ai_user.json` - ユーザーリスト
|
||||
- `ai.syui.ai_chat.json` - チャット記録(空)
|
||||
- `syui.syui.ai_chat.json` - チャット記録(実データ)
|
||||
- `ai.syui.ai_chat_lang.json` - 翻訳記録
|
||||
- `ai.syui.ai_chat_comment.json` - コメント記録
|
||||
|
||||
## 実際の ai.syui.log.chat 構造
|
||||
|
||||
確認された実際の構造:
|
||||
|
||||
```json
|
||||
{
|
||||
"$type": "ai.syui.log.chat",
|
||||
"post": {
|
||||
"url": "https://syui.ai/",
|
||||
"date": "2025-06-18T02:16:04.609Z",
|
||||
"slug": "",
|
||||
"tags": [],
|
||||
"title": "syui.ai",
|
||||
"language": "ja"
|
||||
},
|
||||
"text": "質問またはAI回答テキスト",
|
||||
"type": "question|answer",
|
||||
"author": {
|
||||
"did": "did:plc:...",
|
||||
"handle": "handle名",
|
||||
"displayName": "表示名",
|
||||
"avatar": "アバターURL"
|
||||
},
|
||||
"createdAt": "2025-06-18T02:16:04.609Z"
|
||||
}
|
||||
```
|
||||
|
||||
## イベント通信
|
||||
|
||||
blog(ask-ai.js)と OAuth アプリ間の通信:
|
||||
|
||||
### 送信イベント
|
||||
- `postAIQuestion` - blog から OAuth アプリへ質問送信
|
||||
- `aiProfileLoaded` - OAuth アプリから blog へ AI プロフィール送信
|
||||
- `aiResponseReceived` - OAuth アプリから blog へ AI 回答送信
|
||||
|
||||
### 受信イベント
|
||||
- OAuth アプリが `postAIQuestion` を受信して処理
|
||||
- blog が `aiResponseReceived` を受信して表示
|
||||
|
||||
## 環境変数
|
||||
|
||||
```env
|
||||
VITE_ASK_AI_URL=http://localhost:3000/ask # ask-AI サーバーURL(デフォルト)
|
||||
VITE_ADMIN_HANDLE=ai.syui.ai
|
||||
VITE_ATPROTO_PDS=syu.is
|
||||
VITE_OAUTH_COLLECTION=ai.syui.log
|
||||
```
|
||||
|
||||
## 機能
|
||||
|
||||
### 実装済み
|
||||
- ✅ ask-AI サーバーとの通信
|
||||
- ✅ atproto への question/answer record 保存
|
||||
- ✅ チャット履歴の表示・管理
|
||||
- ✅ blog との双方向イベント通信
|
||||
- ✅ 認証機能(ログイン必須)
|
||||
- ✅ エラーハンドリング・ローディング状態
|
||||
- ✅ 実際の JSON 構造に合わせた実装
|
||||
|
||||
### 今後のテスト項目
|
||||
- ask-AI サーバーの準備・起動
|
||||
- 実際の質問送信テスト
|
||||
- atproto への putRecord 動作確認
|
||||
- blog からの連携テスト
|
||||
|
||||
## 使用方法
|
||||
|
||||
1. 開発サーバー起動: `npm run dev`
|
||||
2. OAuth ログイン実行
|
||||
3. "Ask AI" ボタンをクリック
|
||||
4. チャット画面で質問入力
|
||||
5. AI の回答が表示され、atproto に記録される
|
||||
|
||||
## 注意事項
|
||||
|
||||
- ask-AI サーバー(VITE_ASK_AI_URL)が必要
|
||||
- 認証されたユーザーのみ質問可能
|
||||
- ai.syui.log.chat への書き込み権限が必要
|
||||
- Production 環境では logger が無効化される
|