diff --git a/.claude/settings.local.json b/.claude/settings.local.json index 92f1163..c12c301 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -54,7 +54,10 @@ "mcp__context7__get-library-docs", "Bash(npm run init-mariadb:*)", "Bash(npm test)", - "Bash(npm run build:*)" + "Bash(npm run build:*)", + "Bash(npm run stop:*)", + "Bash(PORT=3007 node server.js)", + "Bash(HOST=119.64.1.86 PORT=3007 node server.js)" ], "deny": [], "ask": [], diff --git a/CLAUDE.md b/CLAUDE.md index 5c278c7..48898df 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,146 +1,34 @@ -# CLAUDE.md +--- +allowed-tools: [Read, Grep, Glob, Bash, Edit, MultiEdit] +description: "Clean up code, remove dead code, and optimize project structure" +--- -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. +# /sc:cleanup - Code and Project Cleanup -## Project Overview - -This is a web-based file management system (자료실) with full CRUD functionality. It's a hybrid application built with vanilla HTML, CSS, and JavaScript that supports both Supabase cloud database and localStorage for data persistence, providing seamless offline/online capabilities. - -### Key Features -- Create, Read, Update, Delete operations for file records -- File upload with multiple file support (local + cloud storage) -- User authentication and authorization -- Search and filtering by title, description, tags, and category -- Categorization system (문서, 이미지, 동영상, 프레젠테이션, 기타) -- Tag-based organization -- Responsive design for mobile and desktop -- Modal-based editing interface -- Cloud database with real-time synchronization -- Offline support with localStorage fallback -- Cross-device data synchronization - -## File Structure +## Purpose +Systematically clean up code, remove dead code, optimize imports, and improve project structure. +## Usage ``` -자료실/ -├── index.html # Main HTML file with UI structure and auth components -├── styles.css # Complete styling with responsive design and auth styles -├── script.js # Core JavaScript with FileManager class and Supabase integration -├── supabase-config.js # Supabase configuration and helper functions -├── supabase-schema.sql # Database schema for Supabase setup -├── setup-guide.md # Comprehensive Supabase setup guide -└── CLAUDE.md # This documentation file +/sc:cleanup [target] [--type code|imports|files|all] [--safe|--aggressive] [--dry-run] ``` -## Architecture +## Arguments +- `target` - Files, directories, or entire project to clean +- `--type` - Cleanup type (code, imports, files, all) +- `--safe` - Conservative cleanup (default) +- `--aggressive` - More thorough cleanup with higher risk +- `--dry-run` - Preview changes without applying them -### Core Components +## Execution +1. Analyze target for cleanup opportunities +2. Identify dead code, unused imports, and redundant files +3. Create cleanup plan with risk assessment +4. Execute cleanup operations with appropriate safety measures +5. Validate changes and report cleanup results -1. **FileManager Class** (`script.js`) - - Main application controller with hybrid storage support - - Handles all CRUD operations (Supabase + localStorage fallback) - - Manages user authentication and session state - - Contains event handling and UI updates - - Real-time synchronization capabilities - -2. **Supabase Integration** (`supabase-config.js`) - - Database configuration and connection management - - Authentication helper functions (signup, login, logout) - - CRUD helper functions for files and attachments - - Storage helper functions for file uploads/downloads - - Real-time subscription management - -3. **Data Model** - ```javascript - // Files table - { - id: UUID, // Primary key - title: string, // File title (required) - description: string, // Optional description - category: string, // Required category - tags: string[], // Array of tags - user_id: UUID, // Foreign key to auth.users - created_at: timestamp, - updated_at: timestamp - } - - // File attachments table - { - id: UUID, - file_id: UUID, // Foreign key to files - original_name: string, - storage_path: string, // Supabase Storage path - file_size: integer, - mime_type: string, - created_at: timestamp - } - ``` - -4. **UI Components** - - Authentication section (login/signup/logout) - - Sync status indicator - - Search and filter section - - Add new file form with cloud upload - - File list display with sorting - - Edit modal for updates - - Responsive card-based layout - - Offline mode notifications - -### Development Commands - -This is a hybrid web application supporting both online and offline modes: - -1. **Local Development** - ```bash - # Open index.html in a web browser - # OR use a simple HTTP server: - python -m http.server 8000 - # OR - npx serve . - ``` - -2. **Supabase Setup (Required for online features)** - ```bash - # 1. Follow setup-guide.md for complete setup - # 2. Create Supabase project and database - # 3. Run supabase-schema.sql in SQL Editor - # 4. Create Storage bucket named 'files' - # 5. Update supabase-config.js with your credentials - ``` - -3. **File Access** - - Open `index.html` directly in browser - - Works offline with localStorage (limited functionality) - - Full features available with Supabase configuration - -### Technical Implementation - -- **Database**: Supabase PostgreSQL with Row Level Security (RLS) -- **Storage**: Supabase Storage for files + localStorage fallback -- **Authentication**: Supabase Auth with email/password -- **Real-time**: Supabase Realtime for live synchronization -- **File Handling**: FileReader API + Supabase Storage API -- **UI Updates**: Vanilla JavaScript DOM manipulation -- **Styling**: CSS Grid and Flexbox for responsive layouts -- **Animations**: CSS transitions and keyframe animations -- **Offline Support**: Automatic fallback to localStorage when offline - -### Data Management - -- **Online Mode**: Files stored in Supabase PostgreSQL + Storage -- **Offline Mode**: Files stored as base64 strings in localStorage -- **Hybrid Sync**: Automatic synchronization when connection restored -- User-specific data isolation with RLS policies -- Search works across title, description, and tags -- Sorting available by date, title, or category -- Categories are predefined but can be extended -- Real-time updates across devices for same user - -### Browser Compatibility - -- Modern browsers with ES6+ support -- localStorage API support required -- FileReader API for file uploads -- Fetch API for Supabase communication -- WebSocket support for real-time features -- External dependency: Supabase JavaScript client library \ No newline at end of file +## Claude Code Integration +- Uses Glob for systematic file discovery +- Leverages Grep for dead code detection +- Applies MultiEdit for batch cleanup operations +- Maintains backup and rollback capabilities \ No newline at end of file diff --git a/README-MariaDB.md b/README-MariaDB.md deleted file mode 100644 index 6a43a60..0000000 --- a/README-MariaDB.md +++ /dev/null @@ -1,139 +0,0 @@ -# Jaryo File Manager - MariaDB 배포 가이드 - -## 개요 -Jaryo File Manager를 시놀로지 NAS의 MariaDB와 함께 배포하는 가이드입니다. - -## 시스템 요구사항 - -### NAS 환경 -- 시놀로지 DSM 7.0+ -- Node.js 18+ (DSM 패키지 센터에서 설치) -- MariaDB 10+ (DSM 패키지 센터에서 설치) -- Git Server (DSM 패키지 센터에서 설치) - -### 개발 환경 -- Node.js 18+ -- MariaDB/MySQL 5.7+ -- Git - -## NAS 배포 단계 - -### 1. 빠른 배포 (권장) -```bash -# 자동 배포 스크립트 실행 -./deploy-to-nas.sh [NAS-IP] jaryo [PASSWORD] - -# 예시: -./deploy-to-nas.sh 192.168.1.100 jaryo mypassword -``` - -### 2. 수동 배포 - -#### 2.1 MariaDB 설정 -NAS SSH 접속 후: -```sql -mysql -u root -p - -CREATE DATABASE IF NOT EXISTS jaryo CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; -CREATE USER 'jaryo_user'@'localhost' IDENTIFIED BY 'JaryoPass2024!@#'; -GRANT ALL PRIVILEGES ON jaryo.* TO 'jaryo_user'@'localhost'; -FLUSH PRIVILEGES; -EXIT; -``` - -#### 2.2 스키마 설정 -```bash -mysql -u jaryo_user -p jaryo < database/mariadb-schema.sql -``` - -#### 2.3 서비스 배포 -```bash -# 소스 코드 클론 -cd /volume1/web -git clone [GITEA_URL] jaryo -cd jaryo - -# 의존성 설치 -npm install - -# 데이터베이스 초기화 -npm run init-mariadb - -# 서비스 시작 -./start-service.sh -``` - -## 환경별 설정 - -### Windows 개발 환경 -`.env` 파일 생성: -```env -DB_HOST=localhost -DB_PORT=3306 -DB_USER=root -DB_PASSWORD=your_password -DB_NAME=jaryo -HOST=0.0.0.0 -PORT=3000 -``` - -### NAS 운영 환경 -환경 변수는 자동으로 설정됩니다: -- `NODE_ENV=production` -- `DEPLOY_ENV=nas` -- Unix Socket 연결: `/run/mysqld/mysqld10.sock` - -## 관리 명령어 - -### 서비스 관리 -```bash -# 시작 -./start-service.sh - -# 중지 -kill $(cat jaryo-nas.pid) - -# 로그 확인 -tail -f logs/app.log -``` - -### 데이터베이스 관리 -```bash -# 초기화 -npm run init-mariadb - -# 직접 연결 -mysql -u jaryo_user -p -S /run/mysqld/mysqld10.sock jaryo -``` - -## 접속 정보 - -### 기본 관리자 계정 -- **이메일**: admin@jaryo.com -- **비밀번호**: Hee150603! - -### 서비스 URL -- **메인**: http://[NAS-IP]:3005 -- **관리자**: http://[NAS-IP]:3005/admin - -## 문제 해결 - -### 연결 오류 -1. MariaDB 서비스 상태 확인 -2. 데이터베이스 및 사용자 권한 확인 -3. 소켓 파일 경로 확인 -4. 방화벽 설정 확인 - -### 상세 가이드 -더 자세한 설정 방법은 `mariadb-setup.md` 파일을 참조하세요. - -## 기술 스택 -- **Backend**: Node.js + Express -- **Database**: MariaDB -- **Frontend**: Vanilla JavaScript -- **Deployment**: Shell Scripts - -## 지원 -- 로그 파일: `/volume1/web/jaryo/logs/app.log` -- 설정 파일: `database/mariadb-helper.js` -- 스키마: `database/mariadb-schema.sql` \ No newline at end of file diff --git a/README_AUTO_START.md b/README_AUTO_START.md deleted file mode 100644 index c61f907..0000000 --- a/README_AUTO_START.md +++ /dev/null @@ -1,101 +0,0 @@ -# Jaryo File Manager 자동 시작 설정 가이드 - -## 🚀 자동 시작 설정 방법 - -### 방법 1: 배치 파일 실행 (권장) - -1. **관리자 권한으로 실행** - - `install-auto-startup.bat` 파일을 마우스 우클릭 - - "관리자 권한으로 실행" 선택 - - 안내에 따라 진행 - -2. **설정 완료 후** - - 컴퓨터 재시작 시 자동으로 서비스 시작 - - 서비스 URL: http://99.1.110.50:3005 - -### 방법 2: 수동 작업 스케줄러 설정 - -1. **작업 스케줄러 열기** - - Windows 키 + R → `taskschd.msc` 입력 → 엔터 - -2. **기본 작업 만들기** - - 오른쪽 패널에서 "기본 작업 만들기" 클릭 - - 이름: `JaryoFileManagerAutoStart` - - 설명: `Jaryo File Manager 자동 시작` - -3. **트리거 설정** - - "컴퓨터를 시작할 때" 선택 - -4. **동작 설정** - - "프로그램 시작" 선택 - - 프로그램/스크립트: `C:\Users\COMTREE\claude_code\jaryo\start-jaryo-service.bat` - - 시작 위치: `C:\Users\COMTREE\claude_code\jaryo` - -5. **고급 설정** - - "가장 높은 권한으로 실행" 체크 - - "작업이 이미 실행 중인 경우 규칙": "새 인스턴스 시작 안 함" - -## 🔧 서비스 관리 명령어 - -### 수동 서비스 제어 -```batch -# 서비스 시작 -start-jaryo-service.bat - -# 서비스 중지 -stop-jaryo-service.bat -``` - -### 자동 시작 관리 -```batch -# 자동 시작 설정 -install-auto-startup.bat (관리자 권한 필요) - -# 자동 시작 해제 -uninstall-auto-startup.bat (관리자 권한 필요) -``` - -### 작업 스케줄러 명령어 -```cmd -# 작업 상태 확인 -schtasks /query /tn "JaryoFileManagerAutoStart" - -# 작업 수동 실행 -schtasks /run /tn "JaryoFileManagerAutoStart" - -# 작업 삭제 -schtasks /delete /tn "JaryoFileManagerAutoStart" /f -``` - -## 🌐 접속 정보 - -- **관리자 페이지**: http://99.1.110.50:3005/admin/index.html -- **메인 페이지**: http://99.1.110.50:3005/index.html -- **API**: http://99.1.110.50:3005/api/files -- **상태 확인**: http://99.1.110.50:3005/health - -## 📁 로그 확인 - -- **로그 파일**: `C:\Users\COMTREE\claude_code\jaryo\logs\app.log` -- **로그 보기**: `type "C:\Users\COMTREE\claude_code\jaryo\logs\app.log"` - -## ⚠️ 문제 해결 - -### 서비스가 시작되지 않는 경우 -1. Node.js가 설치되어 있는지 확인: `node --version` -2. 프로젝트 디렉토리가 올바른지 확인 -3. 포트 3005가 사용 중인지 확인: `netstat -an | findstr :3005` -4. 로그 파일 확인 - -### 자동 시작이 작동하지 않는 경우 -1. 작업 스케줄러에서 작업 상태 확인 -2. 관리자 권한으로 설정했는지 확인 -3. 배치 파일 경로가 올바른지 확인 - -## 📞 지원 - -문제가 발생하면 다음을 확인해주세요: -1. 로그 파일 내용 -2. 작업 스케줄러 작업 상태 -3. 포트 사용 현황 -4. Node.js 설치 상태 \ No newline at end of file diff --git a/admin/script.js b/admin/script.js index 8ef7403..4c9efd4 100644 --- a/admin/script.js +++ b/admin/script.js @@ -1330,7 +1330,6 @@ class AdminFileManager {
diff --git a/cookies.txt b/cookies.txt deleted file mode 100644 index 5d47335..0000000 --- a/cookies.txt +++ /dev/null @@ -1,5 +0,0 @@ -# Netscape HTTP Cookie File -# https://curl.se/docs/http-cookies.html -# This file was generated by libcurl! Edit at your own risk. - -#HttpOnly_localhost FALSE / FALSE 1755922561 connect.sid s%3AmN1rJMxZAee73L5t1g-59UL0tXQP36Vr.6GJ1M%2FUaWj68J9z6Ua9MBxCG54Sl8OuOsRUQNQFlLZE diff --git a/deploy-to-nas.sh b/deploy-to-nas.sh index 6dbadd9..26a9257 100644 --- a/deploy-to-nas.sh +++ b/deploy-to-nas.sh @@ -9,13 +9,22 @@ NAS_IP="${1:-119.64.1.86}" PROJECT_NAME="${2:-jaryo}" NAS_USER="vibsin9322" -NAS_PASS="${3:-vibsin9322}" # 기본 비밀번호, 환경변수 NAS_PASS로 오버라이드 가능 +# NAS_PASS 우선순위: 환경변수 > 스크립트 3번째 인자 > 프롬프트 방식 +if [ -n "$3" ]; then + NAS_PASS="$3" +else + NAS_PASS="${NAS_PASS:-}" +fi DEPLOY_DIR="/volume1/web/$PROJECT_NAME" SERVICE_PORT="3005" GITEA_URL="http://$NAS_IP:3000/vibsin9322/jaryo.git" -# SSH 명령어 준비 -SSH_CMD="ssh -p 2222 -o ConnectTimeout=10 -o StrictHostKeyChecking=no $NAS_USER@$NAS_IP" +# SSH 명령어 준비 (NAS_PASS가 있으면 plink로 비대화식, 없으면 ssh 프롬프트) +if [ -n "$NAS_PASS" ]; then + SSH_CMD="plink -P 2222 -batch -pw \"$NAS_PASS\" $NAS_USER@$NAS_IP" +else + SSH_CMD="ssh -p 2222 -o ConnectTimeout=10 -o StrictHostKeyChecking=no $NAS_USER@$NAS_IP" +fi echo "==========================================" echo "🚀 시놀로지 NAS 자료실 배포 시작" @@ -31,8 +40,12 @@ echo "==========================================" echo "📋 1단계: 사전 요구사항 확인" # SSH 방식 확인 -echo "🔧 SSH 접속 방식: 비밀번호 프롬프트 방식" -echo "📝 SSH 연결 시 비밀번호 입력이 필요합니다." +if [ -n "$NAS_PASS" ]; then + echo "🔧 SSH 접속 방식: 비밀번호 비대화식(plink)" +else + echo "🔧 SSH 접속 방식: 비밀번호 프롬프트 방식" + echo "📝 SSH 연결 시 비밀번호 입력이 필요합니다." +fi # SSH 연결 테스트 (포트 2222) echo "🔗 SSH 연결 테스트 중... (사용자: $NAS_USER, 포트: 2222)" @@ -274,7 +287,7 @@ chmod +x '$DEPLOY_DIR/stop-nas-service.sh' echo "" echo "🎬 5단계: 서비스 시작" -eval "$SSH_CMD '$DEPLOY_DIR/start-nas-service.sh" +eval "$SSH_CMD '$DEPLOY_DIR/start-nas-service.sh'" # 6단계: 접속 테스트 echo "" @@ -303,5 +316,5 @@ if curl -s "http://$NAS_IP:$SERVICE_PORT" >/dev/null; then else echo "❌ 서비스 접속 실패" echo "로그 확인:" - eval "$SSH_CMD 'tail -20 $DEPLOY_DIR/logs/app.log" + eval "$SSH_CMD 'tail -20 $DEPLOY_DIR/logs/app.log'" fi \ No newline at end of file diff --git a/mariadb-setup.md b/mariadb-setup.md deleted file mode 100644 index affdfc8..0000000 --- a/mariadb-setup.md +++ /dev/null @@ -1,130 +0,0 @@ -# 시놀로지 NAS MariaDB 설정 가이드 - -## 1. MariaDB 패키지 설치 - -1. **DSM 패키지 센터** 열기 -2. **MariaDB 10** 검색 및 설치 -3. 설치 완료 후 **실행** - -## 2. MariaDB 초기 설정 - -### 2.1 MariaDB 관리 도구 접속 -- DSM에서 **MariaDB 10** 앱 실행 -- 또는 웹 브라우저에서 `http://NAS-IP:3307` 접속 - -### 2.2 관리자 계정으로 로그인 -- 사용자: `root` -- 비밀번호: 설치 시 설정한 비밀번호 - -## 3. 자료실 데이터베이스 설정 - -### 3.1 데이터베이스 생성 -```sql -CREATE DATABASE IF NOT EXISTS jaryo -CHARACTER SET utf8mb4 -COLLATE utf8mb4_unicode_ci; -``` - -### 3.2 전용 사용자 생성 -```sql -CREATE USER 'jaryo_user'@'localhost' IDENTIFIED BY 'JaryoPass2024!@#'; -GRANT ALL PRIVILEGES ON jaryo.* TO 'jaryo_user'@'localhost'; -FLUSH PRIVILEGES; -``` - -### 3.3 테이블 생성 (스키마 적용) -```bash -# NAS SSH 접속 후 -cd /volume1/web/jaryo -mysql -u jaryo_user -p jaryo < database/mariadb-schema.sql -``` - -## 4. 연결 설정 확인 - -### 4.1 Unix Socket 경로 확인 -```bash -sudo find /run -name "*.sock" | grep mysql -# 일반적인 경로: /run/mysqld/mysqld10.sock -``` - -### 4.2 연결 테스트 -```bash -mysql -u jaryo_user -p -S /run/mysqld/mysqld10.sock jaryo -``` - -## 5. NAS 자료실 서비스 배포 - -### 5.1 자동 배포 -```bash -./deploy-to-nas.sh [NAS-IP] jaryo [PASSWORD] -``` - -### 5.2 수동 초기화 (필요시) -```bash -cd /volume1/web/jaryo -npm run init-mariadb -``` - -## 6. 문제 해결 - -### 6.1 연결 오류 -- MariaDB 서비스 상태 확인: `sudo systemctl status mariadb` -- 소켓 파일 권한 확인: `ls -la /run/mysqld/` -- 방화벽 설정 확인 - -### 6.2 권한 오류 -```sql --- 권한 재설정 -GRANT ALL PRIVILEGES ON jaryo.* TO 'jaryo_user'@'localhost'; -FLUSH PRIVILEGES; -``` - -### 6.3 한글 데이터 문제 -```sql --- 문자셋 확인 -SHOW VARIABLES LIKE 'character_set%'; -SHOW VARIABLES LIKE 'collation%'; -``` - -## 7. 성능 최적화 - -### 7.1 인덱스 확인 -```sql -USE jaryo; -SHOW INDEX FROM files; -SHOW INDEX FROM file_attachments; -``` - -### 7.2 쿼리 최적화 -```sql --- 슬로우 쿼리 로그 활성화 -SET GLOBAL slow_query_log = 'ON'; -SET GLOBAL long_query_time = 2; -``` - -## 8. 백업 및 복원 - -### 8.1 데이터베이스 백업 -```bash -mysqldump -u jaryo_user -p jaryo > jaryo_backup_$(date +%Y%m%d).sql -``` - -### 8.2 데이터베이스 복원 -```bash -mysql -u jaryo_user -p jaryo < jaryo_backup_YYYYMMDD.sql -``` - -## 9. 보안 설정 - -### 9.1 비밀번호 변경 -```sql -ALTER USER 'jaryo_user'@'localhost' IDENTIFIED BY 'NEW_SECURE_PASSWORD'; -``` - -### 9.2 불필요한 권한 제거 -```sql --- 테스트 데이터베이스 제거 -DROP DATABASE IF EXISTS test; -DELETE FROM mysql.user WHERE User=''; -FLUSH PRIVILEGES; -``` \ No newline at end of file diff --git a/server.js b/server.js index 3a5f603..ac4ef33 100644 --- a/server.js +++ b/server.js @@ -6,12 +6,26 @@ const fs = require('fs'); const bcrypt = require('bcrypt'); const session = require('express-session'); const { v4: uuidv4 } = require('uuid'); -const DatabaseHelper = require('./database/db-helper'); +// 환경에 따른 데이터베이스 헬퍼 선택 +const isNAS = process.env.NODE_ENV === 'production' || process.env.DEPLOY_ENV === 'nas'; +const isWindows = process.platform === 'win32' && !isNAS; + +let DatabaseHelper; +if (isNAS) { + DatabaseHelper = require('./database/mariadb-helper'); + console.log('🗄️ NAS 환경: MariaDB 사용'); +} else if (isWindows) { + DatabaseHelper = require('./database/db-helper'); + console.log('🗄️ 로컬 Windows 환경: SQLite 사용'); +} else { + DatabaseHelper = require('./database/mariadb-helper'); + console.log('🗄️ Linux 환경: MariaDB 사용'); +} const app = express(); const PORT = process.env.PORT || 3005; -// 데이터베이스 헬퍼 인스턴스 (SQLite - 로컬 테스트용) +// 데이터베이스 헬퍼 인스턴스 const db = new DatabaseHelper(); // 미들웨어 설정