使用oembed端点获取Instagram的视频媒体源

JFK*_*JFK 5 ajax jquery endpoints oembed instagram

上下文

我有一段(jQuery)ajax代码,在过去几周左右的时间里已经开心工作了大约9个月.

此代码使用Instagram的嵌入端点,允许我从普通的Instagram链接中获取媒体源(图像或视频),http://instagram.com/p/BUG/无论用户是谁,也不需要access_token.

简化示例:

var URL = "http://api.instagram.com/oembed?url=http://instagram.com/p/BUG/";
$(document).ready(function () {
    $.ajax({
        url: URL,
        dataType: "jsonp",
        cache: false,
        success: function (response) {
            console.log(response.url);
        },
        error: function () {
            console.log("couldn't process the instagram url");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,response.url将返回完整的媒体URL源,如:

http://photos-a.ak.instagram.com/xxxx/1234_123456123_123456_n.jpg // image or
http://distilleryvesper3-15.ak.instagram.com/b0c957463548362858_101.mp4 // video
Run Code Online (Sandbox Code Playgroud)

然后我可以使用返回的URL将媒体文件嵌入我的网页.

注意:

由于想法是获取任何Instagram链接的URL源而不管用户,因此使用媒体端点不是一种选择.


问题

Instagram的oembed端点允许您获得json响应,直到最近几周才有这种结构:

{
    "provider_url" : "http:\/\/instagram.com\/",
    "media_id" : "123456789_123456789",
    "title" : "the title",
    "url" : "http:\/\/photos-a.ak.instagram.com\/hphotos-ak-xfp1\/12345678_123456789012345_1234567890_n.jpg",
    "author_name" : "{the user name}",
    "height" : 640,
    "width" : 640,
    "version" : "1.0",
    "author_url" : "http:\/\/instagram.com\/{the user name}",
    "author_id" : 123456789,
    "type" : "photo",
    "provider_name" : "Instagram"
}
Run Code Online (Sandbox Code Playgroud)

您可能已经注意到,我的ajax代码对属性名称特别感兴趣,该名称url包含完整媒体的URL.

请注意,此json响应(如今)对于Instagram图像仍然有效,但是,如果原始Instagram的链接是视频,那么让我们使用一个真实的例子:http://instagram.com/p/mOFsFhAp4f/(CocaCola(c))该json响应不返回任何url了关键.

似乎在引入网络嵌入之后,Instagram已经决定用他们的(oembed)json响应中url的一个html属性替换关键视频,其中包含嵌入的iframe,如:

{
    ...

    "html" : "\u003ciframe src=\"http:\/\/instagram.com\/p\/BUG\/embed\" width=\"616\" height=\"716\" frameborder=\"0\" scrolling=\"no\" allowtransparency=\"true\"\u003e\u003c\/iframe\u003e",

    ...
}
Run Code Online (Sandbox Code Playgroud)

...当然,这会破坏我的代码,因为它response.url是未定义的.


问题

如何在Instagram json响应更改后获取完整视频的URL?

不幸的是我在Instagram的开发者网站上找不到任何适当的文档或更改日志(他们有一个很好的API,但文档很差.)

注意,问题是关于Instagram API(v1)嵌入端点而不是jQuery或ajax问题.

我正在寻找(一个未记录的)Instagram的API选项,端点,oembed或者其他(不需要access_token),它允许我从正常的Instagram链接中检索到媒体视频的直接链接(最好在json响应之后)无论用户......还是愿意考虑不太苛刻的解决方法.

Pro*_*eek 5

这可能不是最佳或最佳答案,但我相信这将解决您现在的问题,因此您可能会认为这是一个解决方法:

感谢whateverorigin.org服务,我们可以获取交叉源json,它包含您可能请求的所有数据,您只需将返回的对象转换为字符串,然后使用正则表达式获取您需要的任何数据.

var myvideourl="http://instagram.com/p/mOFsFhAp4f/"
$.ajaxSetup({
    scriptCharset: "utf-8", //maybe "ISO-8859-1"
    contentType: "application/json; charset=utf-8"
});

$.getJSON('http://whateverorigin.org/get?url=' + 
    encodeURIComponent(myvideourl) + '&callback=?',
    function(data) {

        var xx=data.contents
        var dataindex=xx.search('<meta property="og:video" content=')
        var end=xx.indexOf('/>', dataindex);
        var yy=xx.slice(dataindex,end+2)
        var metaobject=$.parseHTML(yy)
        alert(metaobject[0].content)
        console.log(metaobject[0].content)
});
Run Code Online (Sandbox Code Playgroud)

这是和例子:

JS小提琴演示

适合我,但只在CocaCola视频上试过,没有在其他链接上尝试过.


JFK*_*JFK 4

更新[2015 年 3 月]:有关此解决方案的扩展和更新版本,请访问http://www.picssel.com/build-a-simple-instagram-api-case-study/


@ProllyGeek 的答案提供了一个很好的解决方法来抓取 Instagram 视频页面(当之无愧的赏金),但是它依赖于whateverorigin.org第三方服务,除非该服务最终不可用,否则该服务将正常工作。

由于最新的情况已经在生产环境中发生在我身上,我必须寻找更可靠的替代方案,因此我决定使用 phpfile_get_contents从自己托管的 PHP 模块中抓取视频链接。

我基本上遵循@ProllyGeek提出的相同逻辑,但转换为PHP:

getVideoLink.php模块:

<?php
header('Content-Type: text/html; charset=utf-8');
function clean_input($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = strip_tags($data);
    $data = htmlspecialchars($data);
    return $data;
};
$instalink = clean_input( $_GET['instalink'] );    
if (!empty($instalink)) {
    $response = clean_input( @ file_get_contents( $instalink ) );
    $start_position = strpos( $response ,'video_url&quot;:&quot;' ); // the start position
    $start_positionlength = strlen('video_url&quot;:&quot;'); // string length to trim before
    $end_position = strpos($response ,'&quot;,&quot;usertags'); // the end position
    $mp4_link = substr( $response, ( $start_position + $start_positionlength ), ( $end_position - ( $start_position + $start_positionlength ) ) );
    echo $mp4_link;
};
?>
Run Code Online (Sandbox Code Playgroud)

当然,您可能需要手动分析响应才能知道您在寻找什么。

然后从我的主页对 PHP 模块进行 AJAX 调用:

var instaLink = "http://instagram.com/p/mOFsFhAp4f/"; // the Coca Cola video link
jQuery(document).ready(function ($) {
    $.ajax({
        url: "getVideoLink.php?instalink="+instaLink,
        dataType : "html",
        cache : false,
        success : function (data) {
            console.log(data); // returns http://distilleryvesper3-15.ak.instagram.com/b0ce80e6b91111e3a16a122b8b9af17f_101.mp4
        },
        error : function () {
            console.log("error in ajax");
        }
    });
}); // ready 
Run Code Online (Sandbox Code Playgroud)

假设您的主机支持 php 才能使用此方法。


编辑[2014 年 11 月 19 日]

我修改了getVideoLink.php模块(现在为getInstaLinkJSON.php ),以实际从特定的 Instagram 媒体链接获取JSON信息,例如http://instagram.com/p/mOFsFhAp4f/

这比仅仅抓取视频的 URL 有用得多,并且也可以用于图像。

新的getInstaLinkJSON.php代码:

<?php
function clean_input($data){
    $data = trim($data);
    $data = strip_tags($data);
    return $data;
};
// clean user input
function clean_input_all($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = strip_tags($data);
    $data = htmlspecialchars($data);
    return $data;
};
$instaLink = clean_input_all( $_GET['instaLink'] );

if( !empty($instaLink) ){
    header('Content-Type: application/json; charset=utf-8');
    $response = clean_input( @ file_get_contents($instaLink) );
    $response_length = strlen($response);
    $start_position = strpos( $response ,'window._sharedData = ' ); // the start position
    $start_positionlength = strlen('window._sharedData = '); // string length to trim before
    $trimmed = trim( substr($response, ( $start_position + $start_positionlength ) ) ); // trim extra spaces and carriage returns
    $jsondata = substr( $trimmed, 0, -1); // remove extra ";" added at the end of the javascript variable 
    echo $jsondata;
} elseif( empty($instaLink) ) {
    die(); //only accepts instaLink as parameter
}
?>
Run Code Online (Sandbox Code Playgroud)

我正在清理用户的输入和file_get_contents()响应,但是我不会从最后一个中删除斜杠HTML 字符,因为我将返回JSON响应。

然后AJAX调用:

var instaLink = "http://instagram.com/p/mOFsFhAp4f/"; // demo
jQuery.ajax({
    url: "getInstaLinkJSON.php?instalink=" + instaLink,
    dataType : "json", // important!!!
    cache : false,
    success : function ( response ) {
        console.log( response ); // returns json
        var media = response.entry_data.DesktopPPage[0].media;

        // get the video URL
        // media.is_video : returns true/false

        if( media.is_video ){
            console.log( media.video_url ); // returns http://distilleryvesper3-15.ak.instagram.com/b0ce80e6b91111e3a16a122b8b9af17f_101.mp4
        }
    },
    error : function () {
        console.log("error in ajax");
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑[2020 年 5 月 20 日]

目前正在使用 PHP

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
function clean_input($data){
    $data = trim($data);
    $data = strip_tags($data);
    return $data;
};
// clean user input
function clean_input_all($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = strip_tags($data);
    $data = htmlspecialchars($data);
    return $data;
};
$instaLink = clean_input_all( $_GET['instaLink'] );

if( !empty($instaLink) ){
    header('Content-Type: application/json; charset=utf-8');
    $response = clean_input( @ file_get_contents($instaLink) );
    $response_length = strlen($response);
    $start_position = strpos( $response ,'window._sharedData = ' ); // the start position
    $start_positionlength = strlen('window._sharedData = '); // string length to trim before
    $trimmed = trim( substr($response, ( $start_position + $start_positionlength ) ) ); // trim extra spaces and carriage returns
    $jsondata = substr( $trimmed, 0, -1); // remove extra ";" added at the end of the javascript variable 
    $jsondata = explode('window.__initialDataLoaded', $jsondata);
    echo substr(trim($jsondata[0]), 0, -1);
} elseif( empty($instaLink) ) {
    die(); //only accepts instaLink as parameter
}
?>
Run Code Online (Sandbox Code Playgroud)