Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching between Youku and YouTube based on whether you're in China

I'm hosting a conference website where I want to embed a Youku video if you're in China and a YouTube video otherwise. The conference website is being served through a CDN inside the Great Firewall. I was given the code below to switch between internal and external versions of Youku.

Unfortunately, ipinfo.io does not seem to be accessible inside the Great Firewall, so the code times out after 10 seconds.

I've considered rewriting the page to use a Youku video by default, writing a small, non-blocking JavaScript function that tries to reach YouTube. If it can, replace the Youku with YouTube. If it can't, exit harmlessly. That way, the reachability of YouTube becomes the key test, not whether you're in China.

Alternatively, I've thought of hosting the video on my site, so that it will be replicated via the CDN inside the Great Firewall. However, that would mean that the video would always be downloaded at full resolution, even if you're on a slow connection.

Any better suggestions on how to switch between Youku and Youtube, or more generally have a video playable both inside and outside China?

jQuery.get("https://ipinfo.io", function(response) {
    var country = response.country;

    if(country == 'CN') {
        youku.attr('src',chinaVideo)
    } else {
        youku.attr('src',generalVideo)
    }
}, "jsonp");
like image 243
Dan Kohn Avatar asked Jul 21 '18 02:07

Dan Kohn


1 Answers

Here is the JavaScript we are going with:

$(document).ready(function (){
    var country = '',
    youku = $('#youku');

    $.ajax({
        url: "https://ipinfo.io",
        dataType: "jsonp",
        success: function(response){
            var country = response.country;

            if(country != 'CN') {
                youku.attr('src','https://www.youtube.com/embed/K3cEE5h7c1s')
            }
         },
         error: function(){
            console.log('sorry...')
         },
         timeout: 5000
    });     
});

We are including the Youku link in the HTML and switching to YouTube if country is not China. This still works if connecting to ipinfo.io times out, which sometimes happens in China.

Edit: revised to add a 5 second timeout.

Edit2: We implemented this as an open source Wordpress plugin, in case others are interested. https://github.com/cncf/china-video-block

like image 114
Dan Kohn Avatar answered Oct 19 '22 23:10

Dan Kohn