# TChat - Real-time Chat Application

TChat adalah aplikasi chat real-time yang dibangun dengan Node.js, Socket.IO, dan SQLite. Aplikasi ini mendukung chat publik, private messaging, typing indicators, message status, dan file sharing.

## ✨ Fitur

### 🔐 Autentikasi
- Google OAuth 2.0 integration
- Session management yang aman
- User profile dengan avatar

### 💬 Messaging
- **Public Chat**: Chat room untuk semua user
- **Private Chat**: Pesan pribadi antar user
- **Real-time messaging** dengan Socket.IO
- **Message status**: Sent, Delivered, Read
- **Typing indicators** untuk private chat
- **File sharing** dengan preview
- **Message history** yang persisten

### 🛡️ Keamanan & Performance
- **Input validation** dan sanitization
- **Rate limiting** untuk API dan Socket events
- **Error handling** yang komprehensif
- **Logging system** dengan file rotation
- **CORS protection**
- **Session security**

### 🎨 UI/UX
- **Responsive design** untuk mobile dan desktop
- **Real-time notifications**
- **Smooth animations** dan transitions
- **Modern UI** dengan CSS Grid dan Flexbox
- **Dark/Light theme support** (coming soon)

## 🚀 Quick Start

### Prerequisites
- Node.js (v14 atau lebih baru)
- npm atau yarn
- Google OAuth credentials

### Installation

1. **Clone repository**
   ```bash
   git clone <repository-url>
   cd tchat
   ```

2. **Install dependencies**
   ```bash
   npm install
   ```

3. **Setup environment variables**
   ```bash
   cp .env.example .env
   ```
   
   Edit `.env` file dan isi dengan konfigurasi yang sesuai:
   ```env
   GOOGLE_CLIENT_ID=your-google-client-id
   GOOGLE_CLIENT_SECRET=your-google-client-secret
   SESSION_SECRET=your-super-secret-session-key
   ```

