Telegram Bot API file access via Google Sheets Apps Script - javascript

thanks in advance for any help
How to transfer a local photo file to google drive using multipart/form-data?
I have copied local files to google drive, obtained the google drive file link but following code line hangs and an error comes up related to the html???
var response = UrlFetchApp.fetch(vUrlTelegram + "/sendPhoto?chat_id=" + chat_id + "&photo=" + photoUrl );
note:
have obtained html string for a sample photo from the internet, and the following telegram bot google api javascript code works
function sendPhoto( chat_id, photoUrl ) {
var response = UrlFetchApp.fetch(vUrlTelegram + "/sendPhoto?chat_id=" + chat_id + "&photo=" + photoUrl );
console.log(response.getContentText());
}
Telegram doco
Photo to send.
Pass a file_id as String to send a photo that exists on the Telegram servers (recommended),
pass an HTTP URL as a String for Telegram to get a photo from the Internet, or
upload a new photo using multipart/form-data. More info on Sending Files ยป

From your question, when the direct link of image in the internet is used for the following script, you can confirm that the script works.
function sendPhoto( chat_id, photoUrl ) {
var response = UrlFetchApp.fetch(vUrlTelegram + "/sendPhoto?chat_id=" + chat_id + "&photo=" + photoUrl );
console.log(response.getContentText());
}
From this situation, when you want to use the image file on Google Drive for above script, how about the following flow?
Flow:
Publicly share the image file on Google Drive as Viewer of Anyone with the link.
Use webContentLink of the image file as photoUrl.
In this case, when the file ID of the image file is used, webContentLink is as follows.
https://drive.google.com/uc?export=download&id={fileId}
Sample script:
For example, When the image file is publicly shared and run UrlFetchApp.fetch and sharing image file is stopped, the script is as follows.
var fileId = "###"; // Please set the file ID of the image file.
var file = DriveApp.getFileById(fileId)
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); // Image file is publicly shared.
var photoUrl = "https://drive.google.com/uc?export=download&id=" + fileId;
var response = UrlFetchApp.fetch(vUrlTelegram + "/sendPhoto?chat_id=" + chat_id + "&photo=" + photoUrl );
console.log(response.getContentText());
// Utilities.sleep(2000); // I'm not sure whether this is required for this situation.
file.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.NONE); // Sharing image file is stopped.
References:
Files
setSharing(accessType, permissionType)

Related

Downloading and Storing Images in a Server Database

