How to get the page Info.totalResults from the youtube api Search: list - youtube

Below is the code i have created so far, my goal is to use the youtube Search: list api to find streams for specific games and then publish how many streams there are for that game, I have a database for the game titles and this is my function below, my api link does work im just not able to get the Info.totalResults from it, any help would be great, Thank you for any help you can provide
function totalgamelist() {
global $wpdb;
$gamelistname = $wpdb->prefix . 'Games';
global $wpdb;
$getgames = $wpdb->get_results( 'SELECT * FROM '.$gamelistname , OBJECT );
if (empty($getgames)) {
//empty array
echo 'This is empty sorry!';
} else {
echo 'We Got Something!';
foreach ( $getgames as $getgame )
{
echo '<div class="gamename">'.$getgame->GameTitle;
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=50&q='.$getgame->GameTitle.'&key=[API KEY]");
$json_data = json_decode($JSON, true);
echo $json_data['totalResults'];
echo '</div>';
}
}
}
EDIT:
So with the help from johnh10, i was able to find out that it wasn't my ability to display the results although the echo johnh10 gave is correct :) it was also that my server was blocking access to the url i was asking to view. Below is the curl code i used to access the url, hope it helps others.
$urlgame = 'https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=1&q='.$getgame->GameTitle.'&key=[API Key]';
$ch = curl_init($urlgame);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$json_data = json_decode($data, true);
if (!empty($json_data)) {
$streamnumber = $json_data['pageInfo']['totalResults'];
echo ' Streams:'.$streamnumber;
} else {
echo ' Streams: No Streams Found';
}

echo $json_data['pageInfo']['totalResults'];

Related

Getting the price of Priority Mail Express in USPS shipping

I required to get the rate for standard post,priority mail as well as priority express mail.Using below code i am getting the price rates for priority mail and standard post but not for priority express mail.
When in service column i write the priority express mail then there was an error as given below(Priority mail express)
"The requested Mail Service is not available for the specified request attributes."
Code i am using is this:
{
$url = "http://Production.ShippingAPIs.com/ShippingAPI.dll";
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// parameters to post
curl_setopt($ch, CURLOPT_POST, 1);
$data = "API=RateV4&XML=<RateV4Request USERID=\"$userName\"><Package ID=\"1ST\"><Service>All</Service><ZipOrigination>$orig_zip</ZipOrigination><ZipDestination>$dest_zip</ZipDestination><Pounds>$weight</Pounds><Ounces>0</Ounces><Container/><Size>REGULAR</Size><Machinable>FALSE</Machinable></Package>
</RateV4Request>";
// send the POST values to USPS
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
$data = strstr($result, '<?');
//echo '<!-- '. $data. ' -->'; // Uncomment to show XML in comments
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
} else {
$level[$xml_elem['level']] = $xml_elem['tag'];
}
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
eval($php_stmt);
}
}
curl_close($ch);
//print_r($data);exit;
echo '<pre>'; print_r($params); echo'</pre>'; // Uncomment to see the full array
//echo $params['RATEV4RESPONSE']['1ST'][$servicecode]['RATE'];exit;
}
Priority Mail Express is not available for all types of shipments and it might be restricted in this case. Given that your request works for other mailclasses, there's a high likelihood that this is a shipping, not technical issue. It would help if you can share the specific parameters that you're sending.
If you want to play around with USPS shipping rates you can retrieve shipping rates for free with an easy UI or API at https://goshippo.com.

How to test file download in Behat

