Regex YouTube shorts url javascript python - javascript

I am making a board where users can post text, photo, and YouTube video link
I am trying to generate embed url from different types of YouTube urls that user copy and paste.
thanks Stackoverflow gods, I almost got it but not 100%
my js regex for ajax call to api
const ytRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$/
...
let video = $('#post-video').val();
if (ytRegex.test(video)) {
video = $('#post-video').val();
} else {
video = 0;
}
...
my python regex
video_receive = request.form['video_give']
video_id1 = re.findall("(https?\:\/\/)?(www\.)?(youtube\.com)\/.+$", video_receive)
video_id2 = re.findall("(https?\:\/\/)?(www\.)?(youtu\.?be)\/.+$", video_receive)
video_id3 = re.findall("(https?\:\/\/)?(www\.)?(youtube\.com)\/(shorts).+$", video_receive)
if video_id1 :
link = video_receive.split("=")[1]
embed = "https://www.youtube.com/embed/"
video = embed + link
elif video_id2:
link = video_receive.split("/")[3]
embed = "https://www.youtube.com/embed/"
video = embed + link
elif video_id3:
link = video_receive.split("/")[4]
embed = "https://www.youtube.com/embed/"
video = embed + link
else:
video = 1
I am targetting 3 example types of yt urls with variables video_id#
https://www.youtube.com/watch?v=bjkVUaFhwno
https://youtu.be/BEkxOupf9Zc
https://youtube.com/shorts/UZsysDAUHAY?feature=share
1 is for desktop share url for yt video and yt shorts
2 is mobile share url for yt video
3 is mobile share url for yt shorts
In my python code,
if video_id1 & elif video_id2 works fine but problem arise after I added elif video_id3
when I test with https://youtube.com/shorts/UZsysDAUHAY?feature=share
my code stores https://www.youtube.com/embed/share into db
It seems like if video_id1 is working on video_id3 format. I assume this because the testing url has = before share and if video_id1 has .split("=") condition.
when I delete ?feature=share from the testing url, my web page give me error(POST...500 (INTERNAL SERVER ERROR)) not even submitting to db due to ajax call error. but works with original testing url.
Please advise me where I am getting wrong with yt shorts url.

The regex you use for the first pattern will also match your shorts urls, simply just check for pattern 3 first.

Related

python set variable equal to null if no input else not certain type then string

I am making a board where you can post text, link, photo, and video.
I use python flask, JavaScript for this
For video posting part, I wanted users to input YouTube link URL and I set this to automatically change into embed address. My python and ajax code work fine with YouTube URL format but
the problem is when user input nothing for the video URL or put random letter or non-YouTube link format to the video link input.
python
#app.route('/post', methods=['POST'])
def savingPost():
...
link = request.form['video_give'].split("=")[1]
embed = "https://www.youtube.com/embed/"
video = embed + link
doc = {
...
'video': video,
...
}
db.collection.insert_one(doc)
return jsonify({'msg': 'Posted!'})
javascript
function postArticle(img_location) {
...
let video = $('#post-video').val();
...
$.ajax({
type: "POST",
url: "/post",
data: {..., video_give: video},
success: function (response) {
alert(response["msg"]);
}
})
}
How can I set code for situations for no input or other than youtube format?
A similar question that helps this question is Regex for youtube URL.
You can use RegExps to validate the youtube links before you send the request.
const ytRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$/
function postArticle(img_location) {
...
let video = $('#post-video').val();
if (ytRegex.test(video)){
// Good format
} else {
// Bad format
}
...
}
You could verify that the posted URL is a valid youtube link on the backend using regex.
import re
user_input = "https://youtube.com/watch?v=2bfsoiadbf"
video_id = re.findall("http[s]?:\/\/(?:youtube\.com|youtu\.be)\/watch\?(?:\w+\=(\w+)[\&]?)*", user_input)
if video_id:
# do something with the youtube id
embed = "https://www.youtube.com/embed/"
video = embed + video_id[0]
else:
# respond with an error
this way you only handle the URL if it's valid

Get video id from youtube link

