<?php
class TwitchAPI {
public $url;
public $cachedir = "/home/user/somedir";
public $cachetime = 60;
public $oauth = null;
private $clientid = "";
private function getFromTwitch($u,$f) {
// Last updated 2018-04-13 for v5 Kraken to v"New" Helix transition
$s = curl_init();
$headers[] = 'Client-ID: '.$this->clientid;
if ($this->oauth != null) {
$headers[] = 'Authorization: OAuth '.$this->oauth;
// clear after each use
$this->oauth = null;
}
if (preg_match('/\/kraken\//',$u)) {
$headers[] = 'Accept: application/vnd.twitchtv.v5+json';
}
curl_setopt($s,CURLOPT_HTTPHEADER,$headers);
// clear after each use
$headers = null;
curl_setopt($s,CURLOPT_URL,$u);
curl_setopt($s,CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($s);
curl_close($s);
$fp = fopen($f,"w");
fwrite($fp,$data);
fclose($fp);
return $data;
}
function get($apiurl = "api.twitch.tv",$secure = true) {
$prefix = "http://";
if ($secure) { $prefix = "https://"; }
$inturl = $prefix.$apiurl."/".$this->url;
$md5 = md5($inturl);
$cachefile = $this->cachedir."/".$md5;
if (file_exists($cachefile)) {
$mtime = filemtime($cachefile);
$time = time();
if (($time - $mtime) > $this->cachetime) {
return $this->getFromTwitch($inturl,$cachefile);
} else {
return file_get_contents($cachefile);
}
} else {
return $this->getFromTwitch($inturl,$cachefile);
}
}
}
Comments