4. **Setup Google OAuth**
   - Buka [Google Cloud Console](https://console.cloud.google.com/)
   - Buat project baru atau pilih existing project
   - Enable Google+ API
   - Buat OAuth 2.0 credentials
   - Tambahkan `http://localhost:3001/auth/google/callback` ke authorized redirect URIs

5. **Start aplikasi**
   ```bash
   npm start
   ```

6. **Akses aplikasi**
   Buka browser dan kunjungi `http://localhost:3001`

## 📁 Struktur Project

```
tchat/
├── config/
│   └── config.js              # Konfigurasi aplikasi
├── database/
│   ├── chat.db               # SQLite database
│   └── database.js           # Database layer
├── middleware/
│   ├── errorHandler.js       # Error handling & logging
│   └── validation.js         # Input validation & rate limiting
├── public/
│   ├── index.html           # Frontend HTML
│   ├── script.js            # Frontend JavaScript
│   ├── styles.css           # Frontend CSS
│   └── default-avatar.svg   # Default user avatar
├── routes/
│   ├── auth.js              # Authentication routes
│   └── chat.js              # Chat API routes
├── uploads/                 # File upload directory
├── logs/                    # Application logs
├── server.js               # Main server file
├── package.json
├── .env.example
└── README.md
```

## 🔧 Konfigurasi

### Environment Variables

Semua konfigurasi dapat diatur melalui environment variables. Lihat `.env.example` untuk daftar lengkap.

#### Konfigurasi Penting:

- **GOOGLE_CLIENT_ID** & **GOOGLE_CLIENT_SECRET**: Credentials untuk Google OAuth
- **SESSION_SECRET**: Secret key untuk session encryption (wajib diubah di production)
- **NODE_ENV**: Environment mode (development/production)
- **PORT**: Port server (default: 3001)

### Rate Limiting

Aplikasi menggunakan rate limiting untuk mencegah abuse:

- **API endpoints**: 100 requests/minute
- **Auth endpoints**: 20 requests/minute
- **Socket messages**: 30 messages/minute
- **Private messages**: 20 messages/minute
- **Typing events**: 60 events/minute

### File Upload

- **Max file size**: 10MB
- **Allowed types**: Images (JPEG, PNG, GIF, WebP), PDF, Text, Word documents
- **Storage**: Local filesystem (dapat diubah ke cloud storage)

## 🛠️ Development

### Scripts

```bash
# Start development server
npm run dev

# Start production server
npm start

# Run tests (coming soon)
npm test

# Lint code (coming soon)
npm run lint
```

### Database Schema

Aplikasi menggunakan SQLite dengan schema berikut:

#### Users Table
```sql
CREATE TABLE users (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  google_id TEXT UNIQUE NOT NULL,
  name TEXT NOT NULL,
  email TEXT NOT NULL,
  avatar TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
```

#### Messages Table
```sql
CREATE TABLE messages (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  user_id INTEGER NOT NULL,
  content TEXT,
  message_type TEXT DEFAULT 'text',
  private_chat_id INTEGER NULL,
  status TEXT DEFAULT 'sent',
  read_at DATETIME NULL,
  timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users (id),
  FOREIGN KEY (private_chat_id) REFERENCES private_chats (id)
);
```

#### Private Chats Table
```sql
CREATE TABLE private_chats (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  user1_id INTEGER NOT NULL,
  user2_id INTEGER NOT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user1_id) REFERENCES users (id),
  FOREIGN KEY (user2_id) REFERENCES users (id)
);
```

### API Endpoints

#### Authentication
- `GET /auth/google` - Initiate Google OAuth
- `GET /auth/google/callback` - Google OAuth callback
- `POST /auth/logout` - Logout user
- `GET /auth/user` - Get current user info

#### Chat
- `GET /api/chat/messages` - Get recent public messages
- `GET /api/chat/private/:userId` - Get private chat messages
- `POST /api/chat/upload` - Upload file
- `GET /api/chat/users` - Get all users
- `GET /api/chat/private-chats` - Get user's private chats

### Socket Events

#### Client to Server
- `authenticate` - Authenticate user
- `send_message` - Send public message
- `send_private_message` - Send private message
- `typing_start` - Start typing indicator
- `typing_stop` - Stop typing indicator
- `mark_messages_read` - Mark messages as read
- `file_uploaded` - File upload notification

#### Server to Client
- `new_message` - New public message
- `private_message` - New private message
- `private_message_sent` - Private message sent confirmation
- `user_typing` - User typing indicator
- `user_stop_typing` - User stop typing
- `messages_read` - Messages read notification
- `user_online` - User came online
- `user_offline` - User went offline
- `online_users` - List of online users
- `error` - Error notification

## 🔒 Security

### Implemented Security Measures

1. **Input Validation**: Semua input divalidasi dan disanitasi
2. **Rate Limiting**: Mencegah spam dan abuse
3. **CORS Protection**: Konfigurasi CORS yang proper
4. **Session Security**: Secure session configuration
5. **Error Handling**: Tidak expose sensitive information
6. **File Upload Security**: Validasi file type dan size
7. **SQL Injection Prevention**: Menggunakan prepared statements
8. **XSS Prevention**: Input sanitization

### Security Best Practices

- Selalu gunakan HTTPS di production
- Set `NODE_ENV=production` di production
- Gunakan strong session secret
- Regularly update dependencies
- Monitor logs untuk suspicious activity
- Implement proper backup strategy

## 📊 Monitoring & Logging

### Log Files

Aplikasi menghasilkan log files di direktori `logs/`:

- `info.log` - General application logs
- `warn.log` - Warning messages
- `error.log` - Error messages

### Log Format

```json
{
  "timestamp": "2024-01-01T12:00:00.000Z",
  "level": "info",
  "message": "User authenticated: John Doe (123)",
  "error": null
}
```

## 🚀 Deployment

### Production Checklist

- [ ] Set `NODE_ENV=production`
- [ ] Configure proper `SESSION_SECRET`
- [ ] Setup HTTPS
- [ ] Configure proper CORS origins
- [ ] Setup database backups
- [ ] Configure log rotation
- [ ] Setup monitoring
- [ ] Configure reverse proxy (nginx)
- [ ] Setup SSL certificates

### Docker Deployment (Coming Soon)

```dockerfile
# Dockerfile example
FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3001
CMD ["npm", "start"]
```

## 🤝 Contributing

1. Fork the repository
2. Create feature branch (`git checkout -b feature/amazing-feature`)
3. Commit changes (`git commit -m 'Add amazing feature'`)
4. Push to branch (`git push origin feature/amazing-feature`)
5. Open Pull Request

### Development Guidelines

- Follow existing code style
- Add proper error handling
- Include input validation
- Add logging for important events
- Update documentation
- Test thoroughly

## 📝 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🆘 Troubleshooting

### Common Issues

1. **Google OAuth Error**
   - Pastikan GOOGLE_CLIENT_ID dan GOOGLE_CLIENT_SECRET sudah benar
   - Cek authorized redirect URIs di Google Console

2. **Database Error**
   - Pastikan direktori database dapat ditulis
   - Cek permission file database

3. **File Upload Error**
   - Pastikan direktori uploads dapat ditulis
   - Cek file size limits

4. **Socket Connection Error**
   - Cek CORS configuration
   - Pastikan port tidak diblokir firewall

### Debug Mode

Untuk enable debug logs:
```bash
DEBUG_LOGS=true npm start
```

## 📞 Support

Jika mengalami masalah atau memiliki pertanyaan:

1. Cek [Issues](https://github.com/your-repo/issues) yang sudah ada
2. Buat issue baru dengan detail yang lengkap
3. Sertakan log error jika ada
4. Jelaskan langkah untuk reproduce masalah

---

**TChat** - Built with ❤️ using Node.js, Socket.IO, and modern web technologies.