Changing json file creation destination from dropbox to google drive - json

i need to have this code have the create the json file inside of google drive instead of drop box
I have experimented with a few things but i am not quite knowledgeable enough to make this change, i would show less code but i do not know where the problem lies
function main(spreadsheet_id) {
var json_dict = fillDict(spreadsheet_id)
var json_obj = convertDictToJSON(json_dict)
sendJSONToDropbox(json_obj)
};
function sendJSONToDropbox(json_object) {
var timestamp = timeStamp()
var parameters = {
"path": "/json_jobs/rhino" + "-" + timestamp + ".json",
"mode": "add", // do not overwrite
"autorename": true,
"mute": false // notify Dropbox client
};
var headers = {
"Content-Type": "application/octet-stream",
'Authorization': 'Bearer ' + 'dropbox_access_token',
"Dropbox-API-Arg": JSON.stringify(parameters)
};
var options = {
"method": "POST",
"headers": headers,
"payload": json_object
};
var API_url = "https://content.dropboxapi.com/2/files/upload";
var response = JSON.parse(UrlFetchApp.fetch(API_url, options).getContentText());

Using the DriveApp class, it is not too difficult:
function sendJSONToGDrive(json_object) {
var timestamp = timeStamp();
var fileName = "rhino" + "-" + timestamp + ".json";
var fileContent = JSON.stringify(json_object);
var myFolder = DriveApp.getFolderById('YOUR_FOLDER_ID');
myFolder.createFile(fileName, fileContent, 'application/json');
}
You just have to replace YOUR_FOLDER_ID for your actual destination folder's id.
For more information on how to use the Drive API from Google Apps Script, I recommend you check out the following link: https://developers.google.com/apps-script/reference/drive

Related

How Can I use Dropbox Refresh Tokens in Google Apps Script to transfer Drive Files to Dropbox?

Based on several examples, I wrote a function in Google apps script that takes a given input file and saves it at the specified location on Dropbox. It does this using a short lived access token obtained from the Dropbox apps console...
function driveToDropbox(inputFile, targetFilePath, writeMode='add') {
//inputFile = Drive file object, targetFilePath = string, writeMode = 'overwrite' or 'add'
inputFile = DriveApp.getFilesByName('temp.html').next(); //for testing
targetFilePath = '/temp.html' //for testing
var apiUrl = 'https://content.dropboxapi.com/2/files/upload';
var dropboxAccessToken = '<SL Token>';
var parameters = {
path: targetFilePath,
mode: writeMode,
autorename: true,
mute: false,
strict_conflict: false,
};
var headers = {
'Content-Type': 'application/octet-stream',
Authorization: 'Bearer ' + dropboxAccessToken,
'Dropbox-API-Arg': JSON.stringify(parameters),
};
var options = {
method: 'POST',
headers: headers,
payload: inputFile.getBlob().getBytes(),
};
var response = JSON.parse(UrlFetchApp.fetch(apiUrl, options).getContentText());
//Logger.log(response);
Logger.log('File uploaded successfully');
}
This will only work for 4 hours, so I obtained the refresh token for the app through the standard flow, and with this cURL command via terminal I am able to generate new working SL tokens.
curl https://api.dropbox.com/oauth2/token -d grant_type=refresh_token -d refresh_token=<R Token> -u <App key>:<App secret>
My problem is converting that CURL command into Google apps Javascript and pulling the returned SL token. This was my attempt...
var apiUrl = 'https://api.dropbox.com/oauth2/token';
var refreshToken = '<R Token>';
var appKey = '<App key>';
var appSecret = '<App secret>';
var appKeySecret = '<Combined app key+secret>'
var parameters = {
refresh_token: refreshToken,
client_id: appKey,
client_secret: appSecret,
};
var headers = {
'Content-Type': 'application/json',
Authorization: 'Basic ' + appKeySecret
'Dropbox-API-Arg': JSON.stringify(parameters),
};
var options = {
method: 'POST',
headers: headers,
grant_type: "refresh_token",
muteHttpExceptions: true,
};
var response = JSON.parse(UrlFetchApp.fetch(apiUrl, options).getContentText());
Logger.log(response);
My error response is "{error_description=missing required field "grant_type", error=unsupported_grant_type}" confirming that my issue is misunderstanding the formatting, but I'm not sure how to fix it.
After fixing that, I would parse out the SL token from the response and then use that with the working file upload code above. Is there something obvious that I am missing with the formatting?
EDIT: Here is the working function based on the selected answer. This should probably be broken into two functions.
function driveToDropbox(inputFile, targetFilePath, writeMode='add') {
//inputFile = Drive file object, targetFilePath = string, writeMode = 'overwrite' or 'add'
inputFile = DriveApp.getFilesByName('temp.html').next(); //for testing
targetFilePath = '/temp.html'; //for testing
////Obtain new 4 hour SL access token with Refresh token
var refreshToken = '<R Token>';
var appKey = '<App key>';
var appSecret = '<App secret>';
var apiUrl = 'https://api.dropbox.com/oauth2/token';
var options = {
method: 'POST',
headers: { "Authorization": "Basic " + Utilities.base64Encode(`${appKey}:${appSecret}`) },
payload: {
grant_type: "refresh_token",
refresh_token: refreshToken
},
muteHttpExceptions: true,
};
var response = UrlFetchApp.fetch(apiUrl, options);
var accessToken = JSON.parse(response.getContentText()).access_token;
////Transfer file with refreshed SL access token
apiUrl = 'https://content.dropboxapi.com/2/files/upload';
var parameters = {
path: targetFilePath,
mode: writeMode,
autorename: true,
mute: false,
strict_conflict: false,
};
options = {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
Authorization: 'Bearer ' + accessToken,
'Dropbox-API-Arg': JSON.stringify(parameters),
},
payload: inputFile.getBlob().getBytes(),
};
response = JSON.parse(UrlFetchApp.fetch(apiUrl, options).getContentText());
Logger.log('File uploaded successfully');
}
I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script.
curl https://api.dropbox.com/oauth2/token -d grant_type=refresh_token -d refresh_token= -u :
In this case, how about the following modification?
Modified script:
Please set your values of refreshToken, appKey, appSecret.
var refreshToken = '<R Token>';
var appKey = '<App key>';
var appSecret = '<App secret>';
var apiUrl = 'https://api.dropbox.com/oauth2/token';
var options = {
method: 'POST',
headers: { "Authorization": "Basic " + Utilities.base64Encode(`${appKey}:${appSecret}`) },
payload: {
grant_type: "refresh_token",
refresh_token: refreshToken
},
muteHttpExceptions: true,
};
var response = UrlFetchApp.fetch(apiUrl, options);
var obj = JSON.parse(response.getContentText());
var accessToken = obj.access_token; // You can retrieve the access token.
console.log(accessToken);
When I saw your sample curl command, it seems that it is required to send grant_type and refresh_token as the form data. And, the basic authorization is used.
Note:
In this answer, it supposes that your sample curl command works. Please be careful about this.
Reference:
fetch(url, params)

