Google Drive File IDs to Personal Website using Drive API & Javascript - javascript

I have a Google Drive folder filled with many audio files, and I want my website to play one at random when a user clicks a button. I have the logic setup already, and it's working if I manually enter the google drive links into my array like this:
var fileArray = ["https://docs.google.com/uc?export=open&id=XXXXXXX", "https://docs.google.com/uc?export=open&id=XXXXXXXXX"];
The problem is I have hundreds of files, and I update the Drive often so I want it to update by itself. Thus where the Google Drive API comes in. Unfortunately, I have now found myself going from 1 line of code to many lines of code and being totally lost. I have an API_KEY & CLIENT_ID. The documentation at Drive API -> Javascript Quickstart has a "handleAuthClick" function, but I don't want the user to have to sign in as they will never be making changes to the Drive. I don't even see anywhere it enters the folder ID which I don't understand. People talking about javascript origins, redirect uris, google picker api. The documentation at Drive API -> files.get has cURL & http files, and I've also seen people talking about json files storing information like service account details. Is it possible to just keep everything in my javascript script? Here is an example of some code I've tried:
<script src="https://apis.google.com/js/client:platform.js"></script>
<script type="text/javascript">
var fileArray = [];
const API_KEY = 'XXXXX';
const CLIENT_ID = 'XXXXX';
const CLIENT_SECRET = 'XXXXXX';
const REDIRECT_URI = 'https://developers.google.com/oauthplayground';
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
const { google } = require('googleapis');
const SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly';
function getFileIDs() {
var folderId = 'XXXXXX';
let response;
try {
response = await gapi.client.drive.files.list({
'fileId': folderId,
'fields': 'files(id)',
});
for (var i = 0; i < files.length; i++){
var currentID = files[i].id;
var currentDriveLink = 'https://docs.google.com/uc?export=open&id=' + currentID;
fileArray.push(currentDriveLink);
}
}
}
</script>
I just want the minimum code to get to file.id, and then I can prepend the URL structure and push it to my array. Any thoughts are helpful thank you.

Related

How to allow other user to execute script on Google Apps Script

I have script that works fine on my account but I want other user to be able to use that script over API Executable.
var serviceScript = new ScriptService(new BaseClientService.Initializer()
{
HttpClientInitializer = UserInfo.Credentials,
ApplicationName = "Read Google Scripts .NET",
});
var scriptId = "scriptId";
var Param = new { spreadsheetId = spreadsheetId };
var exec = new ExecutionRequest();
exec.Function = "createDocument";
exec.DevMode = true;
exec.Parameters = new List<object>();
exec.Parameters.Add(Param);
var script = serviceScript.Scripts.Run(exec, scriptId);
//
var result = script.Execute();
This is the error I got when other user tries to access:
GoogleApiException: The service script has thrown an exception. HttpStatusCode is Forbidden. The caller does not have permission Google.Apis.Requests.ClientServiceRequest<TResponse>.ParseResponse(HttpResponseMessage response)
I am using OAuth 2.0 and after creating Apps Script I have two Client IDs
I have deployed script as 'Anyone with Google account' but it is not accessible over API and works fine as Web Application.
Looks it's only possible if I gave Editor role on script for everybody

