Archive

Archive for August, 2013

How to download “past broadcasts” from twitch.tv

08/08/2013 2 comments

Unfortunately justin api no longer support twitch.tv channels and new twitch api doesn’t show direct links for flv videos. But fortunately we can still use listing by archive id using this url:
http://api.justin.tv/api/broadcast/by_archive/yyyyyyyyy.json

So, lets adopt our previous source to get fully working code in php witch download all videos from our favorite twitch channel:

<?php
$url = "https://api.twitch.tv/kraken/channels/xxxxxxx/videos?limit=100&broadcasts=true";

$c = curl_init($url);
$options = array(
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_HTTPHEADER => array('Content-type: application/json'),
	CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
);
curl_setopt_array( $c, $options );
$json = curl_exec($c);
$json_a = json_decode($json,true);

foreach($json_a['videos'] as $v) {
	$id = $v['_id'];
	$id = preg_replace('/[^0-9.]+/', '', $id);
	if(!history_check($id)){
		$vid = "http://api.justin.tv/api/broadcast/by_archive/$id.json";
		$d = curl_init($vid);
		$options2 = array(
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_HTTPHEADER => array('Content-type: application/json')
		);
		curl_setopt_array( $d, $options2 );
		$json2 = curl_exec($d);
		$json2_a = json_decode($json2,true);
		exec('wget --progress=dot:mega -c '.$json2_a[0]['video_file_url'].' -O "downloads/'.$json2_a[0]['start_timestamp'].' - '.format_title($json2_a[0]['title']).'.flv"', $array,$exit_code);
		echo 'Exit code: '.$exit_code."\n";
		echo $array;
		echo "\n";
		history_add($id);
		echo implode('"\n"', $array);
	}
}

function format_title($title){ //format title and limit to 50 chars
	$out = preg_replace('/[^a-zA-Z \.]/','', $title);
	$out = substr($out, 0, 50); 
	return $out;
}
function history_check($date){
	$data = file_get_contents('history');

	if(strpos($data, $date) !== FALSE)
	{
		$out = TRUE;
	}
	else
	{
		$out = FALSE;
	}
return $out;
}

function history_add($date){
	file_put_contents('history', $date."\n", FILE_APPEND);
}
?>
Categories: Uncategorized