Metadata-Version: 2.4
Name: videxpulse-py-fcm-manager
Version: 0.1.3
Summary: Firebase Cloud Messaging (FCM) Python Package for Push Notifications
License: MIT
License-File: LICENSE
Keywords: firebase,fcm,push-notifications,notifications,django,mongodb,sqlalchemy
Author: VidExpulse
Author-email: murali@videxpulse.com
Requires-Python: >=3.9
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Provides-Extra: dev
Provides-Extra: django
Provides-Extra: mongodb
Provides-Extra: sqlalchemy
Requires-Dist: Django (>=3.2) ; extra == "django"
Requires-Dist: black (>=23.0) ; extra == "dev"
Requires-Dist: firebase-admin (>=6.0.0)
Requires-Dist: flake8 (>=6.0) ; extra == "dev"
Requires-Dist: isort (>=5.0) ; extra == "dev"
Requires-Dist: mongoengine (>=0.23.0) ; extra == "mongodb"
Requires-Dist: mypy (>=1.0) ; extra == "dev"
Requires-Dist: pytest (>=7.0) ; extra == "dev"
Requires-Dist: pytest-cov (>=4.0) ; extra == "dev"
Requires-Dist: sqlalchemy (>=1.4,<2.0) ; extra == "sqlalchemy"
Project-URL: Documentation, https://github.com/muraliwebworld/videxpulse-py-push-notification
Project-URL: Homepage, https://github.com/muraliwebworld/videxpulse-py-push-notification
Project-URL: Issues, https://github.com/muraliwebworld/videxpulse-py-push-notification/issues
Project-URL: Repository, https://github.com/muraliwebworld/videxpulse-py-push-notification
Description-Content-Type: text/markdown

# videxpulse_py_fcm_manager - Firebase Cloud Messaging Python Package

A clean, scalable Python package for managing Firebase Cloud Messaging (FCM) push notifications. Send notifications to individual users, subscribe to topics, and manage device tokens across multiple database backends (Django, MongoDB, SQLAlchemy).

## Features

✨ **Core Capabilities**
- 🎯 Send push notifications to individual users by token
- 📢 Send group notifications to topic subscribers
- 📱 Subscribe/unsubscribe devices to FCM topics
- 💾 Support for multiple database backends
- 🔧 Clean, extensible architecture
- 📊 Notification logging and tracking
- 🛡️ Error handling and retry logic

## Installation

### Install from PyPI (Production)

```bash
pip install videxpulse-py-fcm-manager
```

### With Database Support

**Django:**
```bash
pip install videxpulse-py-fcm-manager[django]
```

**MongoDB:**
```bash
pip install videxpulse-py-fcm-manager[mongodb]
```

**SQLAlchemy (MySQL/PostgreSQL):**
```bash
pip install videxpulse-py-fcm-manager[sqlalchemy]
```

**All Backends:**
```bash
pip install videxpulse-py-fcm-manager[django,mongodb,sqlalchemy]
```

### Install from TestPyPI (Pre-release Testing)

To test the latest development version from TestPyPI:

```bash
pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ videxpulse-py-fcm-manager
```

Or use the short alias:
```bash
pip install -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ videxpulse-py-fcm-manager
```

**Note:** The `--extra-index-url` flag tells pip to look for dependencies on the main PyPI while fetching the package from TestPyPI.

## Quick Start

### 1. Initialize the FCM Client

```python
from videxpulse_py_fcm_manager import FCMClient

# Create FCM client with your Firebase service account key
fcm_client = FCMClient(
    service_account_key_path="/path/to/firebase-key.json",
    app_name="my_app"
)
```

### 2. Send to Individual Users

```python
from videxpulse_py_fcm_manager.core.notification import Notification, NotificationType
from videxpulse_py_fcm_manager.managers import NotificationManager

notification_manager = NotificationManager(fcm_client, db_backend="django")

# Create notification
notification = Notification(
    title="Order Shipped",
    body="Your order has been shipped!",
    notification_type=NotificationType.INDIVIDUAL,
    user_id="device_token_123"
)

# Send notification
response = notification_manager.send_notification(notification)
print(f"Message ID: {response.message_id}")
```