i have this line:
token = videos.results[i].titlemay_link.split("?v=")[1];
videos.results[i].titlemay_link = the link to a youtube video en the split only returns the code.
now the problem is that some youtube links i get are links like this:
https://www.youtube.com/watch?v=1zO9nWgI_LY&feature=youtu.be
so the output i get is:
1zO9nWgI_LY&feature=youtu.be
this will not load the video in the embed player, how can i get rid of the
&feature=youtu.be
thanks!
token = videos.results[i].titlemay_link.split("?v=")[1];
token = token.split("&")[0];
But that won't be sufficient in most of the cases as youtube URLs gets complicated many times, here is a more roust method to fetch the youtube video ID
function youtube_parser(url){
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = url.match(regExp);
return (match&&match[7].length==11)? match[7] : false;
}
These are the types of URLs supported
http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
Add one more condition after you get token and check using .contains as below:
if(token.contains('&'))
token=token.split('&')[0];

Print youtube video title script with just video ID provided

I'm doing a simple (not so simple for me) youtube BBCode that hides the embedded video in a dropdown, for when there's too many embedded videos, to not cause the web browser to lag trying to load them all at the same time.
I want the dropdown to display the video thumbnail (got that sorted) and title.
I don't know much about javascript, and the other questions and answers about this haven't worked for me. Example:Fetching YouTube video title from known video id Maybe I don't know how to implement it.
I just need the script to get the youtube vide title from the id and print it, really.
Edit: YouTube shut down the v2 API in 2015, take a look at the documentation of the new API v3 for a working code.
https://stackoverflow.com/a/30685729/753676
Copied from https://stackoverflow.com/a/10597710/753676
You can do this with plain JavaScript like this:
<script
type="text/javascript"
src="https://gdata.youtube.com/feeds/api/videos/videoid?v=2&alt=json-in-script&format=5&callback=getTitle">
</script>
And then:
function getTitle(data) {
var feed = data.feed;
var entries = feed.entry || [];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var title = entry.title.$t;
}
}
Unfortunately, since version 3. This is no longer possible with the youtube API without auth.
You can use noembed however without Auth if you want to grab basic info about the video.
I.E http://noembed.com/embed?url=http%3A//www.youtube.com/watch%3Fv%3DbDOYN-6gdRE&callback=my_embed_function
The response is JSON.

Creating Youtube downloader Plugin via javascript

I am planning to create video downloader plugin.So basically we need signatures to download an video file from youtube.I referred other working plugins..They convert the signature to some format.
Basically orginal signature in youtube page source is
BBB4D55F9CF4387F77958A6960CA96708C73AB59B.037D413F53291E957891898307BBF1C41B6037D77D7
Plugins convert the above signature to below signature.
BB4D55F9CF4787F77958A6960CA96708C73AB59B.037D413F53291E957891898307BBF1C41B6037D3
I want to know is these some kind of hash ? has any one came across similar hash ?
Secret of Cipher Signature code:
Ciphered signature in Youtube are just 'scrambled' signature that you have to rearrange them according to the Algorithm present in the player file (HTML5 player or Flash player).
For example http://www.youtube.com/watch?v=UxxajLWwzqY is presently using the following HTML5 player file : //s.ytimg.com/yts/jsbin/html5player-vfltdb6U3.js
in this file you can easily search for signature decipher code by searching for 'sig'. Here in this case the Algo is:
function bz(a) {
a = a.split("");
a = cz(a, 61);
a = cz(a, 5);
a = a.reverse();
a = a.slice(2);
a = cz(a, 69);
a = a.slice(2);
a = a.reverse();
return a.join("")
}
function cz(a, b) {
var c = a[0];
a[0] = a[b % a.length];
a[b] = c;
return a
};
Above is the deciphering code.
But be aware, it keeps on changing when they change the player file, so you have to keep a tap on the player file being used.
Also to download videos with cipher signature you have to take care of the sending the same cookies, using the same user-agent header, sending the request from the same IP address, and sending the request shortly after extraction. All these are or were required at some point
For more check this API: Cipher API
Another cool API: YTstream API
you can follow on github the youtube-dl python application: it's the best small command-line program to download video that i've found so far, with a great team behind. More specifically, you can visit the youtube-script , in order to grab the latest working decyphering algorithm.
Have fun :)
now a days you can easily create your own youtube downloader via youtube-dl. It also support more than youtube.
I also made a tutorial on how to do this. You can read more about that here

