Currently my project is built in cakephp 2. I am moving stuffs to node.js from cakephp. I have a piece of code in core.php file. My core.php file includes these piece of code:
$bucket = env('PRJECTNAME_S3_BUCKET');
$imgPath = env('BASE_PATH_IMG');
Configure::write('Files.S3Bucket', $bucket);
if (!empty($imgPath)) {
Configure::write('Files.url', $imgPath);
} else if (empty($bucket)) {
if (!empty($httpHost)) {
$s = null;
if (env('HTTPS')) {
$s = 's';
}
$httpHost = 'http' . $s . '://' . $httpHost;
}
Configure::write('Files.url', $httpHost);
} else {
Configure::write('Files.url', 'https://s3.eu-central-2.amazonaws.com/' . $bucket);
}
$filespath = Configure::read('Files.url');
if (substr($filespath, 0, strlen('http://localhost')) == 'http://localhost') {
Configure::write('Files.safeurl', '');
} else {
Configure::write('Files.safeurl', $filespath);
}
Whenever I need to use the path for image I used to invoke it Configure::read('Files.url') in this way.
As a said I am moving our code to node.js from cakephp. I need to write these piece of code in node.js.
Can anyone help me out to converting this cakephp code to node.js?
I'm trying to develop an app that can send a user image input in base64 from their device camera and let my api handle, resize and save the image in jpg format, I'm using react-native image-picker as the camera handler. Here's my code so far
// in imageHandlerController.php
public function resizeImage($image) {
$resizeImage = Image::make($images)->resize(512, 512, function($constraint) {
$constraint->aspectRatio();
})->orientate();
return $resizeImage->response();
}
public function imageHandler(Request $request){
DB::beginTransaction();
try {
$constants = Config::get('constants');
$path = $constants['UPLOAD_PATH'].'/images';
$random_name = str_random(20);
$selfie = $request->selfieImage;
$selfie = str_replace('data:image/png;base64,', '', $selfie);
$selfie = str_replace(' ', '+', $selfie);
$selfie_name = 'selfie-'.$random_name.'.png';
File::put($path.'/partners/'.$selfie_name, $this->resizeImage($selfie));
}
Here's the post request on index.js
launchCameraSelfie = () => {
ImagePicker.showImagePicker(response => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
let source = response;
this.setState({
selfieImage: source.data
});
}
});
};
It show Unable to init from binary data as an error
How can i do this? any help will be appreciated...
It looks like you are using the Intervention Image package. The documentation shows that it is indeed possible to convert a base64 string to an Image.
What is unclear to me is why you remove the initial string data:image/png;base64, from the encoded image. I can imagine this part to be necessary for Intervention to work.
I shortened and rewrote your code a bit. This works for me:
use Intervention\Image\ImageManagerStatic as Image;
$selfie = $request->selfieImage;
$img = Image::make($selfie);
$img->resize(512, 512, function($constraint) {
$constraint->aspectRatio();
})->orientate();
$img->save(storage_path('images') . '/test.png');
For easy testing, the following base64 image can be used (it represents a single black pixel):
$selfie = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';
If you want to do some in-depth debugging, have a look at Intervention's AbstractDecoder class and its init() function. It is the place where the image type is identified, and for some reason your image is identified as binary.
I am using this, for login with Facebook, but i am not getting user response here is the link
http://demos.idiotminds.com/link.php?link=https://www.box.com/s/108pspt0o0oj0fpr6ghf
I have tried this solution also for codeigniter
protected function getCode() {
$server_info = array_merge($_GET, $_POST, $_COOKIE);
if (isset($server_info['code'])) {
if ($this->state !== null &&
isset($server_info['state']) &&
$this->state === $server_info['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $server_info['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
for log in with Facebook but i am not getting value from this $user = $facebook->getUser(); it returns 0 value even if i have logged into Facebook.
I have used so many codes for this but did not success, kindly help me out.
I am very frustrated
Download PHP SDK for Facebook
Now create the a folder in application\libarires "facebook"
Put the "SRC" folder of PHP SDK
Now create a file with FacebookApp.php in that folder and put this code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once( APPPATH . 'libraries/facebook/src/facebook.php' );
class FacebookApp extends Facebook {
var $ci;
var $facebook;
var $scope;
public function __construct() {
$this->ci =& get_instance();
$this->facebook = new Facebook(array('appId' => $this->ci->config- >item('app_id'),'secret' => $this->ci->config->item('app_secret'), 'cookie' => true));
$this->scope = 'public_profile';
}
public function login_url() {
$params = array('scope' => $this->scope);
return $this->facebook->getLoginUrl($params);
}
public function logout_url() {
return $this->facebook->getLogoutUrl(array('next' => base_url() .'logout'));
}
public function getFbObj(){
return $this->facebook;
}
public function get_user() {
$data = array();
$data['fb_user'] = $this->facebook->getUser();
if ($data['fb_user']) {
try {
$data['fb_user_profile'] = $this->facebook->api('/me');
return $data;
} catch (FacebookApiException $e) {
$this->facebook->destroySession();
$fb_login_url = $this->facebook->getLoginUrl(array('scope' => $this->scope));
redirect($fb_login_url, 'refresh');
}
}
}
Now in controller load this library
$this->load->library('facebook/FacebookApp)
in Method
$obj_fb = new FacebookApp();
$fb_user_data = $obj_fb->get_user();
$data['fb_login_url'] = $obj_fb->login_url();
put the fb_login_url in href of login button and now the login will done.
Hope it help you.
Rahul, I had a similar issue. You can find a pretty good solution here.
If you still cannot figure the solution, why don't you look into the JavaScript SDK. It is pretty straight forward and then use AJAX to act on the response that you get from Facebook.
I am a rookie PHP and MongoDB developer.
I have created a PHP web project with an HTML page that contains an 'Add' button. The name of the page is awards.html. The awards.html file contains its counterpart JavaScript file, awards.js. A code is executed in this js file when the Add button is clicked. This code sends an AJAX call to a PHP class elsewhere in the project named, example.php which contains code to execute a function called, connect() that is in an Awards.php file.
The source-code of my files is given as follows:
Awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onrequest();">Add</button>
</div>
</div>
awards.js
function onrequest() {
$("#divAddAward").load('example.php');
alert('Test');
$.post(
'example.php'
).success(function(resp) {
json = $.parseJSON(resp);
alert(json);
});
}
example.php
<?php
include 'Awards.php';
$class = new Awards();
$method = $class->connect();
echo json_encode($method);
Awards.php
<?php
require_once 'mongodb-library/libraries/Mongo_db.php';
include 'mongodb-library/libraries/Mongo_db.php';
class Awards extends Mongo_db
{
//put your code here
public function __construct()
{
parent::__construct();
}
public function connect()
{
$this->load();
//The following code is used for confirmation
$array = array(
$this->message => '1'
);
return $array;
}
public function create()
{
//Code to read
}
public function read()
{
//Code to read
}
public function update()
{
//Code to update
}
public function delete()
{
//Code to delete
}
}
The purpose of my project is to perform CRUD operations on my MongoDB database called, test. I am using the Codeigniter-MongoDB-Library to connect to this database. I have edited the mongodb.php library file accordingly to connect to my database. The config settings for this file are given as follows:
mongodb.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['default']['mongo_hostbase'] = 'localhost:27017';
$config['default']['mongo_database'] = 'test';
$config['default']['mongo_username'] = '';
$config['default']['mongo_password'] = '';
$config['default']['mongo_persist'] = TRUE;
$config['default']['mongo_persist_key'] = 'ci_persist';
$config['default']['mongo_replica_set'] = FALSE;
$config['default']['mongo_query_safety'] = 'safe';
$config['default']['mongo_suppress_connect_error'] = TRUE;
$config['default']['mongo_host_db_flag'] = FALSE;
The problem here is that the connect function is not getting executed; in other words, I am not able to connect to my database successfully. How do I know this? Because on the awards.html page I am getting an output which reads, No direct script access allowed, which is coming from the mongo_db.php file (mind you not the mongodb.php file I have mentioned above).
Can anyone please tell me where exactly am I going wrong? Replies at the earliest will be highly appreciated. Thank you in advance.
The question is very simple. How to get number of video views with YouTube API?
The task is simple but I would like to use that query on large number of videos very often. Is there any way to call their Youtube API and get it? (something like facebook http://api.facebook.com/restserver.php?method=links.getStats&urls=developers.facebook.com)
I think, the easiest way, is to get video info in JSON format. If you want to use JavaScript, try jQuery.getJSON()... But I prefer PHP:
<?php
$video_ID = 'your-video-ID';
$JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$video_ID}?v=2&alt=json");
$JSON_Data = json_decode($JSON);
$views = $JSON_Data->{'entry'}->{'yt$statistics'}->{'viewCount'};
echo $views;
?>
Ref: Youtube API - Retrieving information about a single video
You can use the new YouTube Data API v3
if you retrieve the video, the statistics part contains the viewCount:
from the doc:
https://developers.google.com/youtube/v3/docs/videos#resource
statistics.viewCount / The number of times the video has been viewed.
You can retrieve this info in the client side, or in the server side using some of the client libraries:
https://developers.google.com/youtube/v3/libraries
And you can test the API call from the doc:
https://developers.google.com/youtube/v3/docs/videos/list
Sample:
Request:
GET https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Q5mHPo2yDG8&key={YOUR_API_KEY}
Authorization: Bearer ya29.AHES6ZSCT9BmIXJmjHlRlKMmVCU22UQzBPRuxzD7Zg_09hsG
X-JavaScript-User-Agent: Google APIs Explorer
Response:
200 OK
- Show headers -
{
"kind": "youtube#videoListResponse",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/dZ8K81pnD1mOCFyHQkjZNynHpYo\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"id": "Q5mHPo2yDG8",
"kind": "youtube#video",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/4NA7C24hM5mprqQ3sBwI5Lo9vZE\"",
"statistics": {
"viewCount": "36575966",
"likeCount": "127569",
"dislikeCount": "5715",
"favoriteCount": "0",
"commentCount": "20317"
}
}
]
}
Version 2 of the API has been deprecated since March 2014, which some of these other answers are using.
Here is a very simple code snippet to get the views count from a video, using JQuery in the YouTube API v3.
You will need to create an API key via Google Developer Console first.
<script>
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Qq7mpb-hCBY&key={{YOUR-KEY}}', function(data) {
alert("viewCount: " + data.items[0].statistics.viewCount);
});
</script>
Here is a small code snippet to get Youtube video views from URL using Javascript
Demo of below code
function videoViews() {
var rex = /[a-zA-Z0-9\-\_]{11}/,
videoUrl = $('input').val() === '' ? alert('Enter a valid Url'):$('input').val(),
videoId = videoUrl.match(rex),
jsonUrl = 'http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=json',
embedUrl = '//www.youtube.com/embed/' + videoId,
embedCode = '<iframe width="350" height="197" src="' + embedUrl + '" frameborder="0" allowfullscreen></iframe>'
//Get Views from JSON
$.getJSON(jsonUrl, function (videoData) {
var videoJson = JSON.stringify(videoData),
vidJson = JSON.parse(videoJson),
views = vidJson.entry.yt$statistics.viewCount;
$('.views').text(views);
});
//Embed Video
$('.videoembed').html(embedCode);}
Why using any api key to retrieve a portion of public html!
Simplest unix command line demonstrative example, using curl, grep and cut.
curl https://www.youtube.com/watch?v=r-y7jzGxKNo | grep watch7-views-info | cut -d">" -f8 | cut -d"<" -f1
Yes, it get the full html page, this loss has no meaning against the countless advantages.
You can use this too:
<?php
$youtube_view_count = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json'))->entry->{'yt$statistics'}->viewCount;
echo $youtube_view_count;
?>
Using youtube-dl and jq:
views() {
id=$1
youtube-dl -j https://www.youtube.com/watch?v=$id |
jq -r '.["view_count"]'
}
views fOX1EyHkQwc
Use the Google PHP API Client: https://github.com/google/google-api-php-client
Here's a little mini class just to get YouTube statistics for a single video id. It can obviously be extended a ton using the remainder of the api: https://api.kdyby.org/class-Google_Service_YouTube_Video.html
class YouTubeVideo
{
// video id
public $id;
// generate at https://console.developers.google.com/apis
private $apiKey = 'REPLACE_ME';
// google youtube service
private $youtube;
public function __construct($id)
{
$client = new Google_Client();
$client->setDeveloperKey($this->apiKey);
$this->youtube = new Google_Service_YouTube($client);
$this->id = $id;
}
/*
* #return Google_Service_YouTube_VideoStatistics
* Google_Service_YouTube_VideoStatistics Object ( [commentCount] => 0 [dislikeCount] => 0 [favoriteCount] => 0 [likeCount] => 0 [viewCount] => 5 )
*/
public function getStatistics()
{
try{
// Call the API's videos.list method to retrieve the video resource.
$response = $this->youtube->videos->listVideos("statistics",
array('id' => $this->id));
$googleService = current($response->items);
if($googleService instanceof Google_Service_YouTube_Video) {
return $googleService->getStatistics();
}
} catch (Google_Service_Exception $e) {
return sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
return sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
}
}
YouTube Data API v3 URL Sample
Source Link
https://www.googleapis.com/youtube/v3/videos?key=[YOUR_API_KEY_HERE]&fields=items(snippet(title,tags,channelTitle,publishedAt),statistics(viewCount))&part=snippet,statistics&id=[VIDEOID]
look at yt:statistics tag.
It provides viewCount, videoWatchCount, favoriteCount etc.
Here an example that I used in my TubeCount app.
I also use the fields parameter to filter the JSON result, so only the fields that I need are returned.
var fields = "fields=openSearch:totalResults,entry(title,media:group(yt:videoid),media:group(yt:duration),media:group(media:description),media:group(media:thumbnail[#yt:name='default'](#url)),yt:statistics,yt:rating,published,gd:comments(gd:feedLink(#countHint)))";
var channel = "wiibart";
$.ajax({
url: "http://gdata.youtube.com/feeds/api/users/"+channel+"/uploads?"+fields+"&v=2&alt=json",
success: function(data){
var len = data.feed.entry.length;
for(var k =0; k<len; k++){
var yt = data.feed.entry[k];
v.count = Number(yt.yt$statistics != undefined && yt.yt$statistics.viewCount != undefined ? yt.yt$statistics.viewCount : 0);
}
}
});
Here is a simple function in PHP that returns the number of views a YouTube video has. You will need the YouTube Data API Key (v3) in order for this to work. If you don't have the key, get one for free at: YouTube Data API
//Define a constant so that the API KEY can be used globally across the application
define("YOUTUBE_DATA_API_KEY", 'YOUR_YOUTUBE_DATA_API_KEY');
function youtube_video_statistics($video_id) {
$json = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" . $video_id . "&key=". YOUTUBE_DATA_API_KEY );
$jsonData = json_decode($json);
$views = $jsonData->items[0]->statistics->viewCount;
return $views;
}
//Replace YOUTUBE_VIDEO_ID with your actual YouTube video Id
echo youtube_video_statistics('YOUTUBE_VIDEO_ID');
I am using this solution in my application and it is working as of today. So get the API Key and YouTube video ID and replace them in the above code (Second Line and Last Line) and you should be good to go.
PHP JSON
$jsonURL = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=$Videoid&key={YOUR-API-KEY}&part=statistics");
$json = json_decode($jsonURL);
First go through this one by uncommenting
//var_dump(json);
and get views count as:
$vcounts = $json->{'items'}[0]->{'statistics'}->{'viewCount'};
You can use JQuery, don't forget to replace Your-Api-Key string from the code below, follow the link to find your own Api key google developers console
<script>
$.getJSON('https://www.googleapis.com/youtube/v3/videospart=statistics&id=Qq7mpb-hCBY&key=Your-Api-Key', function(data) {
console.log("viewCount: ", data.items[ 0 ].statistics.viewCount);
});
</script>
This probably is not what you want but you could scrap the page for the information using the following:
document.getElementsByClassName('watch-view-count')[0].innerHTML