- Add build scripts for Android and iOS platforms - Remove duplicate web implementation (src/web.ts) - Add proper TypeScript configuration - Add module documentation to index.ts - Clean up package.json scripts This commit improves the project structure and build process by: 1. Adding dedicated build scripts for native platforms 2. Removing redundant web implementation 3. Adding proper TypeScript configuration with strict mode 4. Improving code documentation 5. Organizing package.json scripts The changes maintain backward compatibility while improving the development experience and code quality.
Daily Notification Plugin for Capacitor
A powerful Capacitor plugin for scheduling and managing daily notifications with advanced features like timezone support, offline capabilities, and retry logic.
Features
- Schedule daily notifications at specific times
- Support for multiple notification schedules
- Timezone-aware scheduling
- Offline support with content caching
- Retry logic with exponential backoff
- Custom notification content handlers
- Event-based notification handling
- Comprehensive settings management
- TypeScript support with full type definitions
Installation
npm install @timesafari/daily-notification-plugin
Usage
Basic Usage
import { DailyNotification } from '@timesafari/daily-notification-plugin';
const plugin = new DailyNotification();
// Schedule a daily notification
await plugin.scheduleDailyNotification({
url: 'https://api.example.com/updates',
time: '09:00',
title: 'Daily Update',
body: 'Your daily content is ready!',
sound: true,
priority: 'high'
});
// Get notification status
const status = await plugin.getNotificationStatus();
console.log('Next notification:', status.nextNotificationTime);
// Handle notification events
plugin.on('notification', (event) => {
console.log('Notification received:', event.detail);
});
Advanced Usage
// Multiple schedules with different timezones
const schedules = [
{
url: 'https://api.example.com/morning',
time: '09:00',
timezone: 'America/New_York',
title: 'Morning Update'
},
{
url: 'https://api.example.com/evening',
time: '18:00',
timezone: 'Europe/London',
title: 'Evening Update'
}
];
for (const schedule of schedules) {
await plugin.scheduleDailyNotification(schedule);
}
// Offline support with caching
await plugin.scheduleDailyNotification({
url: 'https://api.example.com/updates',
time: '10:00',
offlineFallback: true,
cacheDuration: 3600, // 1 hour
contentHandler: async (response) => {
const data = await response.json();
return {
title: data.title,
body: data.content,
data: data.metadata
};
}
});
// Update settings
await plugin.updateSettings({
time: '11:00',
sound: true,
priority: 'high',
timezone: 'America/Chicago'
});
API Reference
Methods
scheduleDailyNotification(options: NotificationOptions): Promise<void>
Schedules a daily notification with the specified options.
interface NotificationOptions {
url: string;
time: string; // "HH:mm" format
title?: string;
body?: string;
sound?: boolean;
vibrate?: boolean;
priority?: 'low' | 'normal' | 'high';
retryCount?: number;
retryInterval?: number;
cacheDuration?: number;
headers?: Record<string, string>;
offlineFallback?: boolean;
timezone?: string;
contentHandler?: (response: Response) => Promise<{
title: string;
body: string;
data?: any;
}>;
}
getLastNotification(): Promise<NotificationResponse | null>
Retrieves the last notification that was delivered.
cancelAllNotifications(): Promise<void>
Cancels all scheduled notifications.
getNotificationStatus(): Promise<NotificationStatus>
Gets the current status of notifications.
updateSettings(settings: NotificationSettings): Promise<void>
Updates notification settings.
interface NotificationSettings {
time?: string;
sound?: boolean;
vibrate?: boolean;
priority?: 'low' | 'normal' | 'high';
timezone?: string;
}
Events
The plugin emits the following events:
notification: Fired when a notification is received or interacted with
interface NotificationEvent extends Event {
detail: {
id: string;
action: string;
data?: any;
};
}
Testing
The plugin includes comprehensive tests covering:
- Basic functionality
- Multiple schedules
- Timezone handling
- Offline support
- Retry logic
- Event handling
- Settings management
Run tests with:
npm test
Security Considerations
- All network requests use HTTPS
- Content is validated before display
- Sensitive data is not stored in logs
- Permissions are properly managed
- Input validation is performed on all methods
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Author
Matthew Raymer
Platform-Specific Implementation
Android Implementation
- Uses
WorkManagerfor periodic data fetching - Implements
AlarmManagerfor precise notification scheduling - Stores data in
SharedPreferences - Handles Doze mode and battery optimizations
iOS
- Utilizes
BGTaskSchedulerfor background fetches - Implements
UNUserNotificationCenterfor notifications - Stores data in
UserDefaults - Respects system background execution limits
Permissions
Android Permissions
Required permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
iOS Implementation
- Notification permissions (requested at runtime)
- Background App Refresh capability (enabled in Xcode)
Error Handling
The plugin implements comprehensive error handling:
- Network failure retry logic with exponential backoff
- Fallback to cached content when fetching fails
- Detailed error logging and reporting
- Graceful degradation when permissions are denied
Best Practices
Content Management
- Keep notification content concise and actionable
- Use clear, engaging titles under 50 characters
- Limit notification body to 2-3 lines
- Include a clear call-to-action when appropriate
Network Optimization
- Implement proper caching headers on your API
- Use compression for network responses
- Keep payload size under 4KB for optimal performance
- Implement rate limiting on your API endpoints
Battery Considerations
- Schedule notifications during active hours
- Avoid excessive background fetches
- Use appropriate fetch intervals (minimum 15 minutes)
- Implement smart retry strategies
User Experience
- Request notification permissions at an appropriate time
- Provide clear value proposition for notifications
- Allow users to customize notification timing
- Implement proper error messaging for users
Security
- Always use HTTPS for API endpoints
- Implement proper API authentication
- Sanitize notification content
- Follow platform-specific security guidelines
Testing
- Test notifications in various app states
- Verify behavior with different network conditions
- Test on multiple device types and OS versions
- Implement proper error logging for debugging
Development Setup
Prerequisites
- Node.js 14 or higher
- Java 11 or higher
- Android Studio and Android SDK
- Xcode (for iOS development, macOS only)
- CocoaPods (for iOS development)
Environment Setup
- Clone the repository:
git clone https://github.com/yourusername/capacitor-daily-notification.git
cd capacitor-daily-notification
- Install dependencies:
npm install
This will:
- Install Node.js dependencies
- Check your development environment
- Set up native build environments
- Install platform-specific dependencies
Building the Plugin
TypeScript Build
# Build TypeScript code
npm run build
# Watch mode for development
npm run watch
Android Build
# Build Android library
npm run build:android
# Run Android tests
npm run test:android
The Android build will:
- Compile the TypeScript code
- Build the Android library
- Generate an AAR file in
android/build/outputs/aar/
iOS Build
# Build iOS library
npm run build:ios
# Run iOS tests
npm run test:ios
The iOS build will:
- Compile the TypeScript code
- Install CocoaPods dependencies
- Build the iOS framework
Using in a Capacitor App
- Install the plugin in your Capacitor app:
npm install capacitor-daily-notification
- Add to your Android app's
android/app/build.gradle:
dependencies {
implementation project(':daily-notification')
}
- Add to your iOS app's
ios/App/Podfile:
pod 'CapacitorDailyNotification', :path => '../node_modules/capacitor-daily-notification'
- Sync native projects:
npx cap sync
Troubleshooting
Android Issues
- Gradle Sync Failed
cd android
./gradlew clean
./gradlew --refresh-dependencies
- Missing Android SDK
- Set ANDROID_HOME environment variable
- Install required SDK components via Android Studio
- Build Errors
- Check Android Studio for detailed error messages
- Ensure all required SDK components are installed
- Verify Gradle version compatibility
iOS Issues
- Pod Install Failed
cd ios
pod deintegrate
pod cache clean --all
pod install
- Xcode Build Errors
- Open Xcode project in Xcode
- Check build settings
- Verify deployment target matches requirements
- Missing Dependencies
- Ensure CocoaPods is installed
- Run
pod setupto update CocoaPods repos
Development Workflow
- Make changes to TypeScript code
- Run
npm run buildto compile - Run
npm run build:nativeto build native code - Test changes:
- Android:
npm run test:android - iOS:
npm run test:ios
- Android:
- Run full validation:
- Android:
npm run validate - iOS:
npm run validate:ios
- Android:
Continuous Integration
The plugin includes pre-commit hooks and CI configurations:
-
Pre-commit checks:
- TypeScript compilation
- Linting
- Native build verification
-
CI pipeline:
- Environment validation
- TypeScript build
- Native builds
- Unit tests
- Integration tests
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Author
Matthew Raymer
Plugin Security
This plugin follows security best practices:
- Secure storage of sensitive data
- HTTPS-only network requests
- Permission-based access control
- Regular security audits
- No sensitive data in logs
Support
For support, please open an issue in the GitHub repository or contact the maintainers.
Changelog
See CHANGELOG.md for a list of changes and version history.