How do I create a blank Google Spreadsheet using Drive API? - javascript

I created a web interface and I am trying to create a blank Google Spreadsheet with Drive API.
How do I create a blank Google Spreadsheet?

Try to use Drive API by setting the MIME Type to application/vnd.google-apps.spreadsheet
from apiclient import errors
from apiclient.http import MediaFileUpload
# ...
def insert_file(service, title, description, parent_id, mime_type, filename):
"""Insert new file.
Args:
service: Drive API service instance.
title: Title of the file to insert, including the extension.
description: Description of the file to insert.
parent_id: Parent folder's ID.
mime_type: MIME type of the file to insert.
filename: Filename of the file to insert.
Returns:
Inserted file metadata if successful, None otherwise.
"""
media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
body = {
'title': title,
'description': description,
'mimeType': mime_type
}
# Set the parent folder.
if parent_id:
body['parents'] = [{'id': parent_id}]
try:
file = service.files().insert(
body=body,
media_body=media_body).execute()
# Uncomment the following line to print the File ID
# print 'File ID: %s' % file['id']
return file
except errors.HttpError, error:
print 'An error occured: %s' % error
return None
Note: Apps creating shortcuts with files.insert must specify the MIME type application/vnd.google-apps.drive-sdk.

Related

Trouble with file upload using javascript swagger client and react

I have a problem with the source code generated by the Swagger codegen.
I want to upload a file with react. For this I have created a Dropzone and get a path to the file. If I use the generated client as it is in the documentation, it will not work. Unfortunately, the file is not sent. Only the file name. The debug console also does not show that binary data has been sent.
The request is not executed correctly. The file will not be uploaded. The parameter "file" is just the file name, instead of the binary data.
Swagger-codegen version
openapi-generator-cli-3.3.4.jar
Swagger declaration file content
Swagger .yaml:
/orders/upload:
post:
operationId: "orderUploadPart"
summary: "upload a textual or audio part of an order"
tags:
- "orders"
description: "This funktion uploads a textual or audio part of an order to the sense.ai.tion cloud system.
The result is the resource identifier, that must be used in the order request."
consumes:
- multipart/form-data
parameters:
- in: "formData"
name: "file"
type: "file"
required: true
description: "the file to upload"
- in: "formData"
name: "media"
type: "string"
enum:
- "text"
- "wav"
- "mp3"
required: true
description: "the media type of the the upload, can be ***text***, ***wav*** or ***mp3***"
Code:
var apiInstance = new SenseaitionApi.OrdersApi();
var file = "/path/to/file"; // File | the file to upload
var media = "media_example"; // String | the media type of the the upload, can be ***text***, ***wav*** or ***mp3***
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.orderUploadPart(file, media, callback);
It's like in: https://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/javascript/docs/PetApi.md#uploadFile
Screenshot Chrome DevTools
Command line used for generation
java -jar ${GOPATH}/bin/openapi-generator-cli.jar generate -i service_js_api.yaml -g javascript -o clients/javascript/senseaition-api-js -Dio.swagger.parser.util.RemoteUrl.trustAll=true
I found the mistake. The documentation of generated Javascript code is wrong. For uploading a file (Javascript object) must be passed, not the Path.
This line is wrong:
var file = "/path/to/file"; // File | the file to upload

Google Drive API : ENOENT - but my file is just in the same directory

ENOENT - but my file is just in the same directory ...
Hi all I try to sent a file, birds.mp3, to my Google Drive using API. The file got to be reached by a function to be sent.
Despite that the file I try to send is just in the same folder that the code concerned, my console return me :
events.js:183
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open './birds.mp3'
Here my tree :
-- folder
|-- birds.mp3
|-- quickstart.js
Here my quickstart.js
module.exports.insertDrive = function (req) {
console.log("callback reached.")
var url = req.body.url;
var folderId = 'id';
var fileMetadata = {
'name': req.body.word,
parents: "id"
};
var media = {
mimeType: 'audio/*',
body: fs.createReadStream("./birds.mp3") // PATH FUNCTION HERE
};
drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
}, function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
console.log('File Id: ', file.id);
}
})};
I can't figure out why my file can't be reached. I have try several tricks like path.resolve and all, I have try to push my birds.mp3 in several folder if any, but that have failed.
Thanks.
If you're trying to load a file from the same directory as the current module and pass that to the Google API, then use __dirname instead of ./. The ./ uses the current working directory which will depend upon how the overall program was invoked and will not point at your module directory.
So, if the intended file is in the same directory as your module, then change this:
fs.createReadStream("./birds.mp3")
to this:
fs.createReadStream(path.join(__dirname, "birds.mp3"));

Bad XMLHttpRequest when uploading to S3

