How to upload files,create folder into repo using api - php

Hi i m using GitHub v3 and i want to add new binery file in repo .by using KnpLabs php-github-api i m exectly doing what says in
get the current commit object
retrieve the tree it points to
retrieve the content of the blob object that tree has for that particular file path
change the content somehow and post a new blob object with that new content, getting a blob SHA back
post a new tree object with that file path pointer replaced with your new blob SHA getting a tree SHA back
and soo on . but on 5 point i got an exseption
server error
form this code
$comit=$client->api('git')->commits()->show($userName,$reposit,'master');
$basetree=$client->api('git')->trees()->show($userName,'appwiz',$comit['commit'] ['tree']['sha']);
$newBlob=$client->api('git')->blobs()->create($userName,$reposit,array('content'=> "gitapi",'encoding'=>'base64'));
$client->authenticate($userName,$password,Github\Client::AUTH_HTTP_PASSWORD);
$treeData = array(
'tree'=>
array( array('path'=>'/'
,'mode'=>'040000'
,'type'=>'tree'
,'content'=>'folder')
)
);

You cannot
As part of our ongoing effort to keep GitHub focused on building software, we
are deprecating the Downloads Tab. The Downloads API is officially deprecated
and will be disabled in 90 days.
github.com/blog/1302-goodbye-uploads

I was under the impression you needed a valid sha before you could create a tree. Based on the documentation for creating a tree it seems you need to get the SHA1 of the object. So it seems you might have to have already added the tree to the index. Without that you won't be able to get the SHA of the object as git has recognized it.

Related

get filename from google docs using laravel

My site has a feature where users can upload a link to their google docs file. What I want to do is list all the uploaded links in a place. While doing that I need to show the name of the file that is associated with the link.
I can extract the file id from the link and make sure the link is of google docs. Now I need to find a way to get the filename from that. I tried going through the google developer API for google drive, but it is for uploading/doing anything only on the authorized docs. My issue here is, my users upload the files manually to their docs which I have no control over. All I get is a sharable link and somehow get the name out of it. In addition, a thumbnail will also help.
I have tried doing this, but it throws error
$url = "https://www.googleapis.com/drive/v3/files/1G6N6FyXzg7plgEtJn-Cawo5gbghrS8z9_j_cvVqcEDA";
// and
$url = "https://docs.google.com/document/d/1G6N6FyXzg7plgEtJn-Cawo5gbghrS8z9_j_cvVqcEDA/edit?usp=sharing"
$html= file_get_contents($url);
print_r($html);
A dummy link for anyone willing to help: https://docs.google.com/document/d/1G6N6FyXzg7plgEtJn-Cawo5gbghrS8z9_j_cvVqcEDA/edit?usp=sharing
Since we are getting the URL to the file, we can do a couple of things -
get the id to the file
get what type of file is that
Before I explain how to do that, it is better to know that there can be 2 possible situations. One the file is a google docs file, the other google drive file. Those both start with different URLs.
$url = explode('/', Str::after(
Str::after($request->url, 'https://docs.google.com/'), 'https://drive.google.com/'
));
I am using 2 Str::after() to remove the unnecessary part from the URL. Then I am using explode to convert the URL into an array.
Since we have excluded the useless part from the URL, we are left with document/d/1G6N6FyXzg7plgEtJn-Cawo5gbghrS8z9_j_cvVqcEDA/edit?usp=sharing in an array form.
So, if we try to do $url[2], we get the id of the file. Also, "document" is also a good thing to note about. I use those to show proper images. There can be 5 different types of them (4 for google docs and 1 for google drive). Those are - document, spreadsheets, forms, presentation for google docs, and file for google drive. I would recommend everyone store these in the database so that extra calculations are not necessary while displaying it.
Now, to answer the actual part of the question. How to get the name. I have created a new model method to handle that.
public function name()
{
$key = config('app.google_api_key');
$url = "https://www.googleapis.com/drive/v3/files/{$this->file_id}?key={$key}";
$response = Http::get($url)->json();
return $response['name'] ?? 'Private File';
}
Don't forget to add your Google API key in the config file app.php (You need to create one). You can get your API key from Google Developer Console and create a project-specific key. Just to note that this key need not be belonging to the user of the URL.
Also, a thing to note here is that $response returns error code if the file is not set to visible to the public or the file is deleted.

Azure SDK PHP SAS for container [duplicate]