### 3. Subscribe to Topics

```python
from videxpulse_py_fcm_manager.managers import TopicManager

topic_manager = TopicManager(fcm_client, db_backend="django")

# Subscribe user device to topic
topic_manager.subscribe_user_to_topic(
    user_id="user_123",
    fcm_token="device_token_456",
    topic="sports_news"
)
```

### 4. Send to Topics

```python
# Create topic notification
topic_notification = Notification(
    title="Breaking News",
    body="New sports update available",
    notification_type=NotificationType.TOPIC,
    topic="sports_news"
)

# Send to all topic subscribers
response = notification_manager.send_notification(topic_notification)
```

### 5. Manage Subscriptions (Django Example)

```python
from videxpulse_py_fcm_manager.models.django_models import UserSubscription

# Get all tokens for a user
user_tokens = UserSubscription.objects.filter(
    user_id=42, 
    is_active=True
).values_list('fcm_token', flat=True)

# Send to all user devices
notification_manager.send_to_multiple_users(
    user_ids=list(user_tokens),
    notification=notification
)
```

## Database Backends

### Django ORM

**Models Available:**
- `UserSubscription` - Store FCM tokens for individual users
- `TopicSubscription` - Manage topic subscriptions
- `NotificationLog` - Track sent notifications
- `NotificationTemplate` - Pre-defined notification templates

**Setup:**
```python
# settings.py
INSTALLED_APPS = [
    ...
    'videxpulse_py_fcm_manager',
]

# Run migrations
python manage.py migrate videxpulse_py_fcm_manager
```

### MongoDB

**Models Available:**
- `UserSubscriptionMongo` - Store FCM tokens
- `TopicSubscriptionMongo` - Topic subscriptions
- `NotificationLogMongo` - Notification tracking
- `NotificationTemplateMongo` - Notification templates

**Setup:**
```python
from mongoengine import connect
from videxpulse_py_fcm_manager.models.mongodb_models import UserSubscriptionMongo

# Configure MongoDB connection
connect('your_database', host='localhost', port=27017)

# Use models
subscription = UserSubscriptionMongo(
    user_id="user_123",
    fcm_token="token_abc",
    device_type="android"
)
subscription.save()
```

### SQLAlchemy (MySQL/PostgreSQL)

**Models Available:**
- `UserSubscriptionSQL` - Store FCM tokens
- `TopicSubscriptionSQL` - Topic subscriptions
- `NotificationLogSQL` - Notification tracking
- `NotificationTemplateSQL` - Notification templates

**Setup:**
```python
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from videxpulse_py_fcm_manager.models.sqlalchemy_models import Base, UserSubscriptionSQL

# Create engine and tables
engine = create_engine('mysql://user:password@localhost/dbname')
Base.metadata.create_all(engine)

# Use models
Session = sessionmaker(bind=engine)
session = Session()

subscription = UserSubscriptionSQL(
    user_id="user_123",
    fcm_token="token_abc",
    device_type="web"
)
session.add(subscription)
session.commit()
```

## Advanced Usage

### Using the Notification Builder

```python
from videxpulse_py_fcm_manager.utils import NotificationBuilder

notification = (NotificationBuilder("Order Update", "Order confirmed")
    .to_individual("device_token_123")
    .with_data({"order_id": "12345", "status": "confirmed"})
    .with_image("https://example.com/image.png")
    .with_click_action("OPEN_ORDER_APP")
    .with_priority("high")
    .build())

response = notification_manager.send_notification(notification)
```

### Batch Sending

```python
user_tokens = ["token_1", "token_2", "token_3", "token_4", "token_5"]

notification = Notification(
    title="Welcome",
    body="Thanks for joining!",
    notification_type=NotificationType.INDIVIDUAL
)

# Send to multiple users
responses = notification_manager.send_to_multiple_users(user_tokens, notification)

# Check results
for response in responses:
    if response.success:
        print(f"Success: {response.message_id}")
    else:
        print(f"Failed: {response.error}")
```

### On-Demand Notifications

