File size: 6,357 Bytes
5acd9c3
 
83f2577
 
5acd9c3
 
 
 
83f2577
 
5acd9c3
 
 
 
 
 
 
 
 
 
 
83f2577
5acd9c3
 
 
 
 
 
 
 
 
 
 
 
83f2577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5acd9c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83f2577
 
 
 
 
5acd9c3
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// lib/main.dart
import 'package:aitube2/config/config.dart';
import 'package:aitube2/models/video_result.dart';
import 'package:aitube2/screens/video_screen.dart';
import 'package:aitube2/services/settings_service.dart';
import 'package:aitube2/services/websocket_api_service.dart';
import 'package:aitube2/theme/colors.dart';
import 'package:aitube2/widgets/maintenance_screen.dart';
import 'package:aitube2/widgets/web_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'screens/home_screen.dart';
import 'services/cache_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Configuration.instance.initialize();

  Widget homeWidget = const HomeScreen();
  Exception? connectionError;
  final WebSocketApiService wsService = WebSocketApiService();

  try {
    // Initialize services in sequence to ensure proper dependencies
    await SettingsService().initialize();
    await CacheService().initialize();
    
    // Initialize the WebSocket service
    await wsService.initialize();
    
    // Check the current status
    if (wsService.status == ConnectionStatus.maintenance || wsService.isInMaintenance) {
      homeWidget = const MaintenanceScreen(error: null);
    } else if (kIsWeb) {
      // Handle URL query parameters (web only)
      final params = getUrlParameters();
      
      // Handle search parameter
      if (params.containsKey('search')) {
        final searchQuery = params['search'] ?? '';
        if (searchQuery.isNotEmpty) {
          // Pass search query to HomeScreen - it will trigger search on load
          homeWidget = HomeScreen(initialSearchQuery: searchQuery);
        }
      } 
      // Handle view parameter (higher priority than search if both are present)
      else if (params.containsKey('view')) {
        final viewQuery = params['view'] ?? '';
        if (viewQuery.isNotEmpty) {
          // Create a loading widget that will transition to VideoScreen once search completes
          homeWidget = FutureBuilder<VideoResult>(
            future: wsService.search(viewQuery),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) {
                // Navigate to VideoScreen once we have the result
                return VideoScreen(video: snapshot.data!);
              } else if (snapshot.hasError) {
                return Scaffold(
                  body: Center(
                    child: Text('Error loading video: ${snapshot.error}'),
                  ),
                );
              } else {
                // Show loading indicator while waiting
                return const Scaffold(
                  body: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              }
            },
          );
        }
      }
    }
    
    // Listen to connection status changes 
    wsService.statusStream.listen((status) {
      if (status == ConnectionStatus.maintenance) {
        // Force update to maintenance screen if server goes into maintenance mode later
        runApp(AiTubeApp(home: const MaintenanceScreen(error: null)));
      }
    });
    
  } catch (e) {
    debugPrint('Error initializing services: $e');
    connectionError = e is Exception ? e : Exception('$e');
    
    // If the error message contains maintenance, show the maintenance screen
    if (e.toString().toLowerCase().contains('maintenance')) {
      homeWidget = const MaintenanceScreen(error: null);
    } else {
      homeWidget = MaintenanceScreen(error: connectionError);
    }
  }

  runApp(AiTubeApp(home: homeWidget));
}

class AiTubeApp extends StatelessWidget {
  final Widget home;
  
  const AiTubeApp({super.key, required this.home});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: Configuration.instance.uiProductName,
      theme: ThemeData.dark().copyWith(
        colorScheme: const ColorScheme.dark(
          surface: AiTubeColors.surface,
          surfaceContainerHighest: AiTubeColors.surfaceVariant,
          primary: AiTubeColors.primary,
          onSurface: AiTubeColors.onSurface,
          onSurfaceVariant: AiTubeColors.onSurfaceVariant,
        ),
        scaffoldBackgroundColor: AiTubeColors.background,
        cardTheme: CardThemeData(
          color: AiTubeColors.surface,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        appBarTheme: const AppBarTheme(
          backgroundColor: AiTubeColors.background,
          elevation: 0,
        ),
        textTheme: const TextTheme(
          titleLarge: TextStyle(color: AiTubeColors.onBackground),
          titleMedium: TextStyle(color: AiTubeColors.onBackground),
          bodyLarge: TextStyle(color: AiTubeColors.onSurface),
          bodyMedium: TextStyle(color: AiTubeColors.onSurfaceVariant),
        ),
      ),
      darkTheme: ThemeData.dark().copyWith(
        colorScheme: const ColorScheme.dark(
          surface: AiTubeColors.surface,
          surfaceContainerHighest: AiTubeColors.surfaceVariant,
          primary: AiTubeColors.primary,
          onSurface: AiTubeColors.onSurface,
          onSurfaceVariant: AiTubeColors.onSurfaceVariant,
        ),
        scaffoldBackgroundColor: AiTubeColors.background,
        cardTheme: CardThemeData(
          color: AiTubeColors.surface,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        appBarTheme: const AppBarTheme(
          backgroundColor: AiTubeColors.background,
          elevation: 0,
        ),
        textTheme: const TextTheme(
          titleLarge: TextStyle(color: AiTubeColors.onBackground),
          titleMedium: TextStyle(color: AiTubeColors.onBackground),
          bodyLarge: TextStyle(color: AiTubeColors.onSurface),
          bodyMedium: TextStyle(color: AiTubeColors.onSurfaceVariant),
        ),
      ),
      // Use custom route handling to support deep linking with URL parameters on web
      onGenerateRoute: (settings) {
        // The home screen is the default fallback
        return MaterialPageRoute(builder: (_) => home);
      },
      home: home,
    );
  }
}