1

I am currently using the Twitter API v1.1.

I am displaying the latest 5 tweets of a particular user. The API responds with a data object that contains an entities object which then contains an array of urls, that looks like the following.

display_url:"youtube.com/watch?v=WtM3wP…"
expanded_url:"https://www.youtube.com/watch?v=WtM3wPVhkik"
url:"https://www.youtube.com/watch?v=WtM3wPVhkik"

I want to display the tweets in a timeline with a thumbnail, or else an option to play the video from the page. Can anyone suggest a way of doing this. I couldn't find anything on SO, or through Google suggesting a solution.

The relevant twitter documentation can be found here.

See my code below if it helps:

get_tweets.php

<?php

require_once('twitter_proxy.php');

// Twitter OAuth Config options
$oauth_access_token = '********';
$oauth_access_token_secret = '********';
$consumer_key = '********';
$consumer_secret = '********';
$user_id = '********';
$screen_name = 'StackOverflow';
$count = 5;

$twitter_url = 'statuses/user_timeline.json';
$twitter_url .= '?user_id=' . $user_id;
$twitter_url .= '&screen_name=' . $screen_name;
$twitter_url .= '&count=' . $count;

// Create a Twitter Proxy object from our twitter_proxy.php class
$twitter_proxy = new TwitterProxy(
    $oauth_access_token,            // 'Access token' on https://apps.twitter.com
    $oauth_access_token_secret,     // 'Access token secret' on https://apps.twitter.com
    $consumer_key,                  // 'API key' on https://apps.twitter.com
    $consumer_secret,               // 'API secret' on https://apps.twitter.com
    $user_id,                       // User id (http://gettwitterid.com/)
    $screen_name,                   // Twitter handle
    $count                          // The number of tweets to pull out
);

// Invoke the get method to retrieve results via a cURL request
$tweets = $twitter_proxy->get($twitter_url);

echo $tweets;

?>

tweets.js

$(function(){

    $.ajax({
        url: 'get_tweets.php',
        type: 'GET',
        success: function(response) {

            console.log(response)

            if (typeof response.errors === 'undefined' || response.errors.length < 1) {

                var $tweets = $('<ul></ul>');
                $.each(response, function(i, obj) {
                    $tweets.append('<li>' + obj.text + '</li>');    
                });

                $('.tweets-container').html($tweets);

            } else {
                $('.tweets-container p:first').text('Response error');
            }
        },
        error: function(errors) {
            $('.tweets-container p:first').text('Request error');
        }
    });
});

Please see below for one of the objects returned

enter image description here

  • What kind of output you have currently? – Chay22 May 30 '16 at 17:17
  • @Chay22 see screenshot attached. Does this provide you with enough info? –  May 30 '16 at 17:27
  • @Chay22 i am questioning whether there is anything I can do with the data returned from twitter? can i show a video if it is youtube/vimeo etc. Irrelevant of the source of the video is there a way I can show the video based on the data provided by instagram? –  May 30 '16 at 22:00
  • I answered, is that what you're trying to achieve? – Chay22 May 31 '16 at 04:21

1 Answers1

0

I ended up searching library you used from google and found it, andyfitch/twitter-proxy.

Just surf within the object returned. First check if it contains object media then return a thumbnail. Else, show embeded video. The idea behind this is because the (old?) way you embed (youtube) video on twitter is to insert the URL on your tweet. So I set thumbnail as priority over video embed.

$.each(response, function(i, obj) {

    var media = obj.entities.media, //media entities
        urls = obj.entities.urls, //url entities
        img, //for image
        thumb; //whether show url+image or iframe

        //Every media (photo?) found should has URL (on tweet)
        if (typeof media != 'undefined') {
            img = '<img src="' + media[0].media_url + '>';
            thumb = '<a href="' + urls[0].expanded_url + '>' + img + '</a>';
        } else {
            //If no media show embeded video
            if (typeof urls != 'undefined' && urls.length > 0) {
                 //see parseVideo() function
                 thumb = parseVideo(urls[0].expanded_url);
            }
        }

    //Show the image or iframe and tweet status
    $tweets.append('<li>' + thumb + obj.text + '</li>');
});

Since we want to embed an iframe if no media found. We should detect the URL entities whether it's coming from either youtube or vimeo (as you requested), because both have different URL in order to embed a video. Example

Youtube: http://www.youtube.com/embed/Abcd1234

Vimeo: http://player.vimeo.com/video/12345678

This can be done with regex and I found a simple but great function from this answer. And modified a bit.

function parseVideo(url) {
    // - Supported YouTube URL formats:
    //   - http://www.youtube.com/watch?v=My2FRPA3Gf8
    //   - http://youtu.be/My2FRPA3Gf8
    //   - https://youtube.googleapis.com/v/My2FRPA3Gf8
    // - Supported Vimeo URL formats:
    //   - http://vimeo.com/25451551
    //   - http://player.vimeo.com/video/25451551
    // - Also supports relative URLs:
    //   - //player.vimeo.com/video/25451551

    url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);

    var src, opt;

    if (RegExp.$3.indexOf('youtu') > -1) {
        src = 'http://www.youtube.com/embed/',
        opt = 'allowfullscreen';
    } else if (RegExp.$3.indexOf('vimeo') > -1) {
        src = 'http://player.vimeo.com/video/',
        opt = 'webkitAllowFullScreen mozallowfullscreen allowFullScreen';
    }

    return '<iframe src="' + src + RegExp.$6 + '" frameborder="0" ' + opt + '></iframe>';
}

It returns an iframe with its optional parameters. Thanks to Embed Responsively.


Of course, it's far away from what you're expecting. You should tweak the HTML code to display each tweet. See this snippet

$tweets.append('<li>' + thumb + obj.text + '</li>');
Community
  • 1
  • 1
Chay22
  • 2,834
  • 2
  • 17
  • 25
  • I don't think this is working. I am getting the error `Uncaught TypeError: Cannot read property 'expanded_url' of undefined` –  May 31 '16 at 07:22
  • I made this working on Firefox developer version 48.0a2. How about `(typeof urls !== 'undefined' && urls.length > 0)` or `(typeof urls[0] != 'undefined' && urls.length > 0)` or `(typeof urls != 'undefined' || urls.length > 0)` or whatever you should run to debug it? In order to work with javascript on browser, it is good to try to handle things on browser console. Put `console.log(obj)` inside the iteration. Dig into the object and find if `entities` exists then find `urls`. Or just try `console.log(urls)` inside the if statement. I'm sure the `typeof` expression should be refined. – Chay22 May 31 '16 at 16:36