There is this new Export functionality developed on this application and I'm trying to test it using Behat/Mink.
The issue here is when I click on the export link, the data on the page gets exported in to a CSV and gets saved under /Downloads but I don't see any response code or anything on the page.
Is there a way I can export the CSV and navigate to the /Downloads folder to verify the file?
Assuming you are using the Selenium driver you could "click" on the link and $this->getSession()->wait(30) until the download is finished and then check the Downloads folder for the file.
That would be the simplest solution. Alternatively you can use a proxy, like BrowserMob, to watch all requests and then verify the response code. But that would be a really painful path for that alone.
The simplest way to check that the file is downloaded would be to define another step with a basic assertion.
/**
* #Then /^the file ".+" should be downloaded$/
*/
public function assertFileDownloaded($filename)
{
if (!file_exists('/download/dir/' . $filename)) {
throw new Exception();
}
}
This might be problematic in situations when you download a file with the same name and the browser saves it under a different name. As a solution you can add a #BeforeScenario hook to clear the list of the know files.
Another issue would be the download dir itself – it might be different for other users / machines. To fix that you could pass the download dir in your behat.yml as a argument to the context constructor, read the docs for that.
But the best approach would be to pass the configuration to the Selenium specifying the download dir to ensure it's always clear and you know exactly where to search. I am not certain how to do that, but from the quick googling it seems to be possible.
Checkout this blog: https://www.jverdeyen.be/php/behat-file-downloads/
The basic idea is to copy the current session and do the request with Guzzle. After that you can check the response any way you like.
class FeatureContext extends \Behat\Behat\Context\BehatContext {
/**
* #When /^I try to download "([^"]*)"$/
*/
public function iTryToDownload($url)
{
$cookies = $this->getSession()->getDriver()->getWebDriverSession()->getCookie('PHPSESSID');
$cookie = new \Guzzle\Plugin\Cookie\Cookie();
$cookie->setName($cookies[0]['name']);
$cookie->setValue($cookies[0]['value']);
$cookie->setDomain($cookies[0]['domain']);
$jar = new \Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar();
$jar->add($cookie);
$client = new \Guzzle\Http\Client($this->getSession()->getCurrentUrl());
$client->addSubscriber(new \Guzzle\Plugin\Cookie\CookiePlugin($jar));
$request = $client->get($url);
$this->response = $request->send();
}
/**
* #Then /^I should see response status code "([^"]*)"$/
*/
public function iShouldSeeResponseStatusCode($statusCode)
{
$responseStatusCode = $this->response->getStatusCode();
if (!$responseStatusCode == intval($statusCode)) {
throw new \Exception(sprintf("Did not see response status code %s, but %s.", $statusCode, $responseStatusCode));
}
}
/**
* #Then /^I should see in the header "([^"]*)":"([^"]*)"$/
*/
public function iShouldSeeInTheHeader($header, $value)
{
$headers = $this->response->getHeaders();
if ($headers->get($header) != $value) {
throw new \Exception(sprintf("Did not see %s with value %s.", $header, $value));
}
}
}
Little modified iTryToDownload() function with using all cookies:
public function iTryToDownload($link) {
$elt = $this->getSession()->getPage()->findLink($link);
if($elt) {
$value = $elt->getAttribute('href');
$driver = $this->getSession()->getDriver();
if ($driver instanceof \Behat\Mink\Driver\Selenium2Driver) {
$ds = $driver->getWebDriverSession();
$cookies = $ds->getAllCookies();
} else {
throw new \InvalidArgumentException('Not Selenium2Driver');
}
$jar = new \Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar();
for ($i = 0; $i < count($cookies); $i++) {
$cookie = new \Guzzle\Plugin\Cookie\Cookie();
$cookie->setName($cookies[$i]['name']);
$cookie->setValue($cookies[$i]['value']);
$cookie->setDomain($cookies[$i]['domain']);
$jar->add($cookie);
}
$client = new \Guzzle\Http\Client($this->getSession()->getCurrentUrl());
$client->addSubscriber(new \Guzzle\Plugin\Cookie\CookiePlugin($jar));
$request = $client->get($value);
$this->response = $request->send();
} else {
throw new \InvalidArgumentException(sprintf('Could not evaluate: "%s"', $link));
}
}
In project we have problem that we have two servers: one with web drivers and browsers and second with selenium hub. As result we decide to use curl request for fetching headers. So I wrote function which would called in step definition. Below you can find a function which use a standard php functions: curl_init()
/**
* #param $request_url
* #param $userToken
* #return bool
* #throws Exception
*/
private function makeCurlRequestForDownloadCSV($request_url, $userToken)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Content-Type: application/json',
"Authorization: Bearer {$userToken}"
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$output .= "\n" . curl_error($ch);
curl_close($ch);
if ($output === false || $info['http_code'] != 200 || $info['content_type'] != "text/csv; charset=UTF-8") {
$output = "No cURL data returned for $request_url [" . $info['http_code'] . "]";
throw new Exception($output);
} else {
return true;
}
}
How you can see I have authorization by token. If you want to understand what headers you should use you should download file manual and look request and response in browser's tab network

