Uploading file to onedrive using microsoft graph api - laravel

I am trying to uploading a video file to onedrive using the microsoft graph api with the php sdk implementation in laravel.
Code details as below
// Get the access token from the cache
$tokenCache = new TokenCache();
$accessToken = $tokenCache->getAccessToken();
$file_name = 'new_video.mp4';
$media_path = storage_path('video.mp4');
// Create a Graph client
$graph = new Graph();
$graph->setAccessToken($accessToken);
//create post request
$postData = json_encode([ 'items' =>
[
"#odata.type" => "microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior" => "rename",
"name" => $file_name
]
]);
//dd(json_encode($postData));
try {
$post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);
} catch (\Illuminate\Http\Client\RequestException $e) {
dd($e);
}
Not sure what should go into the item path too, i tried using the folder name but got error and i also tried excluding the item path but still got an error.
This is the error I am getting
Client error: `POST https://graph.microsoft.com/v1.0/drive/root/createUploadSession` resulted in a `400 Bad Request` response: {
"error": {
"code": "BadRequest",
"message": "Unable to read JSON request payload. Please ensure Content-T (truncated...)
Json Encode of the request data is also as below and I cant figure out the problem...
{"items":
{
"#odata.type":"microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior":"rename",
"name":"new_video.mp4"
}
}

According to this example given on msgraph-sdk-php repository you don't need to json_econde your body data. The sdk will do it for you.
So your code should looks like this:
// Get the access token from the cache
$tokenCache = new TokenCache();
$accessToken = $tokenCache->getAccessToken();
$file_name = 'new_video.mp4';
$media_path = storage_path('video.mp4');
// Create a Graph client
$graph = new Graph();
$graph->setAccessToken($accessToken);
//create post request
$postData = [ 'items' =>
[
"#odata.type" => "microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior" => "rename",
"name" => $file_name
]
];
try {
$post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);
} catch (\Illuminate\Http\Client\RequestException $e) {
dd($e);
}

Related

How to make Exception much simpler CodeIgniter4

so, I have JWT authentication API using CI4, and one of the method is filtering which is telling if you has the token for JWT or not, if the user don't have the token it will return to an exception telling that JWT authentication is failed like this :
Postman :
Web :
is it possible to make it more simpler like this ?, just a response and without a trace exception like in the first image
Here is the
jwt_helper.php :
<?php
use App\Models\AuthModel;
use Firebase\JWT\JWT;
function getJWT($headerAuth)
{
if (is_null($headerAuth)) {
throw new Exception("JWT Authentication failed");
}
return explode(" ", $headerAuth)[1];
}
function validateJWT($encodedToken)
{
$key = getenv('JWT_SECRET_KEY');
$decodedToken = JWT::decode($encodedToken, $key, ['HS256']);
$authModel = new AuthModel();
// * xxxx.xxxx.xxxx
$authModel->getEmail($decodedToken->email);
}
function createJWT($email)
{
$requestTime = time();
$tokenTime = getenv('JWT_TOKEN_TIME');
$tokenExpireTime = $requestTime + $tokenTime;
$payload = [
'email' => $email,
'iat' => $requestTime,
'exp' => $tokenExpireTime
];
$jwt = JWT::encode($payload, getenv('JWT_SECRET_KEY'), 'HS256');
return $jwt;
}
This full stack is displayed only in DEVELOPMENT.
Edit your .ENV file accordingly.
CI_ENVIRONMENT = production
https://codeigniter.com/user_guide/general/environments.html#error-reporting

pagination is not working properly for Twilio in Laravel

I am trying to paginate the records for Twilio and after taking the reference from here
I have added the next page and previous page url and its showing successfully but when I am opening the url, its showing the error i.e.
"code": 20003,
"detail": "Your AccountSid or AuthToken was incorrect.",
"message": "Authentication Error - No credentials provided",
"more_info": "https://www.twilio.com/docs/errors/20003",
"status": 401
Here is my code :
public function listcallsapp(Request $request){
$calls = $this->twilio->calls->page([], 50);
$data = [];
$i = 0;
foreach($calls as $call){
$data[$i]['sid'] = $call->sid;
$data[$i]['from'] = $call->from;
$data[$i]['to'] = $call->to;
$data[$i]['direction'] = $call->direction;
$data[$i]['status'] = $call->status;
$data[$i]['duration'] = $call->duration;
$i++;
}
return response()->json([
'message'=>'Call Logs!',
'code'=>200,
'prev' => $calls->getPreviousPageUrl(),
'next' => $calls->getNextPageUrl(),
'data'=>$data,
'status'=>'success'
]);
}
Where I am missing, please help me out. Also, If any other way, please suggest.

Laravel - Using Stream with the new Http client

I'm migrating my old system to the new version of Laravel, and I'm having problems with one of my requests...
Basically on this request I receive any file and simply forward it to the user. Here is the old version using Guzzle:
use Symfony\Component\HttpFoundation\StreamedResponse;
public function getMedia($media)
{
try {
$response = $this->client->get('media/' . $media, [
'stream' => true
]
);
$contentType = $response->getHeader('Content-Type');
$body = $response->getBody();
$stream = new StreamedResponse(function () use ($body) {
while (!$body->eof()) {
echo $body->read(1024);
}
});
$stream->headers->set('Content-Type', $contentType);
return $stream;
} catch (ClientException $e) {
return response()->json([
'errors' => json_decode($e->getResponse()->getBody()->getContents())->errors,
'message' => 'Unfortunately we could not find the requested file'
], 404);
}
}
And the new code that I tried to write, without success:
use Symfony\Component\HttpFoundation\StreamedResponse;
public function getMedia($media)
{
$response = Http::withOptions([
'stream' => true
])->get("media/{$media}");
$contentType = $response->header('Content-Type');
$body = $response->body();
$stream = new StreamedResponse(function () use ($body) {
while (!$body->eof()) {
echo $body->read(1024);
}
});
$stream->headers->set('Content-Type', $contentType);
return $stream;
}
Does anyone have any idea how to solve this? I don't know what to do anymore...
I know, 2 years late, but i'm doing something similar, you should access to the response via the psr
instead of:
$body = $response->body(); // This try to return an string
Use this:
$body = $response->toPsrResponse()->getBody(); // the guzzle response
Then you can use your normal code
I hope someone can find this useful,

How to insert into couchDB in laravel

How to insert the records to couchDB in laravel. i have done the retrieval part but now I want to do insert, update and delete .
My retrieval code is below.
class couchdbcontroller extends Controller
{
public function getdata()
{
$content =null;
try {
$client = new Client();
$apiRequest = $client->request('GET','http://localhost:5984/user/_design/userdesign/_view/user-view?limit=20&reduce=false');
$code = $apiRequest->getBody()->getContents();
} catch (RequestException $re) {
//For handling exception
return $re->error;
}
return $code;
//return response()->json($code);
}
}
Inserting code below:
public function guzzle_insert_doc()
{
$client = new Client();
$res = $client->request('PUT', 'http://localhost:5984/login/new_doc',[
'uname' => 'admin',
'password' => 'admin123',
]);
//return $res;
}
Error: Client error: PUT http://localhost:5984/login/new_doc resulted in a 400 Bad Request response:
{"error":"bad_request","reason":"invalid UTF-8 JSON"}
From my google search, you could do something like this :
<?php
$client = new Client();
$doc = ['title'=>'This is a new doc'];
$res = $client->request('PUT', 'http://localhost:5984/db/new_doc',['json' => $doc]);
I assume you're using Guzzle (If I am wrong, tell us what your are using)
I didn't test my code since I don't have time to setup a laravel project with Guzzle. See documentation for further help.

Updates records more than one time on laravel

I am trying to update values in laravel. I have a userupdate profile api which I can update the values first time with given parameters and their values but 2nd time when I update same values it gives me user profile does not exist.
My Code is :
public function UpdateUserProfile(Request $request)
{
$id = $request->input('id');
$client_gender = $request->input('client_gender');
$client_age = $request->input('client_age');
$client_weight = $request->input('client_weight');
$client_height = $request->input('client_height');
$client_dob = $request->input('client_dob');
$profile= DB::table('clients')
->where('id',$id)
->update(['client_gender'=>$client_gender,'client_age'=>$client_age,'client_height'=>$client_height,'client_weight'=>$client_weight,'client_dob'=>$client_dob]);
if($profile)
{
$resultArray = ['status' => 'true', 'message' => 'User profile updated Successfully!'];
return Response::json( $resultArray, 200);
}
$resultArray = ['status' => 'false', 'message' => 'User profile does not exist!'];
return Response::json($resultArray, 400);}
first time when I update the value it gives me the response like this:
{
"status": "true",
"message": "User profile updated Successfully!"
}
and when I hit the update request through a postman it gives a 400 Bad request and response is :
{
"status": "false",
"message": "User profile does not exist!"
}
I'd recommend rewriting that function to look like the following; mostly because it reads better and uses the Model methods that are more commonly found in Laravel
public function UpdateUserProfile(Request $request)
{
// this code fails if there is no client with this id
$client = App\Client::findOrFail($request->id);
// attach new values for all of the attributes
$client->client_gender = $request->input('client_gender');
$client->client_age = $request->input('client_age');
$client->client_weight = $request->input('client_weight');
$client->client_height = $request->input('client_height');
$client->client_dob = $request->input('client_dob');
// save
$client->save();
return ['status' => 'true', 'message' => 'User profile updated Successfully!'];
}

Resources