Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 18,915 Bytes
5acd9c3 6c71972 d5e94b5 5acd9c3 83f2577 5acd9c3 2f88b0d f26b729 5acd9c3 6c71972 5acd9c3 6c71972 5acd9c3 6c71972 5acd9c3 6c71972 5acd9c3 6c71972 5acd9c3 2f88b0d 49dcd35 5acd9c3 83f2577 2f88b0d 2e813e6 83f2577 5acd9c3 49dcd35 5acd9c3 49dcd35 5acd9c3 49dcd35 5acd9c3 2e813e6 2f88b0d 2e813e6 5acd9c3 d5e94b5 2e813e6 2f88b0d 2e813e6 d5e94b5 5acd9c3 6c71972 5acd9c3 d5e94b5 5acd9c3 f26b729 5acd9c3 7a46537 f26b729 5acd9c3 f26b729 5acd9c3 7a46537 5acd9c3 7a46537 5acd9c3 2f88b0d 7ab27ea 2f88b0d 5acd9c3 6c71972 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 |
// lib/screens/video_screen.dart
import 'dart:async';
import 'package:aitube2/screens/home_screen.dart';
import 'package:aitube2/widgets/chat_widget.dart';
import 'package:aitube2/widgets/search_box.dart';
import 'package:aitube2/widgets/web_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:universal_html/html.dart' if (dart.library.io) 'package:aitube2/services/html_stub.dart' as html;
import '../config/config.dart';
import '../models/video_result.dart';
import '../services/websocket_api_service.dart';
import '../services/settings_service.dart';
import '../theme/colors.dart';
import '../widgets/video_player_widget.dart';
class VideoScreen extends StatefulWidget {
final VideoResult video;
const VideoScreen({
super.key,
required this.video,
});
@override
State<VideoScreen> createState() => _VideoScreenState();
}
class _VideoScreenState extends State<VideoScreen> {
Future<String>? _captionFuture;
final _websocketService = WebSocketApiService();
bool _isConnected = false;
late VideoResult _videoData;
final _searchController = TextEditingController();
bool _isSearching = false;
// Subscription for limit statuses
StreamSubscription? _anonLimitSubscription;
StreamSubscription? _deviceLimitSubscription;
@override
void initState() {
super.initState();
_videoData = widget.video;
_searchController.text = _videoData.title;
_websocketService.addSubscriber(widget.video.id);
// Listen for changes to anonymous limit status
_anonLimitSubscription = _websocketService.anonLimitStream.listen((exceeded) {
if (exceeded && mounted) {
_showAnonLimitExceededDialog();
}
});
// Listen for changes to device limit status (for VIP users on web)
_deviceLimitSubscription = _websocketService.deviceLimitStream.listen((exceeded) {
if (exceeded && mounted) {
_showDeviceLimitExceededDialog();
}
});
_initializeConnection();
}
Future<void> _initializeConnection() async {
try {
await _websocketService.connect();
// Check if anonymous limit is exceeded
if (_websocketService.isAnonLimitExceeded) {
if (mounted) {
_showAnonLimitExceededDialog();
}
return;
}
if (mounted) {
setState(() {
_isConnected = true;
_captionFuture = _generateCaption();
});
}
} catch (e) {
if (mounted) {
setState(() => _isConnected = false);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to connect to server: $e'),
action: SnackBarAction(
label: 'Retry',
onPressed: _initializeConnection,
),
),
);
}
}
}
void _showAnonLimitExceededDialog() async {
// Create a controller outside the dialog for easier access
final TextEditingController controller = TextEditingController();
final settings = await showDialog<String>(
context: context,
barrierDismissible: false,
builder: (BuildContext dialogContext) {
bool obscureText = true;
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: const Text(
'Connection Limit Reached',
style: TextStyle(
color: AiTubeColors.onBackground,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_websocketService.anonLimitMessage.isNotEmpty
? _websocketService.anonLimitMessage
: 'Anonymous users can enjoy 1 stream per IP address. If you are on a shared IP please enter your HF token, thank you!',
style: const TextStyle(color: AiTubeColors.onSurface),
),
const SizedBox(height: 16),
const Text(
'Enter your HuggingFace API token to continue:',
style: TextStyle(color: AiTubeColors.onSurface),
),
const SizedBox(height: 8),
TextField(
controller: controller,
obscureText: obscureText,
decoration: InputDecoration(
labelText: 'API Key',
labelStyle: const TextStyle(color: AiTubeColors.onSurfaceVariant),
suffixIcon: IconButton(
icon: Icon(
obscureText ? Icons.visibility : Icons.visibility_off,
color: AiTubeColors.onSurfaceVariant,
),
onPressed: () => setState(() => obscureText = !obscureText),
),
),
onSubmitted: (value) {
Navigator.pop(dialogContext, value);
},
),
],
),
backgroundColor: AiTubeColors.surface,
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text(
'Cancel',
style: TextStyle(color: AiTubeColors.onSurfaceVariant),
),
),
FilledButton(
onPressed: () => Navigator.pop(dialogContext, controller.text),
style: FilledButton.styleFrom(
backgroundColor: AiTubeColors.primary,
),
child: const Text('Save'),
),
],
);
}
);
},
);
// Clean up the controller
controller.dispose();
// If user provided an API key, save it and retry connection
if (settings != null && settings.isNotEmpty) {
// Save the API key
final settingsService = SettingsService();
await settingsService.setHuggingfaceApiKey(settings);
// Retry connection
if (mounted) {
_initializeConnection();
}
}
}
void _showDeviceLimitExceededDialog() async {
await showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext dialogContext) {
return AlertDialog(
title: const Text(
'Too Many Connections',
style: TextStyle(
color: AiTubeColors.onBackground,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_websocketService.deviceLimitMessage,
style: const TextStyle(color: AiTubeColors.onSurface),
),
const SizedBox(height: 16),
const Text(
'Please close some of your other browser tabs running AiTube to continue.',
style: TextStyle(color: AiTubeColors.onSurface),
),
],
),
backgroundColor: AiTubeColors.surface,
actions: [
FilledButton(
onPressed: () {
Navigator.pop(dialogContext);
// Try to reconnect after dialog is closed
if (mounted) {
Future.delayed(const Duration(seconds: 1), () {
_initializeConnection();
});
}
},
style: FilledButton.styleFrom(
backgroundColor: AiTubeColors.primary,
),
child: const Text('Try Again'),
),
],
);
},
);
}
Future<String> _generateCaption() async {
if (!_isConnected) {
return 'Error: Not connected to server';
}
try {
return await _websocketService.generateCaption(
_videoData.title,
_videoData.description,
);
} catch (e) {
return 'Error generating caption: $e';
}
}
void _shareVideo() async {
// For non-web platforms
final uri = Uri.parse("https://aitube.at");
final params = Map<String, String>.from(uri.queryParameters);
// Ensure title and description are in the URL parameters
params['title'] = _videoData.title;
params['description'] = _videoData.description;
// Create a new URL with updated parameters
final shareUri = uri.replace(queryParameters: params);
final shareUrl = shareUri.toString();
try {
// this is a text to share on social media
// final textToCopy = 'Messing around with #aitube2 👀 $shareUrl';
// but for now let's just use the url
final textToCopy = shareUrl;
// Copy to clipboard
await Clipboard.setData(ClipboardData(text: textToCopy));
// Show a temporary "Copied!" message
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Copied to clipboard!'),
backgroundColor: Colors.green,
duration: Duration(seconds: 3),
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error copying to clipboard: $e')),
);
}
}
}
// Reference to the current VideoPlayerWidget to force reset when needed
Key _videoPlayerKey = UniqueKey();
Future<void> _onVideoSearch(String query) async {
if (!_isConnected) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Not connected to server')),
);
return;
}
setState(() => _isSearching = true);
// Update URL parameter on web platform
if (kIsWeb) {
// We'll update title and description parameters after we get the search result
// removeUrlParameter('search') will happen after we get the result
}
try {
// First, cancel any requests for the current video
_websocketService.cancelRequestsForVideo(_videoData.id);
// Get the search result
final result = await _websocketService.search(query);
if (mounted) {
setState(() {
// Generate a new key to force recreation of the VideoPlayerWidget
_videoPlayerKey = UniqueKey();
_videoData = result;
_isSearching = false;
});
// Now that we have the result, update the URL parameter on web platform
if (kIsWeb) {
// Update title and description parameters
updateUrlParameter('title', result.title);
updateUrlParameter('description', result.description);
removeUrlParameter('search');
}
}
} catch (e) {
if (mounted) {
setState(() => _isSearching = false);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error: $e')),
);
}
}
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final isWideScreen = constraints.maxWidth >= 900;
return Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(kToolbarHeight + 16),
child: Padding(
padding: const EdgeInsets.only(top: 16),
child: AppBar(
leading: IconButton(
icon: Navigator.canPop(context)
? const Icon(Icons.arrow_back, color: AiTubeColors.onBackground)
: const Icon(Icons.home, color: AiTubeColors.onBackground),
onPressed: () {
// Restore the search parameter in URL when navigating back
if (kIsWeb) {
// Remove the title and description parameters
removeUrlParameter('title');
removeUrlParameter('description');
// Get the search query from the video description
final searchQuery = _videoData.description.trim();
if (searchQuery.isNotEmpty) {
// Update URL to show search parameter again
updateUrlParameter('search', searchQuery);
}
}
if (Navigator.canPop(context)) {
Navigator.pop(context);
} else {
// Navigate to home screen if we can't go back
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const HomeScreen()),
);
}
},
),
titleSpacing: 0,
title: Padding(
padding: const EdgeInsets.all(8),
child: SearchBox(
controller: _searchController,
isSearching: _isSearching,
enabled: _isConnected,
onSearch: _onVideoSearch,
onCancel: () {
setState(() => _isSearching = false);
},
),
),
actions: [
IconButton(
icon: Icon(
_isConnected ? Icons.cloud_done : Icons.cloud_off,
color: _isConnected ? Colors.green : Colors.red,
),
onPressed: _isConnected ? null : _initializeConnection,
),
],
),
),
),
body: SafeArea(
child: isWideScreen
? Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: _buildMainContent(),
),
if (Configuration.instance.showChatInVideoView) ...[
const SizedBox(width: 16),
Padding(
padding: const EdgeInsets.only(right: 16),
child: ChatWidget(videoId: widget.video.id),
),
],
],
)
: Column(
children: [
Expanded(
child: _buildMainContent(),
),
if (Configuration.instance.showChatInVideoView) ...[
const SizedBox(height: 16),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: ChatWidget(
videoId: widget.video.id,
isCompact: true,
),
),
),
],
],
),
),
);
},
);
}
Widget _buildMainContent() {
return Container(
color: Theme.of(context).scaffoldBackgroundColor,
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
physics: const AlwaysScrollableScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Video Player with unique key to force recreation when needed
VideoPlayerWidget(
key: _videoPlayerKey,
video: _videoData,
initialThumbnailUrl: _videoData.thumbnailUrl,
autoPlay: true,
),
const SizedBox(height: 16),
// Collapsible Title and Description Section
_buildCollapsibleInfoSection(),
],
),
),
);
}
Widget _buildCollapsibleInfoSection() {
return ExpansionTile(
initiallyExpanded: false,
tilePadding: EdgeInsets.zero,
title: Row(
children: [
Expanded(
child: Text(
_videoData.title,
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
color: AiTubeColors.onBackground,
fontWeight: FontWeight.bold,
),
),
),
IconButton(
icon: const Icon(Icons.share, color: AiTubeColors.primary),
onPressed: _shareVideo,
tooltip: 'Share prompt',
),
],
),
iconColor: AiTubeColors.primary,
collapsedIconColor: AiTubeColors.primary,
backgroundColor: Colors.transparent,
collapsedBackgroundColor: Colors.transparent,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Tags
if (_videoData.tags.isNotEmpty) ...[
Wrap(
spacing: 8,
runSpacing: 8,
children: _videoData.tags.map((tag) => Chip(
label: Text(tag),
backgroundColor: AiTubeColors.surface,
labelStyle: const TextStyle(color: AiTubeColors.onSurface),
)).toList(),
),
const SizedBox(height: 16),
],
// Description Section
const Text(
'Description',
style: TextStyle(
color: AiTubeColors.onBackground,
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
const SizedBox(height: 8),
Text(
_videoData.description,
style: const TextStyle(
color: AiTubeColors.onSurface,
height: 1.5,
),
),
],
),
],
);
}
@override
void dispose() {
// Cancel any pending video-related requests
_websocketService.cancelRequestsForVideo(widget.video.id);
_websocketService.removeSubscriber(widget.video.id);
// Cleanup other resources
_searchController.dispose();
_anonLimitSubscription?.cancel();
_deviceLimitSubscription?.cancel();
super.dispose();
}
} |