```python
# Send on-demand notification to multiple users
responses = notification_manager.send_ondemand_notification(
    notification=notification,
    recipient_type="individual",
    recipients=["token_1", "token_2", "token_3"]
)

# Or send to multiple topics
responses = notification_manager.send_ondemand_notification(
    notification=notification,
    recipient_type="topic",
    recipients=["sports_news", "tech_updates"]
)
```

## Architecture

```
videxpulse_py_fcm_manager/
├── core/                          # Core FCM functionality
│   ├── fcm_client.py             # Main FCM client
│   ├── notification.py           # Notification models
│   └── exceptions.py             # Custom exceptions
│
├── models/                        # Database models
│   ├── base.py                   # Abstract base models
│   ├── django_models.py          # Django ORM models
│   ├── mongodb_models.py         # MongoDB models
│   └── sqlalchemy_models.py      # SQLAlchemy models
│
├── managers/                      # High-level managers
│   ├── subscription_manager.py   # Subscription management
│   ├── notification_manager.py   # Notification sending
│   └── topic_manager.py          # Topic management
│
└── utils/                         # Utilities
    └── helpers.py               # Helper functions
```

## Error Handling

```python
from videxpulse_py_fcm_manager.core.exceptions import (
    FCMException,
    NotificationException,
    SubscriptionException,
    ValidationException
)

try:
    response = notification_manager.send_notification(notification)
except ValidationException as e:
    print(f"Validation failed: {e}")
except NotificationException as e:
    print(f"Notification failed: {e}")
except FCMException as e:
    print(f"FCM error: {e}")
```

## Configuration

### Setup Logging

```python
from videxpulse_py_fcm_manager.utils import setup_logging
import logging

# Setup package logging
setup_logging(level=logging.DEBUG)
```

### Validation Helpers

```python
from videxpulse_py_fcm_manager.utils import (
    validate_fcm_token,
    validate_topic_name,
    validate_user_id
)

# Validate before sending
if validate_fcm_token("your_token"):
    notification_manager.send_to_individual("your_token", notification)

if validate_topic_name("sports_news"):
    topic_manager.subscribe_user_to_topic("user_1", "token_1", "sports_news")
```

## Performance Considerations

⚠️ **Batch Limits**: FCM's `send_multicast()` has a 500 token limit per request. For larger batches, the package automatically chunks requests.

⚠️ **Database Queries**: For high-volume applications, consider:
- Adding database indexes on `user_id`, `fcm_token`, and `topic` fields
- Implementing caching for frequently accessed token lists
- Using connection pooling for SQLAlchemy and database connections

## Testing

```bash
# Install dev dependencies
pip install videxpulse-py-fcm-manager[dev]

# Run tests
pytest tests/

# Run with coverage
pytest tests/ --cov=videxpulse_py_fcm_manager
```

## Contributing

Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Submit a pull request

## Package Links

- **PyPI (Production)**: https://pypi.org/project/videxpulse-py-fcm-manager/
- **TestPyPI (Pre-release)**: https://test.pypi.org/project/videxpulse-py-fcm-manager/
- **GitHub Repository**: https://github.com/muraliwebworld/videxpulse-py-push-notification

## License

MIT License - see LICENSE file for details

## Support

For issues, feature requests, or questions:
- 📧 Email: murali@videxpulse.com
- 🐛 Issues: https://github.com/muraliwebworld/videxpulse-py-push-notification/issues
- 📖 Documentation: https://github.com/muraliwebworld/videxpulse-py-push-notification

**Version Information:**
- Latest stable: Available on [PyPI](https://pypi.org/project/videxpulse-py-fcm-manager/)
- Development/Pre-release: Available on [TestPyPI](https://test.pypi.org/project/videxpulse-py-fcm-manager/)

## Changelog

### v0.1.3 (2026-08-04)
- Initial release
- Core FCM client implementation with Firebase Admin SDK integration
- Django, MongoDB, SQLAlchemy model support
- Notification manager and topic manager
- Comprehensive error handling and retry logic
- 78 passing tests with quality validation (Black, isort, flake8, mypy)
- Firebase topic subscription management (fixed SDK compatibility)
- Available on: https://pypi.org/project/videxpulse-py-fcm-manager/
- Available on test: https://test.pypi.org/project/videxpulse-py-fcm-manager/