how to get youtube video id from url

I am trying to check whether a url is a valid youtube video URL and get the youtube video ID from it, so far I am using a simple javascript split function in order to achieve this, however this has some minor disadvantages as youtube has multiple URL's.
I have been viewing other stackoverflow threads however all of them only support 1 specific URL which is not what I need.
I need something that matches all these URL's:
http(s)://www.youtu.be/videoID
http(s)://www.youtube.com/watch?v=videoID
(and optionally any other short URL's which the script automatically detects whether it contains a youtube video)
Any ideas which can be handled by the browser quick/efficient is greatly appreciated!
Try this:
var url = "...";
var videoid = url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/);
if(videoid != null) {
console.log("video id = ",videoid[1]);
} else {
console.log("The youtube url is not valid.");
}
see regex:
/
(?:https?:\/{2})? // Optional protocol, if have, must be http:// or https://
(?:w{3}\.)? // Optional sub-domain, if have, must be www.
youtu(?:be)? // The domain. Match 'youtu' and optionally 'be'.
\.(?:com|be) // the domain-extension must be .com or .be
(?:\/watch\?v=|\/)([^\s&]+) //match the value of 'v' parameter in querystring from 'watch' directory OR after root directory, any non-space value.
/
Maybe you should look at the Youtube API and try to see if there is a way to get a videoID by parsing the URL though the API.
Look at this SO post:
Youtube API - Extract video ID
This could be quick:
var url = 'http://www.youtu.be/543221';
//http://www.youtube.com/watch?v=SNfYz6Yw0W8&feature=g-all-esi would work also
var a = url.split("v=")[1];
a = a != undefined ? a : url.split("youtu.be/")[1];
b = a.split("&")[0];
the variable c will have your id. Quick. The regex is nicer... harder to read though. I have modified my code to account for both.
There are too many kind:
latest short format: http://youtu.be/NLqAF9hrVbY
iframe: http://www.youtube.com/embed/NLqAF9hrVbY
iframe (secure): https://www.youtube.com/embed/NLqAF9hrVbY
object param: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
object embed: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
watch: http://www.youtube.com/watch?v=NLqAF9hrVbY
users: http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo
ytscreeningroom: http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I
any/thing/goes!: http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/2/PPS-8DMrAn4
any/subdomain/too: http://gdata.youtube.com/feeds/api/videos/NLqAF9hrVbY
more params: http://www.youtube.com/watch?v=spDj54kf-vY&feature=g-vrec
query may have dot: http://www.youtube.com/watch?v=spDj54kf-vY&feature=youtu.be
(Source: How do I find all YouTube video ids in a string using a regex?)
The best way is limiting input-data.
Good luck
try this code
var url = "...";
var videoid = url.match((?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11}));
if(videoid != null) {
console.log("video id = ",videoid[1]);
} else {
console.log("The youtube url is not valid.");
}
The Regex is from
YouTube video ID regex
you can do it easily using preg_match here is the example:$url = "http://www.youtube.com/watch?v=YzOt12co4nk&feature=g-vrec";
preg_match('/v=([0-9a-zA-Z]+)/', $url, $matches);
$vid = $matches[1];
Now you will have the video id as: $vid = YzOt12co4nk;
I found a simple way of doing it without using regex.
I made a function which does it for you:
function getLink(url){
fetch('www.youtube.com/oembed?url=' + url).then(res => {
var thumbnailUrl = res.thumbnail_url;
var id = thumbnail_url.split('vi/')[1].substring(0, 11);
return id;}
)
}
console.log(getLink(your_url));
// here replace 'your_url' with your specified youtube url.
All this does is, it uses youtube api and passes your url as an parameter, and youtube take cares of the type of the url, so you dont have to worry about it. The next thing is, the function then takes the 'thumbnail_url' data from that api, and then splits the thumbnail's url accordingly to find the ID of the video.

Categories

Resources