Is there a field for knowing if the youtube channel is verified from the Youtube API?

I am using the Youtube data API and I needed to know if there is any way of finding that the youtube channel is a Verified one.
just ran into this today, and while the channelBranding of the V3 youtube API looks promising, I couldn't get it to return if the account/channel user id was verified or not
so I threw up a pretty lame php script that uses DOM model searching to examine the html directly.
to return true if the following element is present.
<a href="//support.google.com/youtube/bin/answer.py?answer=3046484&hl=en" class="qualified-channel-title-badge" target="_blank">
As of today (9/8/2014) a verified user will return true..
<?php
function isVerified($youtubeUser)
{
$youtubeUser = trim($youtubeUser);
$url = '\''."https://www.youtube.com/user/".$youtubeUser.'\'';
$url = "https://www.youtube.com/user/".$youtubeUser ;
$Verified = false;
echo "<BR>looking at $url ";
$ch = curl_init();
$timeout = 10;
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);
$dom = new DOMDocument;
#$dom->loadHTML($html);
foreach ( $dom->getElementsByTagName('a') as $link ) {
$myVar = $link->getAttribute('class');
$search = "qualified-channel-title-badge";
$found=false;
$found = strpos($myVar, $search);
if ( $found !== false) {
$Verified = true; //echo "<BR><font color=green>TRUE</font>";
} else {
$Verified = false; //echo "<BR><font color=red>FALSE</font>";
}
}
if ( $Verified ) {
return true;
} else {
return false;
}
}
?>
Bye for now!
RE: mpgn's solution, note that there's a distinction between whether the G+ account is Verified and whether one or more of the accounts YouTube channels are Verified. It's possible for an account to have more than one channel, and each of those channels are verified independently, and for channels to be unverified even though the associated G+ account is verified.
As #Paul Blakely suggests, the current best way to do this is to check the status.longUploadStatus flag, per https://developers.google.com/youtube/v3/docs/channels
As of November, 2022, the YouTube Data API provides no method for determining whether or not a given YouTube channel is or is not verified. Instead, the current approach that yields reliable results is to scrape the channel, and parse a bit of JSON, and search the resulting structure.
We'll start by loading the server response for a given channel. Below I have a channel ID hard-coded in as the id variable:
const id = 'UCFNTTISby1c_H-rm5Ww5rZg';
const response = await needle( 'get', `https://www.youtube.com/channel/${id}` );
With our response object, we should now proceed to check that a 200 OK was received, indicating there were no issues retrieving the page data, and that it is safe to proceed:
if ( response.statusCode === 200 ) {
// proceed to search for verification status
}
Within the block following the condition is where we can start to retrieve the initial data for the YouTube page. When serving a channel page, YouTube will also serve initial data for the channel itself, presumably to speed up delivery among other reasons.
We'll look for this initial data, parse it as JSON, and sift through the results:
const json = response.body.match( /ytInitialData = (.*?);<\/script>/ )[1];
const parsed = JSON.parse( json );
With our data parsed, we'll turn our attention now to one piece of the resulting structure, the c4TabbedHeaderRenderer property. This is where badges for the page (such as a verification badge) are stored. We'll also define a verifiedLabel, to explain what it is we're seeking:
const header = parsed.header.c4TabbedHeaderRenderer;
const verifiedLabel = 'BADGE_STYLE_TYPE_VERIFIED';
Lastly we need to confirm that badges is an array (it may not be, in the event the channel has no badges to enumerate), and follow that up with a check for our verifiedLabel badge:
const verified = Array.isArray(header.badges) && header.badges.some( badge => {
return badge.metadataBadgeRenderer.style === verifiedLabel
});
At this point, verified is either true (if the channel is verified), or false. I hope this helps!
On verified channels, the class "has-badge" is present.
Work in 2018:
<?php
$key = 'has-badge';
$channel = file_get_contents('https://www.youtube.com/...');
if( stripos($channel, $key) !== FALSE )
echo "Verified";
else
echo "Not Verified";
?>
If may be possible to check infer the verified status of a youtube channel via the status.longUploadsStatus flag being either allowed or eligible, as currently this feature requires the associated youtube account to be verified.
source : https://developers.google.com/youtube/v3/docs/channels

