youtube_explode/lib/src/reverse_engineering/responses/embed_page.dart

60 lines
1.5 KiB
Dart
Raw Normal View History

2020-05-31 23:36:23 +02:00
import 'dart:convert';
import 'package:html/dom.dart';
import 'package:html/parser.dart' as parser;
2020-06-03 13:18:37 +02:00
2020-06-03 23:02:21 +02:00
import '../../extensions/helpers_extension.dart';
2020-06-05 16:17:08 +02:00
import '../../retry.dart';
2020-06-03 23:02:21 +02:00
import '../youtube_http_client.dart';
2020-05-31 23:36:23 +02:00
2020-07-16 20:02:54 +02:00
///
2020-05-31 23:36:23 +02:00
class EmbedPage {
2020-10-17 22:09:52 +02:00
static final _playerConfigExp = RegExp(r"'PLAYER_CONFIG':\s*(\{.*\})\}");
2020-05-31 23:36:23 +02:00
final Document _root;
2020-06-22 17:40:57 +02:00
_PlayerConfig _playerConfig;
String __playerConfigJson;
2020-05-31 23:36:23 +02:00
2020-07-16 20:02:54 +02:00
///
2020-06-03 13:18:37 +02:00
_PlayerConfig get playerconfig {
2020-06-22 17:40:57 +02:00
if (_playerConfig != null) {
return _playerConfig;
}
2020-06-03 13:18:37 +02:00
var playerConfigJson = _playerConfigJson;
if (playerConfigJson == null) {
return null;
}
2020-06-22 17:40:57 +02:00
return _playerConfig = _PlayerConfig(json.decode(playerConfigJson));
2020-06-03 13:18:37 +02:00
}
2020-05-31 23:36:23 +02:00
2020-06-22 17:40:57 +02:00
String get _playerConfigJson => __playerConfigJson ??= _root
2020-05-31 23:36:23 +02:00
.getElementsByTagName('script')
.map((e) => e.text)
2020-06-05 16:17:08 +02:00
.map((e) => _playerConfigExp.firstMatch(e)?.group(1))
2020-06-03 13:18:37 +02:00
.firstWhere((e) => !e.isNullOrWhiteSpace, orElse: () => null);
2020-05-31 23:36:23 +02:00
2020-07-16 20:02:54 +02:00
///
2020-06-22 17:40:57 +02:00
EmbedPage(this._root);
2020-07-16 20:02:54 +02:00
///
2020-05-31 23:36:23 +02:00
EmbedPage.parse(String raw) : _root = parser.parse(raw);
2020-07-16 20:02:54 +02:00
///
2020-06-03 13:18:37 +02:00
static Future<EmbedPage> get(YoutubeHttpClient httpClient, String videoId) {
2020-05-31 23:36:23 +02:00
var url = 'https://youtube.com/embed/$videoId?hl=en';
return retry(() async {
var raw = await httpClient.getString(url);
return EmbedPage.parse(raw);
});
}
}
class _PlayerConfig {
// Json parsed map.
final Map<String, dynamic> _root;
_PlayerConfig(this._root);
2020-06-05 16:17:08 +02:00
String get sourceUrl => 'https://youtube.com${_root['assets']['js']}';
2020-05-31 23:36:23 +02:00
}