How to download file from google drive api with service account? - ruby

Hello google hackers!
I am using Drive Service app and uploaded file successfully like this:
require 'googleauth'
require 'google/apis/drive_v2'
Drive = Google::Apis::DriveV2
upload_source = "/User/my_user_name/hacking.txt"
drive = Drive::DriveService.new
# Drive::AUTH_DRIVE is equal to https://www.googleapis.com/auth/drive
drive.authorization = Google::Auth.get_application_default([Drive::AUTH_DRIVE])
file = drive.insert_file({title: 'hacking.txt'}, upload_source: upload_source)
file has a lot of properties, like this:
download_url
But when I try to open this download_url in browser it shows me blank screen. Why I can't download it?
I guess, that may be there are permission problems? But the scope is correct, and uploading is successful...

The answer is simple - we cannot download it from file object, we must send another get request, just download it like this:
drive.get_file(file.id, download_dest: '/tmp/my_file.txt')

Related

Open an image in Google Docs

Just a little background: As you might know, if you have an image in Google drive and you try to open it with Google Docs, Google tries to extract the text within your image (OCR) and show the text alongside the image in a newly created Google Docs file.
I am writing a script and within that script I would like to open an image (with some text) with Google Docs.
When I try to do it through the following code, I just an Error message with no explanation on why it fails.
var file_url = file.getUrl();
try
{
var doc = DocumentApp.openByUrl(file_url);
}catch (e) {
Logger.log("Error Occurred: " + e.toString());
}
Any help would be appreciated.
Edit 1: Here is an actual scenario. I have the following .png image and I can open it with Google Docs.
When I open with Google Docs, I get the following document:
Document generated after opening the .png image with Google Doc.
Having the url of this .png file, I would like to do all this through my script so I can have the OCR generated text.
You want to convert a PNG file to Google Document by OCR using Google Apps Script.
If my understanding is correct, how about this modification? In this modification, Drive API is used.
When you use this script, please enable Drive API at Advanced Google Services and API console. You can see about this at here.
Modified script:
var fileId = "### file ID of PNG file ###";
var file = DriveApp.getFileById(fileId);
Drive.Files.insert(
{title: file.getName(), mimeType: MimeType.GOOGLE_DOCS},
file.getBlob(),
{ocr: true}
);
Note:
When the URL of PNG file is like https://drive.google.com/file/d/#####/view?usp=sharing, ##### is the file ID.
In this modified script, the filename of created Document uses the filename of file retrieved by fileId. If you want to use other filename, please modify title: file.getName().
References:
Advanced Google Services
Drive API

Read the word document content from google drive

I am trying fetch doc content from google drive using the Google sdk. The problem is, the get() function is not working properly. It gives only file metadata not any actual content.
$googl = new Googl();
$this->client = $googl->client();
$this->client->setAccessToken(session('user.token'));
$this->drive = $googl->drive($this->client);
$file = $this->drive->files->get("fileId");
return $file;
From the documentation it looks like you can download a file using:
$file = $this->drive->files->get("fileId", array('alt' => 'media'));
$content = $file->getBody()->getContents();
I suspect that we may have a language issue here.
Read the content from a Google drive file
The google drive api is a file datastore api. This means that it stores the file itself and the information about said file. It does not give you any access to the contents of that file.
If you want to know what is in the file you will need to download the file and open it up on your machine.
or try Google documents api however i suspect that it will only be able to read a google drive document file and not a word file you may have to convert it first.
download the the file
If you check the documentation for Download Files you will find the following.
$fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
$response = $driveService->files->get($fileId, array(
'alt' => 'media'));
$content = $response->getBody()->getContents();

Download my own private albums using Flickr API