update google sheet script with another script

I have a folder with approximately 140 google sheets and a main standalone google script that I call with a library script from each sheet but need to add/update all of the scripts attached to each google sheet script. Currently the only way I have found is to open each sheet script and add the library script save and move on but 140 sheets takes a long time. I know all my sheets that i need scripts adding or updating are in one folder so thinking I could use something like this to loop through all the gsheets but can't find away to edit the scripts from here...
function scriptupdate() {
var folder = DriveApp.getFolderById('FOLDER CONTAINING THE GSHEETS ID');
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log("File Name is "+file.getName());
Logger.log("File ID is "+file.getId());
}
}
I'm not sure if what I'm trying to do is possible but trying to save a lot of time if this is doable but really appreciate any help and guidance offered
Answer
You can create and update projects and its content using the projects resource methods. As these have no built-in service in Apps Script they must be called with urlFetchApp.fetch.
When writing functions, remember to put them between grave accents (`). You can use the key combination Ctrl + Shift + I to fix all the indentation and spacing in the whole script file.
Code
function scriptupdate() {
// GET FILES
var folder = DriveApp.getFolderById('FOLDER CONTAINING THE GSHEETS ID');
var files = folder.getFiles();
while (files.hasNext()) {
// GET FILE INFORMATION
var file = files.next();
var name = file.getName()
var fileId = file.getId()
// CREATE CONTAINER-BOUND SCRIPT
var url = 'https://script.googleapis.com/v1/projects'
var formData = {
'title': name,
'parentId': fileId
};
var options = {
method: 'post',
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
payload: formData,
muteHttpExceptions: true
};
var res = JSON.parse(UrlFetchApp.fetch(url, options).getContentText())
var scriptId = res["scriptId"]
// UPDATE PROJECT CONTENT
var url = 'https://script.googleapis.com/v1/projects/' + scriptId + '/content';
var formData = {
"files": [
{
"name": "appsscript",
"type": "JSON",
"source": `{
"timeZone": "America/New_York",
"dependencies": {},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8"
}`
},
{
"name": "main",
"source":
`function main() {
console.log('hello world')
}`,
"type": "SERVER_JS"
}
]
}
var options = {
method: 'put',
contentType: 'application/json',
payload: JSON.stringify(formData),
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
muteHttpExceptions: true
};
var res = UrlFetchApp.fetch(url, options).getContentText()
console.log(res)
}
}
Reference
projects
projects: create
projects: updateContent
urlFetchApp.fetch

Save Document without closing

How do I save the current document as docx without closing through saveAndClose() first? I want to create multiple docx files from the same original Google Docs document on which my Script is running.
You can export a docs to docx with URL fetch:
function myFunction() {
var doc_id = 'YOUR DOCUMENT ID';
var url = 'https://docs.google.com/feeds/download/documents/export/Export?id=' + doc_id + '&exportFormat=docx';
var options = {
headers: {
Authorization: "Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true
}
var response = UrlFetchApp.fetch(url, options);
var doc = response.getBlob();
DriveApp.createFile(doc).setName('myDocxFile1');
DriveApp.createFile(doc).setName('myDocxFile2');
}

Spotify API authorisation via Google Apps Script

I am using the following code to make requests to the Spotify API via Google Apps Script:
function search() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var artist = sheet.getRange(1,1).getValue();
artist = encodeURIComponent(artist.trim());
var result = searchSpotify(artist);
Logger.log(result);
}
function searchSpotify(artist) {
//searches spotify and returns artist ID
var response = UrlFetchApp.fetch("https://api.spotify.com/v1/search?q=" + artist + "&type=artist&limit=1",
{ method: "GET",
headers:{
"contentType": "application/json",
'Authorization': "Bearer BQBnpSUdaEweirImw23yh2DH8OGhTwh5a_VnY_fgb2BPML0KvFvYd04CaEdUhQN9N4ZUXMIVfJ1MjFe1_j0Gl0UoHDhcoC_dklluZyOkq8Bo6i2_wfxSbGzP3k5EUjUKuULAnmTwCdkdZQnl-SNU0Co"
},
});
json = response.getContentText();
var data = JSON.parse(json);
var uri = data.artists.items[0].uri.slice(15);
var getArtists = getRelatedArtists(uri);
Logger.log(getArtists);
return getArtists;
}
function getRelatedArtists(uri) {
//searches related artists with the returned ID
var response = UrlFetchApp.fetch("https://api.spotify.com/v1/artists/" + uri + "/related-artists",
{ method: "GET",
headers:{
"contentType": "application/json",
'Authorization': "Bearer BQBnpSUdaEweirImw23yh2DH8OGhTwh5a_VnY_fgb2BPML0KvFvYd04CaEdUhQN9N4ZUXMIVfJ1MjFe1_j0Gl0UoHDhcoC_dklluZyOkq8Bo6i2_wfxSbGzP3k5EUjUKuULAnmTwCdkdZQnl-SNU0Co"
},
});
json = response.getContentText();
var data = JSON.parse(json);
var listArtists = [];
for(var i = 0, len = data.artists.length; i < len; i++){
listArtists.push(data.artists[i].name);
}
return listArtists;
}
This works fine using the temporary Authorisation token from the Spotify website but this token refreshes every hour and so is obviously useless.
I am trying to use my own Authorisation token and ID which I have setup on Spotify however I'm struggling to make this work. As I understand it I may need to add an extra step at the beginning to start the authorisation process but I've tried all methods suggested but keep receiving server errors.
From the document, it seems that "Client Credentials Flow" uses the basic authorization.
In order to use this, at first, you are required to retrieve "client_id" and "client_secret".
Sample script:
var clientId = "### client id ###"; // Please set here.
var clientSecret = "### client secret ###"; // Please set here.
var url = "https://accounts.spotify.com/api/token";
var params = {
method: "post",
headers: {"Authorization" : "Basic " + Utilities.base64Encode(clientId + ":" + clientSecret)},
payload: {grant_type: "client_credentials"},
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText())
From curl sample, grant_type is required to send as form.
Result:
The document says that the response is as follows.
{
"access_token": "NgCXRKc...MzYjw",
"token_type": "bearer",
"expires_in": 3600,
}
Note:
This is a simple sample script. So please modify this for your situation.
I prepared this sample script by the sample curl in the document.
Reference:
Client Credentials Flow
Edit:
As your next issue, you want to retrieve the access token from the returned value. If my understanding is correct, how about this modification? Please modify my script as follows.
From:
Logger.log(res.getContentText())
To:
var obj = JSON.parse(res.getContentText());
Logger.log(obj.access_token)
When the value is returned from API, it returns as a string. So it is required to parse it as an object using JSON.parse().

Connecting Google spreadsheet to Atlassian JIRA

I want to display my JIRA issues in a Google spreadsheet using Google Apps script but first i need to establish a connection with JIRA, so i went through these tutorials only to find out that the opposit is possible (JIRA connects to other applications), therefore i want to ask if there's a way to connect Google Sheets to JIRA and in that case how to get the Authentication Token ?
Request token from JIRA:
Code.gs
function requestJIRA_Token() {
var baseUrl = 'Put Base URL to JIRA here';
var theUrl = baseUrl + "/plugins/servlet/oauth/request-token";
var response = UrlFetchApp.fetch(theUrl);
Logger.log('response: ' + response);
};
JIRA OAUTH
Please find sample code to connect to JIRA and get the response as an Json Load
function seachIssuesR(j_query, maxresult) {
if (!j_query) {
Browser.msgBox("Null Query :: " + j_query);
}
var url = "https://<jiraServerName>.jira.com/rest/api/2/search?jql=" + j_query + "&startAt=0&maxResults=" + maxresult;
Logger.log(url);
if (!PropertiesService.getScriptProperties().getProperty("digest")) {
var userAndPassword = Browser.inputBox("Enter your Jira On Demand User id and Password in the form User:Password. e.g. javarohit#gmail.com:mypassword#123 (Note: This will be base64 Encoded and saved as a property on the spreadsheet)", "Userid:Password", Browser.Buttons.OK_CANCEL);
var x = Utilities.base64Encode(userAndPassword);
PropertiesService.getScriptProperties().setProperty("digest", "Basic " + x);
}
var digestfull = PropertiesService.getScriptProperties().getProperty("digest");
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"method": "GET",
"headers": {
"Authorization": digestfull
},
"muteHttpExceptions": true
};
var resp = UrlFetchApp.fetch(url, headers);
if (resp.getResponseCode() != 200) {
Browser.msgBox("Error retrieving data for url" + url + ":" + resp.getContentText());
return "";
} else {
json = resp.getContentText();
}
pri_list = JSON.parse(json);
return pri_list;
}