youtube_explode/lib/src/videos/video_id.dart

81 lines
2.3 KiB
Dart
Raw Normal View History

2020-06-03 13:18:37 +02:00
import 'package:equatable/equatable.dart';
2020-06-03 23:02:21 +02:00
import '../extensions/helpers_extension.dart';
2020-06-03 13:18:37 +02:00
/// Encapsulates a valid YouTube video ID.
class VideoId with EquatableMixin {
2020-06-03 13:18:37 +02:00
static final _regMatchExp = RegExp(r'youtube\..+?/watch.*?v=(.*?)(?:&|/|$)');
static final _shortMatchExp = RegExp(r'youtu\.be/(.*?)(?:\?|&|/|$)');
static final _embedMatchExp = RegExp(r'youtube\..+?/embed/(.*?)(?:\?|&|/|$)');
/// ID as string.
final String value;
/// Initializes an instance of [VideoId] with a url or video id.
2021-03-04 12:20:00 +01:00
VideoId(String idOrUrl) : value = parseVideoId(idOrUrl) ?? '' {
if (value.isEmpty) {
2020-06-05 16:17:08 +02:00
throw ArgumentError.value(
idOrUrl, 'urlOrUrl', 'Invalid YouTube video ID or URL');
}
}
2020-06-03 13:18:37 +02:00
@override
String toString() => value;
@override
List<Object> get props => [value];
/// Returns true if the given [videoId] is valid.
static bool validateVideoId(String videoId) {
if (videoId.isNullOrWhiteSpace) {
return false;
}
if (videoId.length != 11) {
return false;
}
return !RegExp(r'[^0-9a-zA-Z_\-]').hasMatch(videoId);
}
/// Parses a video id from url or if given a valid id as url returns itself.
/// Returns null if the id couldn't be extracted.
2021-03-04 12:20:00 +01:00
static String? parseVideoId(String url) {
2020-06-03 13:18:37 +02:00
if (url.isNullOrWhiteSpace) {
return null;
}
if (validateVideoId(url)) {
return url;
}
// https://www.youtube.com/watch?v=yIVRs6YSbOM
var regMatch = _regMatchExp.firstMatch(url)?.group(1);
2021-03-04 12:20:00 +01:00
if (!regMatch.isNullOrWhiteSpace && validateVideoId(regMatch!)) {
2020-06-03 13:18:37 +02:00
return regMatch;
}
// https://youtu.be/yIVRs6YSbOM
var shortMatch = _shortMatchExp.firstMatch(url)?.group(1);
2021-03-04 12:20:00 +01:00
if (!shortMatch.isNullOrWhiteSpace && validateVideoId(shortMatch!)) {
2020-06-03 13:18:37 +02:00
return shortMatch;
}
// https://www.youtube.com/embed/yIVRs6YSbOM
var embedMatch = _embedMatchExp.firstMatch(url)?.group(1);
2021-03-04 12:20:00 +01:00
if (!embedMatch.isNullOrWhiteSpace && validateVideoId(embedMatch!)) {
2020-06-03 13:18:37 +02:00
return embedMatch;
}
return null;
}
2020-06-05 20:08:04 +02:00
/// Converts [obj] to a [VideoId] by calling .toString on that object.
/// If it is already a [VideoId], [obj] is returned
factory VideoId.fromString(dynamic obj) {
if (obj is VideoId) {
return obj;
}
return VideoId(obj.toString());
}
2020-06-03 13:18:37 +02:00
}