I'm getting this error:
<Error>
<Code>AuthenticationFailed</Code>
<Message>
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:6c3fc9a8-cdf6-4874-a141-10282b709022 Time:2014-07-30T10:48:43.8634735Z
</Message>
<AuthenticationErrorDetail>
Signature did not match. String to sign used was rwl 2014-07-31T04:48:20Z /acoustie/$root 2014-02-14
</AuthenticationErrorDetail>
</Error>
I get it when I generate a sas (Shared Access Signature) then paste that sas at the end of the container uri into a browser. This is the full address with the generated sas:
https://acoustie.blob.core.windows.net/mark?sv=2014-02-14&sr=c&sig=E6w%2B3B8bAXK8Lhvvr62exec5blSxsA62aSWAg7rmX4g%3D&se=2014-07-30T13%3A30%3A14Z&sp=rwl
I have scoured SO and Google and have tried lots of combinations, as far as I can tell I'm doing everything correctly, I know I'm not, I just can't see it...really hoping someone can help :-\
To be clear, I am generating a sas on a container, not a specific blob and not on the root container. Access on the blob is defined as Public Blob. My end goal is to simply allow writes to the container with the sas, while 'debugging' I have added most permissions to the SharedAccessBlobPolicy.
I have tried adding a \ at the beginning and ending of the container name. No change.
This is the code I use to generate the sas:
var blobClient = storageAccount.CreateCloudBlobClient();
//Get a reference to the blob container
var container = blobClient.GetContainerReference(containerName);
// Do not set start time so the sas becomes valid immediately.
var sasConstraints = new SharedAccessBlobPolicy
{
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30),
Permissions = SharedAccessBlobPermissions.Write
| SharedAccessBlobPermissions.Read
| SharedAccessBlobPermissions.List,
};
var sasContainerToken = container.GetSharedAccessSignature(sasConstraints);
//Return the URI string for the container, including the SAS token.
var sas = string.Format("{0}{1}", container.Uri.AbsoluteUri, sasContainerToken);
Logger.Debug("SAS: {0}", sas);
return sas;
It generates a signature, it just doesn't seem to be a valid signature.
I've tried different containers, changing the Access policy, with and without start times, extending the expiry to > 12 hours from now (I'm in a UTC+10 timezone), it doesn't seem to matter what I change it results in the same "signature did not match" error.
I have even tried using an older version of 'WindowsAzure.Storage', so I have now tried 4.2 and 4.1. Even tried the uri in a different browser, really shouldn't make a difference but hey...
Any suggestions are greatly appreciated :-)
Short Answer:
Add comp=list&restype=container to your SAS URL and you should not get this error.
Long Answer:
Essentially from your SAS URL, Azure Storage Service is not able to identify if the resource you're trying to access is a blob or a container and assumes it's a blob. Since it assumes the resource type is blob, it makes use of $root blob container for SAS calculation (which you can see from your error message). Since SAS was calculated for mark blob container, you get this Signature Does Not Match error. By specifying restype=container you're telling storage service to treat the resource as container. comp=list is required as per REST API specification.
Adding to #Gaurav Mantri Answer, in order to double check the permissions, you can also create your OWN SAS token in Azure Portal
From this you can relate this comp=list&restype=container
Resource types you can provide as :
Container
Object
Service
Hope this helps to some one..
After spending lot of time on this the actual error is different then exception raised by .net compiler. if you're using meta data fields while uploading blob file into storage then check metadata character's. For example I am adding metadata fields like description, filename and etc.... In description field I have some junk characters and which i found at the run time string text viewer.
my description originally > test� file description , after changing the description "test file description" . It is working fine.
metadata values i have extracted from different sources tats why it got that junk characters . Please remove/amend values of metadata then it will work well.

Youtube API V3 - How to get filename from fileDetails

I'm brand new to APIs so please excuse what is probably a long and stupid question. Can I modify this code I got from this sample script - https://developers.google.com/youtube/v3/code_samples/php#update_a_video_by_adding_new_tags - to return the original name of the uploaded file for one of my company's videos? Note: I have already modified the linked script to remove the updating of tags (i.e. I just had it print the video id and the current tags to test that I had the Oauth2 working and I did - so, I got that far at least.)
// Call the API's videos.list method to retrieve the video resource.
$listResponse = $youtube->videos->listVideos("snippet",
array('id' => $videoId));
I was thinking that changing to "snippet" to "fileDetails" is what I need. If so, then how do then extract just the original filename from $listResponse?
Welcome to the world of Google Development. Lets look at the documentation a little for videos.list.
If you check under response you will notice that it returns an array of video resources click on that and the documentation will take you to Videos resource representation as you can see there is lots of fun stuff here. Under snippet you find title.
snippet.title string The video's title. The property value has a
maximum length of 100 characters and may contain all valid UTF-8
characters except < and >. You must set a value for this property if
you call the videos.update method and are updating the snippet part of
a video resource.
On the main videos.list documentation page you will find some examples of how to use it with PHP. Here is a hunk of the first one I think you will like.
// Display the list of matching videos.
foreach ($videosResponse['items'] as $videoResult) {
$videos .= sprintf('<li>%s </li>',
$videoResult['snippet']['title']);
}
Googles documentation is very useful always check it.

