Skip to content

Latest commit

 

History

History
437 lines (358 loc) · 11.3 KB

File metadata and controls

437 lines (358 loc) · 11.3 KB

Airwave Automator Free - Technical Documentation

Table of Contents

  1. Overview
  2. Architecture
  3. API Reference
  4. Configuration
  5. Matrix Integration
  6. Audio System
  7. Storage Management
  8. Error Handling
  9. Performance Optimization
  10. Security Considerations
  11. Troubleshooting Guide

Overview

Airwave Automator Free is a Chrome extension built with Manifest V3 that combines radio streaming capabilities with Matrix chat integration. The extension uses a side panel interface and provides real-time audio streaming with chat functionality.

Key Components

  • Background Service Worker: Manages global audio playback and inter-page communication
  • Side Panel Interface: Main user interface with Radio, Chat, and Options pages
  • Matrix SDK Integration: Custom minimal Matrix client implementation
  • Audio Management: HTML5 audio with Web Audio API visualization
  • Storage System: Chrome storage API for persistent settings

Architecture

Extension Structure

Airwave Automator Free/
├── manifest.json              # Extension configuration
├── background.js              # Service worker
├── popup.html/js              # Extension popup
├── radio.html/js              # Radio player interface
├── matrix.html/js             # Matrix chat interface
├── options.html/js            # Settings interface
├── styles.css                 # Global styling
├── assets/                    # Static assets
│   └── logo.png              # Extension logo
└── third_party/              # External dependencies
    ├── matrix/
    │   └── browser-matrix.min.js  # Custom Matrix SDK
    └── sonic-widget.min.js       # SonicPanel integration

Data Flow

  1. User InteractionUI ComponentsBackground Script
  2. Matrix EventsMatrix SDKChat Interface
  3. Audio StreamsHTML5 AudioVisualizerUI Updates
  4. Settings ChangesChrome StoragePersistent State

API Reference

Background Script (background.js)

Message Types

  • AA_SET_SIDEPANEL_PATH: Change the side panel page
  • AA_PLAY_AUDIO: Start global audio playback
  • AA_STOP_AUDIO: Stop global audio playback
  • AA_SET_VOLUME: Adjust global audio volume

Functions

// Play audio globally across all pages
playGlobalAudio(streamUrl, volume)

// Stop global audio playback
stopGlobalAudio()

// Set global audio volume
setGlobalVolume(volume)

Matrix SDK (third_party/matrix/browser-matrix.min.js)

MatrixClient Class

// Initialize Matrix client
const client = new MatrixClient({
  baseUrl: 'https://matrix.org',
  accessToken: 'your_token',
  userId: '@user:server',
  deviceId: 'device_id'
})

// Login to Matrix
await client.login('m.login.password', {
  user: '@user:server',
  password: 'password'
})

// Join a room
await client.joinRoom('#room:server')

// Send a message
await client.sendTextMessage('#room:server', 'Hello!')

// Perform sync
await client.performSync(limit)

Events

  • sync: Emitted when sync completes
  • Room.timeline: Emitted when new messages arrive

Radio Player (radio.js)

Audio Management

// Setup audio visualization
setupViz()

// Initialize SonicPanel widget
initSonicWidget(port)

// Fetch SonicPanel metadata
fetchSonicInfo()

// Save/restore audio state
saveAudioState()
restoreAudioState()

Matrix Chat (matrix.js)

Room Management

// Open a Matrix room
openMatrixRoom(roomId)

// Join a room
joinRoom()

// Join recommended room
joinRecommendedRoom(roomId)

// Render room list
renderMatrixRooms(rooms)

Configuration

Manifest Configuration (manifest.json)

{
  "manifest_version": 3,
  "name": "Airwave Automator Free",
  "version": "1.0.26",
  "permissions": ["storage", "sidePanel"],
  "host_permissions": ["https://*/*", "http://*/*"],
  "background": {
    "service_worker": "background.js"
  },
  "side_panel": {
    "default_path": "radio.html"
  }
}

Stream Configuration

// Stream object structure
{
  name: "Stream Name",
  url: "http://stream.example.com:8000",
  port: 8000,
  apiUrl: "http://api.example.com/get_info.php",
  volume: 0.8
}

Matrix Configuration

// Matrix settings structure
{
  homeserver: "https://matrix.org",
  user: "@user:server",
  password: "password",
  loggedIn: true,
  refreshInterval: 1
}

Matrix Integration

Custom Matrix SDK Features

Sync Token Management

The custom Matrix SDK implements proper sync token handling for incremental updates:

// Sync with token for incremental updates
let syncUrl = `${baseUrl}/_matrix/client/v3/sync?limit=${limit}&timeout=1000`;
if (this.nextBatchToken) {
  syncUrl += `&since=${this.nextBatchToken}`;
}

Event Deduplication

Prevents duplicate messages by checking event IDs:

const existingEvent = room.timeline.events.find(e => 
  e.eventData.event_id === eventData.event_id
);
if (!existingEvent) {
  room.timeline.events.push(event);
  this.emit("Room.timeline", event, room);
}

Room Management

  • Automatic room creation and updates
  • Fuzzy room ID matching
  • Member management
  • Timeline event processing

Matrix API Endpoints Used

  • /r0/login - User authentication
  • /v3/sync - Event synchronization
  • /v3/rooms/{roomId}/join - Join rooms
  • /v3/rooms/{roomId}/send/m.room.message - Send messages
  • /v3/directory/room/{roomAlias} - Resolve room aliases