So currently my website is loading an JSON File from my server, looking for the data it needs and then showing it up on the screen as well as downloading and showing an image related to that info from a public API. I was wondering how would I go about storing the API downloaded image to my own servers database so before every image fetch it would check for the image in my server and if it doesn't exist, it would go to the public API and download and store it in my servers database?
This code below is a sample, when the site is loaded it pulls a random card from the JSON and displays its info along with the image. I want to download the image from the api, store it in my servers database and then check for said image before downloading as to reduce API calls to a minimum.
function RandomCard() {
const RC = Math.floor(Math.random() * cardAPIListings.data.length);
var cardShowcase = document.getElementById("randomcardshowcase");
var randomCardImage = document.getElementById('randomImage');
switch (cardAPIListings.data[RC].type) {
case "Spell Card":
case "Trap Card":
cardShowcase.innerHTML = '\"' +cardAPIListings.data[RC].name + '\"' + '<br><br>' + '[' +
cardAPIListings.data[RC].race + ' / ' + cardAPIListings.data[RC].type + ']' + '<br>' +
'Attri: ' + cardAPIListings.data[RC].attribute + '<br><br>' + 'Effect: ' + '<br>' +
cardAPIListings.data[RC].desc;
randomCardImage.src = cardAPIListings.data[RC].card_images[0].image_url;
break;
Edit:
The PUBLIC API that I'm using says this:
[ Card Images
Users who pull our card images directly from our server instead of our google cloud repository will be immediately blacklisted.
Card images can be pulled from our Google Cloud server but please only pull an image once and then store it locally(I Assume this means Store it in your Own Server/API Database).
If we find you are pulling a very high volume of images per second then your IP will be blacklisted and blocked.]
So I need a way to store the images in my own location as they are being downloaded from the Public API so I Dont get blacklisted.
Unless I'm misunderstanding your question, only store images and other binary data to the file system.
No reason to burden database with big binary data. Only store file link (or URL) in the database.

Trying to post url segment to firebase

I am running a script on a public webpage and i want to post part of the url into firebase.
I can insert a button that retrieves the url segment as a string variable but I can't post automatically to firebase from the open page because of permissions. Is there any way to do this other than creating an external page and posting the variable manually? Here is the Script I am using. This runs fine in external pages but i want to run it from the public page.
function pushit() {
firebase.initializeApp(config);
var url = location.href;
var filename = url.substr(38, 8);
console.log("Push Successfull!!!");
var database = firebase.database();
var ref = database.ref('url/data'); var data = {url: filename }
ref.push(data);
}
The error get is:
Uncaught ReferenceError: pushit is not defined
at HTMLButtonElement.onclick (index.html)
I created a popup window instead, which sends the data to the Firebase. I realized that running this sort of code in other websites was not possible.

How to get a direct download URL from Google Picker JavaScript API?

I'm trying to get a direct download URL for a file using Google's Picker API so that I can choose a file and pass this URL to server side code to download and store a copy of the item on the server.
I'm able to authorize through the picker API and get info of a picked file including the file name and preview URL (which is confusingly referred to as simply "A URL to this item" in the JSON response docs: https://developers.google.com/picker/docs/results)
I noticed that there is a post about using the Drive API to get a direct download URL here: Get google drive file download URL
However when I do this in my picker callback function (based on the docs here: https://developers.google.com/picker/docs/)
I get an error of:
"Project [number here] is not found and cannot be used for API calls. If it is recently created, enable Drive API by visiting https://console.developers.google.com/apis/api/drive.googleapis.com/overview?project=[project number here] then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."
I have the API enabled in my developer console and the URL added to the JS allowed origins.
The documentation is very confusing and there seems to be 3 versions of the REST API to use with Drive which is based on an gapi.auth2 object whereas the picker api uses gapi.auth object.
I'm not sure if I need to authenticate again using the Google Drive API before performing the GET request. This all seems very messy and I believe there must be an easier approach for what is a simple request!
My picker callback function:
pickerCallback: function(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var fileName = doc[google.picker.Document.NAME];
var url = doc[google.picker.Document.URL];
var docId = doc[google.picker.Document.ID];
var request = null;
gapi.client.load('drive', 'v2', function() {
request = gapi.client.drive.files.get({
'fileId': docId
});
request.execute(function(resp){
console.log(resp);
});
});
//Write upload details to page
//Populate hidden field
}
Developer console screen - The first app is the picker API the second is for the Drive API:
You may want to try the simple callback implementation shown in this documentation. Notice that url was initialized before the if statement:
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'You picked: ' + url;
document.getElementById('result').innerHTML = message;
}
Also, in authorizing, set the AppId value and choose the user account with the app's current OAuth 2.0 token. Note that the AppId set and the client ID used for authorizing access to a user's files must be contained in the same app. Then, after successfully obtaining the fileId, you can then send request using files.get. By default, this responds with a Files resource in the response body which includes downloadUrl.
For additional insights, see this related SO post.

Lotus notes client link and browser link in xpages to download file stored in server directory

I have a Xpage in which there is a link to download the ics file which I have stored on server,As when the user clicks the link, the user is able to download the file name "votes.ics".
Accordingly when it is been accessed from browser, it allows me to download the file but at the same time when I want to download the same file using the link from LOTUS NOTES Client,It throws as an error Resource file not found it means the path in notes client has an issue,
To make it more clear, For example I have a database name "SMP_Intern.nsf" in the folder name "SMP" on the server and the onclick script behind the link is
var docId = getVotingDocumentUID();
if(docId != ""){
if(#ClientType() == "Notes"){
var path_private = "server_name/SMP/SMP_Intern.nsf";
var httpUrl = path_private.split("/")[0];
var databaseUrl = (httpUrl+"!!"+path_private.split("/")[1]+"/"+path_private.split("/")[2]);
var url = "/xsp/"+databaseUrl+"/.ibmmodres/domino/OpenAttachment/"+databaseUrl+"/"+docId+"/ics_file/votes.ics";
return url;
}else{
var url = "/0/"+docId+"/$File/"+"votes"+".ics?OpenElement";
return url;
}
}else return false;
For the notes client it goes to 'if' condition and gives error resource not found,but when it is browser the 'else' condition works perfectly fine.
Both the paths are same basically but could not able to find the mistake.
Any suggestion will be helpful.
You don't need a special treatment for Notes Client (XPiNC) in this case.
Your SSJS code for link value
var url = "/0/"+docId+"/$File/"+"votes"+".ics?OpenElement";
return url;
works for XPiNC too as the attachment is in the current database:
If current database resides on server then the URL points to the attachment on server.
If current database is a local replica then the URL points to the attachment in local database on client.
Have you tried #URLOpen( urlstring )formula for opening from client ?
The url must be a complete url http://DominoServer/DBPath/0/DocUNID/$file/filename
var url = "http://"+path_private +"/0/"+docId+"/$File/"+"votes"+".ics?OpenElement";
#URLOpen( url );

Implementing pdf.js in android to read from sd card

I'm trying to implement a pdf viewer for my android app which displays different pdf files which are present in the SD card.
I am thinking of using the pdf.js library.I used the code sample as posted here: https://bitbucket.org/butelo/pdfviewer/
However, the library takes the pdf url in the javascript file which is relative address to the folder to which it belongs (/assets/pdfviewer).
<script type="text/javascript">
var url = '../compressed.tracemonkey-pldi-09.pdf';
</script>
How can I redirect it to use a pdf present in a folder in the sdcard ?
Also the filenames of the pdfs are not fixed and I need to change them in the program as per requirement.
Update --------------------------------------------------------------------------------------------------------------------------
I updated the java code like this:
Uri path = Uri.parse(Environment.getExternalStorageDirectory().toString() + "/data/test.pdf");
webView.loadUrl("file:///android_asset/pdfviewer/index.html?file=" + path);
In the pdffile.js, I modified the following:
From:
<script type="text/javascript">
var url = '../compressed.tracemonkey-pldi-09.pdf';
</script>
To:
var url = getURLParameter('file');
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null}
The above javascript code extracts the 'file' parameter from the URL of the 'index.html'
Still does not work. The webview 'chromium' in logcat shows:
I/chromium(1353): [INFO:CONSOLE(106)] "Warning: Unhandled rejection:
Unexpected server response (0) while retrieving PDF "file:///storage/sdcard0/data/test.pdf".", source: file:///android_asset/pdfviewer/pdf.js (106)"
This seems to be cross server issue. So how can I modify the pdf.js code to read local files without server ?
Solved the issue. The app was missing READ_EXTERNAL_STORAGE permissions.
The code can be found at: https://github.com/pauldmps/Android-pdf.js
Its Apache V2 license, so feel free to use in your app.

Categories

Resources