CakePHP requestAction catch error when url not exists

I try to catch error when the requested url does not exist in my application when I use requestAction($url);
with try-catch block, requested wrongs url continue to be loaded;
Please tell me if there is an other solution to test if the url exist, or if the file exist in cakephp dir (my url can be composed of a plugin name).
my actual code:
$url = $appliUrl . $cron['Cron']['plugin'] . '/'. $cron['Cron']['controller'] . '/' . $cron['Cron']['action'];
if (!empty($cron['Cron']['params'])) {
$params = explode(',', $cron['Cron']['params']);
foreach ($params as $param)
$url .= '/' . $param;
}
try{
$output = $this->requestAction($url);
}catch (Exception $e){
$output = "error in the url : ".$url;
}
You can use a variety of methods to accomplish this. In this example, use cURL.
function url_exists($url) {
if (!$fp = curl_init($url)) return false;
return true;
}
Then you can wrap your $output in an if block checking for the url.
if (url_exists($url)) {
$output = $this->requestAction($url);
}
EDIT
Make sure you put the function in a lib or your bootstrap for access. Don't just stick it in your controller like that :)
ANOTHER EDIT
<?php
$ch = curl_init('http://yoururl/');
curl_setopt($ch, CURLOPT_NOBODY, 1);
$c = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE);

Using basic oauth to send a tweet

I was using basic auth to send tweets from a server every time a song changed. Now they have blocked basic auth and I am not sure how to incorporate it. I have a server at home that updates an html file on the webserver and then calls the following script to tweet out from that file. Any ideas on how to accomplish this simply?
<?php
//====================================================
// CONFIGURATION
//====================================================
// YOUR TWITTER USERNAME AND PASSWORD
$username = '#####';
$password = '#####';
DEFINE(htmlfile, '/homec/public_html/site.com/twitter.html');
$stationURL = "http://www.site.com";
$maxLimit = "139";
$da="";
$f=#fopen(htmlfile, "r");
if ($f!=0)
{
$da=#fread($f, 4096);
fclose($f);
}
else
{
exit;
}
$da=str_replace("\r", "\n", $da);
$da=str_replace("\n\n", "\n", $da);
$d=explode("\n", $da);
$d[0]=trim($d[0], "|"); // title
$d[1]=trim($d[1], "|"); // artist
//====================================================
if ($d[0]=="" || $d[1]=="")
{
// IF WE COULD NOT GRAB THE ARTIST AND
// SONG TITLE FROM THE SAM-GENERATED HTML FILE,
// WE'LL BAIL OUT NOW WITHOUT SUBMITTING ANY TEXT
// TO TWITTER.
exit;
}
else
{
// SUCCESS IN GETTING ARTIST AND TITLE!
// WE'LL PROCEED WITH BUILDING A TEXT STRING TO SUBMIT TO TWITTER.
$message = urlencode('' . $d[1] . ' - ' . $d[0] . ' #bandradio #nowplaying ');
$stationURL = urlencode(' ' . $stationURL);
if ((strlen($message) + strlen($stationURL)) > $maxLimit)
{
// We have to truncate the artist-title string to make room for the station URL string.
$message = substr($message, 0, (($maxLimit - 2) - strlen($stationURL)));
$message .= ".." . $stationURL;
}
else
{
// No need to truncate, it all fits.
$message = $message . $stationURL;
}
} // if ($d[0]=="" || $d[1]=="")
//====================================================
// The twitter API address
$url = 'http://twitter.com/statuses/update.json';
// Set up and execute the curl process
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "$url");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
//curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message");
//curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
$buffer = curl_exec($curl_handle);
$resultArray = curl_getinfo($curl_handle);
curl_close($curl_handle);
Download the latest version of TwitterOAuth from http://github.com/abraham/twitteroauth/downloads Unpack the download and place the twitteroauth.php and OAuth.php files in the same directory as a file with the following code. Register an application at http://dev.twitter.com/apps and from your new apps details page click on "my access token" to get your access token. Fill the four required variables into the script below and you can then run it to post new tweets.
<?php
require_once('twitteroauth.php');
$connection = new TwitterOAuth('app consumer key', 'app consumer secret', 'my access token', 'my access token secret');
$connection->post('statuses/update', array('status' => 'text to be tweeted'));

Resources