Audio System

Global Audio Management

The extension implements a global audio system that persists across page navigation:

// Background script manages global audio
let globalAudioPlayer = null;

function playGlobalAudio(streamUrl, volume) {
  if (!globalAudioPlayer) {
    globalAudioPlayer = new Audio();
  }
  globalAudioPlayer.src = streamUrl;
  globalAudioPlayer.volume = volume;
  globalAudioPlayer.play();
}

Audio Visualization

Uses Web Audio API for real-time visualization:

function setupViz() {
  const audioContext = new AudioContext();
  const analyser = audioContext.createAnalyser();
  const source = audioContext.createMediaElementSource(player);
  source.connect(analyser);
  analyser.connect(audioContext.destination);
  
  // Render visualization frames
  function render() {
    requestAnimationFrame(render);
    // Update canvas visualization
  }
}

SonicPanel Integration

Automatic metadata fetching and display:

function initSonicWidget(port) {
  const script = document.createElement('script');
  script.src = 'third_party/sonic-widget.min.js';
  script.onload = () => {
    // Initialize SonicPanel widget
  };
  document.head.appendChild(script);
}

Storage Management

Chrome Storage API Usage

// Sync storage for settings
chrome.storage.sync.set({ aa_streams: streams });
chrome.storage.sync.set({ aa_matrix_settings: matrixSettings });

// Local storage for audio state
chrome.storage.local.set({ aa_audio_state: audioState });
chrome.storage.local.get(['aa_audio_state']);

Data Persistence

  • Streams: Stored in chrome.storage.sync (syncs across devices)
  • Matrix Settings: Stored in chrome.storage.sync
  • Audio State: Stored in chrome.storage.local (device-specific)
  • UI State: Managed in memory, restored on page load

Error Handling

Matrix Error Handling

try {
  await matrixAuthed.joinRoom(roomId);
} catch (error) {
  console.error('Failed to join room:', error);
  let suggestion = '';
  if (error.message.includes('404')) {
    suggestion = '\n\nTry these popular public rooms...';
  }
  alert(`Failed to join room: ${error.message}${suggestion}`);
}

Audio Error Handling

player.addEventListener('error', (e) => {
  console.error('Audio error:', e);
  matrixStatus.textContent = 'Audio error: ' + e.message;
  matrixStatus.className = 'status error';
});

Network Error Handling

  • Automatic retry mechanisms
  • Graceful degradation
  • User-friendly error messages
  • Fallback options

Performance Optimization

Matrix Sync Optimization

  • 1-second refresh interval for near real-time updates
  • Incremental sync using tokens
  • Event deduplication to prevent spam
  • Timeout parameters for faster responses

Audio Performance

  • Global audio management reduces resource usage
  • Efficient visualization using requestAnimationFrame
  • Memory management for audio contexts
  • Background playback optimization

UI Performance

  • Lazy loading of Matrix SDK
  • Efficient DOM updates
  • Debounced user inputs
  • Optimized event listeners

Security Considerations

Content Security Policy

"content_security_policy": {
  "extension_pages": "script-src 'self' data: https: http:; img-src 'self' data: https: http:; connect-src 'self' https: http: wss: ws:;"
}

Matrix Security

  • End-to-end encryption support
  • Secure token storage in Chrome storage
  • HTTPS-only Matrix connections
  • Input validation for user data

Data Privacy

  • Local storage for sensitive data
  • No data collection or transmission
  • User control over all settings
  • Secure credential handling

Troubleshooting Guide

Common Issues

Audio Not Playing

  1. Check stream URL accessibility
  2. Verify Chrome audio permissions
  3. Check for ad blocker interference
  4. Test with different stream formats

Matrix Login Fails

  1. Verify Matrix credentials
  2. Check homeserver accessibility
  3. Ensure proper Matrix ID format (@user:server)
  4. Test with different homeserver

Messages Not Appearing

  1. Check Matrix connection status
  2. Verify room membership
  3. Use "Force Fresh Sync" button
  4. Check console for errors

Extension Crashes

  1. Reload extension in chrome://extensions/
  2. Check browser console for errors
  3. Clear extension data if needed
  4. Reinstall extension

Debug Tools

Console Logging

The extension includes comprehensive logging:

console.log('Matrix SDK performing sync with limit:', limit);
console.log('Sync response received:', data);
console.log('Added new message event:', eventData.event_id);

Debug Buttons

  • Test Message: Adds dummy message to timeline
  • Debug Timeline: Shows timeline state information
  • Refresh Rooms: Forces room list refresh
  • Force Fresh Sync: Resets sync token and performs fresh sync

Performance Monitoring

  • Monitor Matrix sync response times
  • Track audio playback performance
  • Monitor memory usage
  • Check for memory leaks

Development Guidelines

Code Style

  • Use consistent indentation (2 spaces)
  • Include comprehensive comments
  • Follow JavaScript best practices
  • Implement proper error handling

Testing

  • Test with multiple Matrix homeservers
  • Verify audio playback across different stream types
  • Test extension behavior across page navigation
  • Validate error handling scenarios

Maintenance

  • Regular dependency updates
  • Security patch management
  • Performance monitoring
  • User feedback integration

Technical Support: For technical issues, contact support@spunwebtechnology.com or join #airwavesupport:matrix.org