Saving XLS from Google Docs with PHP

I'm trying to parse XLS files from Google Docs with PHP. It works fine when I manually download a file and then upload it to the server, but when I use PHP to save the exact same XLS file to the server directly, instead of getting all the data in the XLS, the response is:
<b>DOM ELEMENT: </b>HTML<br /><b>ATTRIBUTE: </b>lang => en<br /><b>DOM ELEMENT: </b>HEAD<br /><b>DOM ELEMENT: </b>META<br /><b>ATTRIBUTE: </b>charset => utf-8<br /><b>DOM ELEMENT: </b>META<br /><b>ATTRIBUTE: </b>content => width=300, initial-scale=1<br /><b>ATTRIBUTE: </b>name => viewport<br /><b>DOM ELEMENT: </b>META<br /><b>ATTRIBUTE: </b>name => description<br /><b>ATTRIBUTE: </b>content => Create a new spreadsheet and edit with others at the same time -- from your computer, phone or tablet. Get stuff done with or without an internet connection. Use Sheets to edit Excel files. Free from Google.<br /><b>DOM ELEMENT: </b>TITLE<br />
Here's an example of how I use PHP to save the XLS to the server:
$fileName = 'xls/newday2014.xls';
$xlsURL = 'https://docs.google.com/spreadsheets/d/1KKMiBOlvpKaAJ_MsNfaWGmR6ixL53AjAaLf0R18X3e4/edit#gid=161299136';
file_put_contents($fileName, file_get_contents($xlsURL));
You're missing some fundamental things here with your three liner code:
file_get_contents is not a browser. Any URI (URL) it takes can not have the fragment (in your case #gid=161299136) because this is never send to the server.
The last point also highlights: If you used that exact URI to download with your browser, there is most likely something running in your browser for the download before the correct download URI is created. So you're using the wrong URI to download.
file_get_contents does not log you into google accounts just by magic.
Just making a filename ending with .xls does not change the file-format from HTML magically into an Excel Spreadsheet.
As these are already four fundamental problems with your three lines of code, it should be obvious that the code you're using is unfitable to high degree for what you try to do. I suggest you throw it away and start from scratch doing some research first, e.g. contact the vendor of that webservice for your support options as a PHP developer. Most likely they offer an API for what you're trying to do.
Quickstart: Run a Drive App in PHP (via: How do I read a Google Drive Spreadsheet in PHP?)
Most likely, a cookie is set to your browser, when you log in into Google Docs - this cookie is not present on the file_get_contents($xlsURL) call, so you get different content. The web debugger of your choice will confirm that, so does pasting your URL into a not-logged-in browser.
The cURL extension can hand cookies to the server, but please understand, that this cookie is dynamic - so getting it out of your browser and into cURL is by far not enough. Most likely you will have to walk the complete way from login to the document, including the need to update, whenever Google choses to update.

Updating documents with the help of cas in couchbase 2.0 server using PHP API

I am trying to update a document in Couchbase 2.0 server using PHP API (php-ext-couchbase).
http://www.couchbase.com/docs/couchbase-sdk-php-1.1/api-reference-summary.html
The document is similar to facebook POSTS with comments and likes associated with it.
To be more specific.
-Load the doc.
-Modify it
-Store the modified doc if it has not been accessed by any other person.
Basic operations that would be required to accomplish this will be
# Get a document by key
doc = get(key)
# Modify a document when no one has modified it since my last read
casVersion = doc.getCas()
cas(key, casVersion, changedDoc)
I just want to know how i can accomplish this in PHP.
especially how to get the casVersion or the revision_id of the document and then further carry out the update process so that changes made by simultaneous updates on same document are not lost.
No worries I found it,
The code is
$bucket='yourbucketname';
$cb=new Couchbase("127.0.0.1:8091","root","password",$bucket);
$old_doc=null;
$cb->getDelayed($obj_id, true,
function($cb, $data) use (&$old_doc) { $old_doc = $data; });
$casKey=$old_doc['cas'];
Use getDelayed method, and callback function to get the array having (key,value,caskey)
I hope the couchbase documentation would be more clear in future with usages examples.

Categories