I'm using Evaporate.js to upload files to S3. I've had everything working, until I decided to enable server side encryption.
According to the S3 docs, you can enable it by passing a header. So I updated my add code to look like:
var promise = _e_.add({
name: name,
file: files[i],
started: callback_methods.started,
complete: callback_methods.complete,
cancelled: callback_methods.cancelled,
progress: callback_methods.progress,
error: callback_methods.error,
warn: callback_methods.warn,
paused: callback_methods.paused,
pausing: callback_methods.pausing,
resumed: callback_methods.resumed,
nameChanged: callback_methods.nameChanged,
xAmzHeadersAtInitiate: { 'x-amz-server-side​-encryption': 'AES256'} // THIS IS THE ONLY LINE THAT CHANGED!!!
}
)
I get the error: DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'AWS4-HMAC-SHA256 Credential=XXXXXXXXXXXXXXX/XXXXXXX/us-east-1/s3/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-server-side​-encryption, Signature=XXXXXXXXXXXXXXXXXXXXX' is not a valid HTTP header field value.
Update:
Header fields can only be ASCII characters. x-amz-server-side-encryption in your code contains a hidden character. Type it instead of copy pasting it from somewhere. Go to this web page and paste the header field name after copying from your question, you will see what i mean.
From the documentation:
You can't enforce whether or not objects are encrypted with SSE-S3 when they are uploaded using pre-signed URLs.
You need to sign the header along with the URL. Just sending the headers after signing the URL won't work.
var promise = _e_.add({
name: name,
file: files[i],
started: callback_methods.started,
complete: callback_methods.complete,
cancelled: callback_methods.cancelled,
progress: callback_methods.progress,
error: callback_methods.error,
warn: callback_methods.warn,
paused: callback_methods.paused,
pausing: callback_methods.pausing,
resumed: callback_methods.resumed,
nameChanged: callback_methods.nameChanged,
signHeaders: { 'x-amz-server-side-encryption': 'AES256' }, // notice this
xAmzHeadersAtInitiate: { 'x-amz-server-side-encryption': 'AES256'} // this should be fine now as we have the header in the signed request too but try removing this if you still get an error. S3 does not require you to re-specify the headers that were already signed.
});

Uploading a file to Netsuite using Node.js

So I am testing out a script that comes with an npm module that will upload a NetSuite file to the File Cabinet.
Here is a link to the npm module called nsupload. The instructions say to upload the Restlet included in the module to Netsuite and set the function in the RESTlet in the PUT method in Netsuite. When I run the script on my end to upload a file to the Netsuite File Cabinet I get the error "TypeError: sendToNetsuite is not a function."
Here is the test code the module supplies:
var sendToNetsuite = require('nsupload')
.config({
email: 'email',
password: 'pass',
account: 'account number',
script: 'script number',
method: 'PUT'
});
sendToNetsuite('./foo.json', function(err, body) {
console.log('Success!');
console.log(body);
});
EDIT:
I changed the npm module I was using to the one called nscabinet. This stoo came with a sample code for uploading a file to Netsuite. Here's the code to that:
var nscabinet = require('nscabinet') ,
gulp = require('gulp') //or just vinyl-fs
gulp.src('foo.js')
.pipe(nscabinet({
email : 'foo#bar.baz.com' ,
password : '123456' ,
account : '123456' ,
// realm : 'sandbox.netsuite.com' ,
//role : 3 ,
rootPath : '/SuiteScripts',
script : 'myuploadfile' ,
deployment : 2
}))
I left out a few parameters but I don't believe they make a difference. At the moment the error I keep getting is "SSS_INVALID_SCRIPTLET_ID - That Suitelet is invalid, disabled, or no longer exists." I have upload the Restlet that came with it to Netsuite as well but the problem persists.
Again, I have looked up the error but I still haven't figured out what the problem is. I tried testing the code within the code I wanted to use and by itself when it didn't work. Any ideas on solving this?
Thanks!
Change your script option to the script id of the Restlet you uploaded to NetSuite.
gulp.src('foo.js')
.pipe(nscabinet({
email : 'foo#bar.baz.com' ,
password : '123456' ,
account : '123456' ,
// realm : 'sandbox.netsuite.com' ,
//role : 3 ,
rootPath : '/SuiteScripts',
script : 1234 ,
deployment : 2
}))
Output console.log(inspect(sendToNetsuite)); It is not defined or not a function. The repo is private here https://github.com/truecloud-com/nsupload -- maybe contact TrueCloud/Netsuite whatever.

ModuleParse Failed or Not Found

I am building a web app that allows users to type in phone numbers and send text messages via the Twilio API. I've built the functionality in a file, shown below. If I cd to this file and run node twilioActions.js, the text message gets sent.
var client = require('twilio')(CLIENT_ID, CLIENT_SECRET);
// ideally, I'd like to send the message using this method and call this from other JavaScript files
export const sendMessage = () => {
}
// the following code works when I run 'node twilioActions.js'
client.sendMessage({
to:'...',
from: '...',
body: 'Text message test.'
}, function(err, responseData) {
if (!err) {
console.log(responseData.from); // outputs "+14506667788"
console.log(responseData.body); // outputs "word to your mother."
}
});
However, I want to call the sendMessage method from a different React file. Here is it:
import * as twilioActions from './twilioActions';
class PhoneView extends React.Component{
// other methods are hidden obviously, the one below is called when a button is pressed to send a message.
sendMessage() {
twilioActions.sendMessage();
}
}
When I try to build the project, I get the following errors:
ERROR in ./~/twilio/package.json
Module parse failed:/Users/Felix/Desktop/ECE590/node_modules/twilio/package.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "_args": [
| [
| "twilio",
# ./~/twilio/lib/Client.js 5:17-43
ERROR in ./~/request/lib/har.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Felix/Desktop/ECE590/node_modules/request/lib
# ./~/request/lib/har.js 3:9-22
ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'net' in /Users/Felix/Desktop/ECE590/node_modules/tunnel-agent
# ./~/tunnel-agent/index.js 3:10-24
ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in /Users/Felix/Desktop/ECE590/node_modules/tunnel-agent
# ./~/tunnel-agent/index.js 4:10-24
I feel like I am making a simple mistake and perhaps am not using the correct libraries or including the proper references. Could someone point me in the right direction about how to get this to work? Thank you so much!
Twilio developer evangelist here.
The twilio npm module is not built or recommended for use in the front end. The main thing is that you would need to expose your account credentials in the front end code of your site. This is a security risk as it means a malicious attacker could get hold of your credentials and abuse your Twilio account.
I recommend creating a service on your server side that you can call to with an AJAX request in order to perform actions like this.

Categories

Resources