Script to transfer user data to (for example, a md#org.com) after deleting a user account from G Suite Admin SDK

I'm trying to develop a google script to transfer user data to (for example, a md#org.com), after deleting a user account from G Suite Admin SDK.
I've tried and am unable to find it anywhere the script to transfer user data after google mail deletion.
function onFormSubmit(e) {
deleteUsers(e);
}
function deleteUsers() {
var ss = SpreadsheetApp.openById('1Z0cNwh2BJLrq1bMQS3eU1tWLrjz2DLUne8CY3rMM7OE');
var sheet = ss.getSheetByName('Delete Users');
var data = sheet.getDataRange().getValues();
var len = data.length;
for(var i=1; i<len; i++){
var user = data[i][0];
var transferToEmail = data["Transfer to Email"][1];
Logger.log(user);
//use try catch in case a user is already removed
try{
AdminDirectory.Users.remove(user);
}
catch(err){}
}
}
Some Google APIs are integrated with Google Apps Script as advanced services, unfortunately the Data Transfer API isn't, that is why on How to execute Data Transfer API? are using UrlFetchApp to make a HTTP request to call the Data Transfer API instead of something like AdminDirectory to call the Directory API / Reports API.

How do I get Figma API to work with the Google App-script API?

I am thinking of creating a google slides to Figma exporter using Google App Script. Starting out I would first like to route the shapes created in from google Slides to figma. How would I go about setting up my file? And I don't know how to set up the Oauth api communication between Google and Figma or if it's even possible.
I believe that I can start with:
References
Figma reference
https://github.com/figma/plugin-samples/blob/master/react/src/code.ts
google app script reference
https://github.com/gsuitedevs/apps-script-samples/blob/master/slides/style/style.gs#L30
Get Figma Shape
var file=projectid.key()
var=figma rectangle= file()
await figma.loadFontAsync({ family: "Roboto", style: "Regular" })
name;
var figmaShape = {
figma.ui.onmessage = msg => {
if (msg.type === 'create-rectangles') {
const nodes = []
for (let i = 0; i < msg.count; i++) {
const rect = figma.createRectangle()
rect.x = i * 150
rect.fills = [{type: 'SOLID', color: {r: 1, g: 0.5, b: 0}}]
figma.currentPage.appendChild(rect)
nodes.push(rect)
}
figma.currentPage.selection = nodes
figma.viewport.scrollAndZoomIntoView(nodes)
}
figma.closePlugin()
}
};
Get Google Docs File Shape
var powerpointfile = driveApp.getFileById = ("### Slide file ID ###")
function powerPointShape = () {
var slide = SlidesApp.getActivePresentation().getSlides()[0];
var shape = slide.insertShape(SlidesApp.ShapeType.TEXT_BOX, 100, 200, 300,
getObjectId.element(SHAPE);
};
Create new Figma file#
file.getSlides.shape = (powerPointShape, ) => {
this.powerPointShape.getRigh()=this.figmaShape(rect.x);
this.powerPointShape.getleft()=this.figmaShape(rect.y);
}
But from there would I also want to get the file id from google app script to a Figma File?
and after looking at: https://github.com/alyssaxuu/figma-to-google-slides/blob/master/Chrome%20Extension/background.js I wonder if I would have to create a chrome extension or a google Slides plugin.
How about this answer?
Issue and workaround:
Unfortunately, it seems that the shapes of Google Slides cannot be put to the page of Figma file. Because it seems that there are no methods of API for putting the shapes. But it was found that that the pages of Figma file can be retrieved as the image using Figma API.
In this answer, I would like to propose the sample script that the pages of Figma file can be put to the Google Slides as the image using Figma API with the access token. So you can directly use Figma API with Google Apps Script.
Usage:
1. Retrieve access token
You can see the method for retrieving the access token at here. Although there is also OAuth2 for retrieving the access token, in your situation, I thought that the method for directly generating the access token on the site might be suitable. So in this answer, the generated access token on the site is used. Please retrieve the access token as follows.
Generate a personal access token
Login to your Figma account.
Head to the Account Settings from the top-left menu inside Figma.
Find the Personal Access Tokens section.
Click Create new token.
A token will be generated. This will be your only chance to copy the token, so make sure you keep a copy of this in a secure place.
The access token is like #####-########-####-####-####-############. At Google Apps Script, the authorization is done by headers: {"X-Figma-Token": accessToken}.
2. Retrieve file key
In order to retrieve the Figma file using Figma API, the file key is required. You can retrieve the file key from the URL of the file.
The URL of the file is like https://www.figma.com/file/###/sampleFilename. In this case, ### is the file key.
3. Run script
The sample script is as follows. Before you run the script, please set the variables of accessToken and fileKey.
function myFunction() {
var accessToken = "###"; // Please set your access token.
var fileKey = "###"; // Please set the file key.
var baseUrl = "https://api.figma.com/v1";
var params = {
method: "get",
headers: {"X-Figma-Token": accessToken},
muteHttpExceptions: true,
};
var fileInfo = JSON.parse(UrlFetchApp.fetch(baseUrl + "/files/" + fileKey, params));
var children = JSON.parse(UrlFetchApp.fetch(baseUrl + "/images/" + fileKey + "?format=jpg&scale=3&ids=" + fileInfo.document.children.map(function(c) {return c.id}).join(","), params));
if (!children.err) {
var s = SlidesApp.create("sampleSlide");
var slide = s.getSlides()[0];
var keys = Object.keys(children.images);
keys.forEach(function(c, i) {
slide.insertImage(children.images[c]);
if (i != keys.length - 1) slide = s.insertSlide(i + 1);
})
} else {
throw new Error(children);
}
}
When myFunction() is run, at first, the file information is retrieved with the file key fileKey. Then, all pages are retrieved from the retrieved file information, and the retrieved pages are put to each slide of new Google Slides.
I think that the action of this script is similar to the script which is shown at the bottom of your question.
Note:
This is a sample script. So please modify it for your actual situation.
References:
Figma API
Class UrlFetchApp
Class SlidesApp
If I misunderstood your question and this was not the direction you want, I apologize.

Trigger spreadsheet script after change by IFTTT

Is there a way to make a google spreadsheet script run if the sheet is edited by IFTTT instead of by a person via the sheets browser?
Background: IFTTT put a value in a specific cell. My google spreadsheet script says if the cell is not empty; insert a new row. So my script is running if my sheet is edited by me manually and I put a value in that cell. However, if IFTTT adds a new entry to the spreadsheet nothing happens. I have tried both the onEdit and onChange triggers to no avail. Any suggestions?
The actual script I am using is below:
(function InsertRow() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Diagramm');
var values = sheet.getRange('B2').getValues();
if (values[0][0] != "")
sheet.insertRowBefore(2);
})();
So I followed the tutorial on Google Driver API Push Notifications and added following code to my script:
function listFiles() {
var optionalArgs = {
maxResults: 10
};
var response = Drive.Files.list(optionalArgs);
var files = response.items;
if (files && files.length > 0) {
Logger.log('Files:');
for (i = 0; i < files.length; i++) {
var file = files[i];
Logger.log('%s (%s)', file.title, file.id);
}
} else {
Logger.log('No files found.');
}
};
But what do I need to do now? Sorry I am not a good programmer...
You have to use Drive API push notifications to pick up these changes.
This example on using Apps Script with the Drive API is helpful to get started.
Spencer Easton has also provided a tutorial on get GMail push notifications that'll give you some hints on setting this up as you have to make some changes in the dev console.

Real-time basic web analytics with Javascript

I need to develop an in-house real-time analytics solution (similar to GA or mixpanel for example) that collects:
Information from the website itself ­­(URL)
Information from the user’s browser ­­(lang, device, OS etc..)
Information from the referring source etc..
.. and sends this data to the server with a single-pixel image request. Similar to how GA and other solutions work:
Google Analytics works by the inclusion of a block of JavaScript code
on pages in your website. When users to your website view a page, this
JavaScript code references a JavaScript file which then executes the
tracking operation for Analytics. The tracking operation retrieves
data about the page request through various means and sends this
information to the Analytics server via a list of parameters attached
to a single-pixel image request.
I wonder if there's any open source project available that does this part which I could use as base to build further. There's Piwik but its too feature-packed and too heavy for my requirement.
Edited to add: I'm doing something specific with the data, otherwise I'd just use the existing solutions.
Try
var img = new Image;
img.width = img.height = "1px";
var res = window.navigator;
var data = {};
var _plugins = {};
Array.prototype.slice.call(navigator.plugins).forEach(function(v, k) {
_plugins[v.name.toLowerCase().replace(/\s/, "-")] = {
"name": v.name,
"description": v.description,
"filename": v.filename
}
});
delete res.plugins && delete res.mimeTypes;
data.url = window.location.href;
data.ref = document.referrer;
data.nav = res;
data._plugins = _plugins;
// set `img` `dataset` with `data` ,
// send `img` to server , decode `img` `dataset` at server
img.dataset.stats = JSON.stringify(data);
var img = new Image;
img.width = img.height = "1px";
var res = window.navigator;
var data = {};
var _plugins = {};
Array.prototype.slice.call(navigator.plugins).forEach(function(v, k) {
_plugins[v.name.toLowerCase().replace(/\s/, "-")] = {
"name": v.name,
"description": v.description,
"filename": v.filename
}
});
delete res.plugins && delete res.mimeTypes;
data.url = window.location.href;
data.ref = document.referrer;
data.nav = res;
data._plugins = _plugins;
img.dataset.stats = JSON.stringify(data);
document.write(
img.dataset.stats
);
There are 2 big solutions for open source analytics.
Piwik as you mentioned is a well documented and pretty mature solution. Drilling down the code, how Piwik makes things come around will give you some insights.
Open Web Analytics is the other big player on the game. A more simplified tool which will help you understand how basic tracking is made.
Depending on the data you want to track I would also suggest taking a look on this tutorial which uses sockets in order to track real time data.
Least but not last you can also check what Crazy Egg does if you want to track down user's interactivity.

Categories

Resources