I'm trying to download my own flickr albums using the API. I'm using the flickr.rb gem here
I am creating a new object using this:
#flickr = Flickr.new({api_key: 'xxxxx', shared_secret: 'xxxxx', verify_ssl: false})
And then I'm using:
p = #flickr.photoset(photoset_id)
Where I pass the id of my photoset I want to download.
I keep getting the error:
/.rvm/gems/ruby-2.2.5/gems/flickr.rb-1.2.1/lib/flickr.rb:199:in `request': Photoset not found (RuntimeError)
What is the correct way to authenticate to Flickr and download my photos? I don't want to build any UI, just want a command line app to do this. Is there some URL I need to hit in the browser to authorize the app and grant permissions? The documentation is really sparse and doesn't give any examples.
Update: In response to #r-f-nelson
The 'user' as retrieved:
#Flickr::User:0x007fd8cea6ad98 #id="29916617#N02", #username="taraporefarhad", #client=#<Flickr:0x007fd8cf09fc68 #host="https://api.flickr.com", #api="/services/rest", #verify_ssl=false, #api_key="36705xxxxxxxxxxxxxxx", #shared_secret="xxxxxxxxxxxxxx", #auth_token=nil, #ca_file=nil
The 'flickr' client object:
#Flickr:0x007fd8cf09fc68 #host="https://api.flickr.com", #api="/services/rest", #verify_ssl=false, #api_key="36705xxxxxxxxxxxxxxx", #shared_secret="xxxxxxxxxxxxxx", #auth_token=nil, #ca_file=nil, #user=#
Flickr::User:0x007fd8cea6ad98 #id="29916617#N02", #username="taraporefarhad", #client=#<Flickr:0x007fd8cf09fc68 ...
The Photoset object:
#Flickr::Photoset:0x007fd8cf06c9d0 #id="72157638843727066", #api_key=nil, #client=#<Flickr:0x007fd8cf06c8b8 #host="https://api.flickr.com", #api="/services/rest", #verify_ssl=true, #api_key=nil, #shared_secret=nil, #auth_token=nil, #ca_file=nil
/.rvm/gems/ruby-2.2.5/gems/flickr.rb-1.2.1/lib/flickr.rb:199:in `request': Invalid API Key (Key has invalid format) (RuntimeError)
Note above that the "photoset" object has a different flickr client object id and NO shared secret and API key! Not sure how that's happening since I'm using the same client and user objects to get the photoset as well.
Assuming you are successfully connecting to Flickr's API, you can browse your own photosets like so:
user = flickr.users('you#yourflickraccount.com')
photosets = user.photosets
From there you can iterate through your photosets to find the correct one. I'm guessing whatever id you're using is not the actual photoset_id that the Flickr API uses.

Empty Shared with me Folder in Google Drive?

I want to Empty Share with me folder How can I empty It is My Code and I am using Google Drive V3 .
service.Permissions.Delete(PermissionID, fileId).Execute();
service.Files.Delete(fileId).Execute();
Both line gives a permission 403 error.
If I delete MyDrive file that time Second line he worked fine but Shared With me Folder not Deleted
The thing you need to remember is that Share with me is not a file you actually own that is why this didn't work.
service.Files.Delete(fileId).Execute();
First Get a list of all files in Share with me folder.
var request = service.Files.List();
request.Q = "(sharedWithMe = true)";
request.Fields = "*";
var results = request.Execute();
Find the file you wish to delete:
var myfile = results.Files.Where(a => a.Name.ToLower().Equals("receipt.pdf")).FirstOrDefault();
Now find the permissions on that file associated with the current authenticated user:
var per = myfile.Permissions.Where(a => a.EmailAddress.ToLower().Equals("xxxxx#gmail.com")).FirstOrDefault();
Delete the permissions from the mail file.
service.Permissions.Delete(myfile.Id, per.Id).Execute();
I tested it and it worked. You can just run the initial request though a loop and delete everything if you wish.
Note: This does not appear to work in all cases. I have a file on my Google drive that was shared with me by what appears to be a service account. I have no permissions on the file there for i cant remove my access. I am still digging.

How to upload file on another domain?

I have an external hosting server.
On that server I have 2 domains:
www.dom1.com
www.dom2.com
On www.dom1.com I have my whole web page (in Codeigniter). One of the functionalities is upload (users can upload their files.)
On www.dom2.com there is only one folder called upload_dom2. www.dom2.com is otherwise empty and not visible anywhere on the Internet. I would like to use it exclusively for upload. I imagine that this is a much safer way than letting the users upload their files on www.dom1.com where all my other files are (by the way, let me know if I'm wrong, please).
So, how do I do that? How do I upload a file - that user has uploaded in the framework of Codeignitors system (webpage) on www.dom1.com - in a folder called upload-dom2 on www.dom2.com
I know how to upload a file in a folder called uplod_dom1 that is located on www.dom1.com. This is a code that I use.
$pathd=$_SERVER['DOCUMENT_ROOT'];
$config['upload_path'] = $pathd.'/upload_dom1';
But as said, that is not what I want. I want to upload to www.dom2.com (in its uplod-dom2 folder).
May I know what is the correct way to achieve my objective?
Take a look at the Codeigniter FTP class. You can do this with any external website/server that supports FTP: http://ellislab.com/codeigniter/user-guide/libraries/ftp.html
Example code:
$this->load->library('ftp');
$config['hostname'] = 'ftp.example.com';
$config['username'] = 'your-username';
$config['password'] = 'your-password';
$config['debug'] = TRUE;
$this->ftp->connect($config);
$this->ftp->upload('/local/path/to/myfile.html', '/public_html/myfile.html', 'ascii', 0775);
$this->ftp->close();

Resources