How do I download images served by Cloudinary to my local directory using extendscript? - cloudinary

If this is my url for the image: https://static.www.nfl.com/image/private/h_100,f_auto,q_auto,c_fill,g_auto/league/jccqiejlzdigw2zwxx2n
I've previously downloaded images from a url that was http and not a server in the following code but can't figure out how to download an image from cloudinary.
var imageURL = "http://www.nfl.com/static/content/public/static/img/fantasy/transparent/512x512/";
var imageName = imageURL + playerID + ".png";
var localFileImage = playerID + ".png";
var fileRepository = "/01 feedRepository/IMAGE_FILES/";
var playerName = playerLastName + "_" + playerFirstName;
getJSONFile(imageName, fileRepository);
...
I've tried this, which works from the terminal but not from AE:
app.system.callSystem("curl -o ~/Desktop/OLU474619.png https://static.www.nfl.com/image/private/h_100,f_auto,q_auto,c_fill,g_auto/league/jccqiejlzdigw2zwxx2n.png");

You can simply add fl_attachment in the URL to download the image: https://static.www.nfl.com/image/private/h_100,f_auto,q_auto,c_fill,g_auto,fl_attachment/league/jccqiejlzdigw2zwxx2n
If doing programmatically then pass it as a flag("attachment") in the transformation.
For your case, the first option should do.

I realized that the app.system.callSystem() does actually work but without app.
So it would look like this:
system.callSystem("curl -o ~/Desktop/OLU474619.png https://static.www.nfl.com/image/private/h_100,f_auto,q_auto,c_fill,g_auto/league/jccqiejlzdigw2zwxx2n.png");
This allows me to download the cloudinary image to a specific directory with simplicity.

Related

How to download single sheet as PDF to my local device directly (not export to Google Drive)?

I've come across a few scripts to use with Google Sheets that will let me export a single sheet to a file on my Google Drive. However, instead of sending it there, I want it to download to my computer directly.
I'm looking to replace this...
DriveApp.createFile()
with something else that will send the file, with a customized name, as a file to download in my browser.
You want to download a specific sheet in the active Spreadsheet as a PDF file.
If my understanding is correct, how about this sample script? This sample script supposes the following points.
Script is the container-bound script of Spreadsheet.
Sheet you want to download is in the active Spreadsheet.
When the script is run, a dialog is opened. When the button is clicked, the active sheet is downloaded as a PDF file to the local PC.
In this script, the PDF file is downloaded by Javascript. So I used a dialog to execute Javascript.
Sample script:
When you use this script, please copy and paste this script to the script editor. Script is the container-bound script of Spreadsheet. When you run downloadSheetAsPDF(), a dialog is opened on the Spreadsheet. Please check it. When you click the button, the PDF file is downloaded.
function downloadSheetAsPDF() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetId = ss.getActiveSheet().getSheetId();
var url = "https://docs.google.com/a/mydomain.org/spreadsheets/d/" + ss.getId() + "/export?exportFormat=pdf&gid=" + sheetId + "&access_token=" + ScriptApp.getOAuthToken();
var str = '<input type="button" value="Download" onClick="location.href=\'' + url + '\'" >';
var html = HtmlService.createHtmlOutput(str);
SpreadsheetApp.getUi().showModalDialog(html, "sample");
}
Note:
This is a simple sample script. So please modify this for your situation.
If you want to download the specific sheet name, please modify to var sheetId = ss.getSheetByName("sheetName").getSheetId();.
References:
Class HtmlService
Class Ui
If this was not the result you want, I apologize.
Edit:
You want to use the specific filename of PDF file, when the file is downloaded.
You want to automatically download when the script is run.
If my understanding is correct, how about this sample script? The flow of this sample script is as follows. I think that there might be several answers for your situation. So please think of this as just one of several answers.
PDF file is created as a temporal file.
Create the URL for downloading.
Open a dialog box and the PDF file is automatically downloaded by running Javascript.
Remove the temporary file.
Close the dialog box.
Sample script:
function downloadSheetAsPDF2() {
var filename = "sampleFilename.pdf"; // Please set the filename here.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetId = ss.getActiveSheet().getSheetId();
// Creat PDF file as a temporary file and create URL for downloading.
var url = "https://docs.google.com/a/mydomain.org/spreadsheets/d/" + ss.getId() + "/export?exportFormat=pdf&gid=" + sheetId + "&access_token=" + ScriptApp.getOAuthToken();
var blob = UrlFetchApp.fetch(url).getBlob().setName(filename);
var file = DriveApp.createFile(blob);
var dlUrl = "https://drive.google.com/uc?export=download&id=" + file.getId();
// Open a dialog and run Javascript for downloading the file.
var str = '<script>window.location.href="' + dlUrl + '"</script>';
var html = HtmlService.createHtmlOutput(str);
SpreadsheetApp.getUi().showModalDialog(html, "sample");
file.setTrashed(true);
// This is used for closing the dialog.
Utilities.sleep(3000);
var closeHtml = HtmlService.createHtmlOutput("<script>google.script.host.close()</script>");
SpreadsheetApp.getUi().showModalDialog(closeHtml, "sample");
}
Alternatively, You can use the anchor tag to download to local drive with a custom name:
Flow:
Create custom download url for pdf export from using spreadsheet id
UrlFetchApp to fetch the pdf
Serve pdf as Data URI using anchor tag
Use anchor tag's download attribute to provide the custom name for the download
Snippet:
function downloadPdfToDesktop() {
var ss = SpreadsheetApp.getActive(),
id = ss.getId(),
sht = ss.getActiveSheet(),
shtId = sht.getSheetId(),
url =
'https://docs.google.com/spreadsheets/d/' +
id +
'/export' +
'?format=pdf&gid=' +
shtId;
var val = 'PDFNAME';//custom pdf name here
val += '.pdf';
//can't download with a different filename directly from server
//download and remove content-disposition header and serve as a dataURI
//Use anchor tag's download attribute to provide a custom filename
var res = UrlFetchApp.fetch(url, {
headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
});
SpreadsheetApp.getUi().showModelessDialog(
HtmlService.createHtmlOutput(
'<a target ="_blank" download="' +
val +
'" href = "data:application/pdf;base64,' +
Utilities.base64Encode(res.getContent()) +
'">Click here</a> to download, if download did not start automatically' +
'<script> \
var a = document.querySelector("a"); \
a.addEventListener("click",()=>{setTimeout(google.script.host.close,10)}); \
a.click(); \
</script>'
).setHeight(50),
'Downloading PDF..'
);
}

Blob Storage Images - Azure

I have some problems with images that I upload through my web api to a public container in my blob storage. The problem is that i need the image i uploaded through my api have to be browseable, i mean when put the public link in a browser you can see the image in the browser, but the actual behavior is that when i put the link the image make a download of the image and doesnt show me nothing in the browser But when i Upload the image through the azure portal i can see the image as I want.... I have my container public and i dont know what else to do.... my code to upload a image is this:
private readonly CloudBlobContainer blobContainer;
public UploadBlobController()
{
var storageConnectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
blobContainer = blobClient.GetContainerReference("messagesthredimages");
blobContainer.CreateIfNotExists();
blobContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
}
[HttpPost]
[Route("UploadImagetoBlob")]
public async Task<IHttpActionResult> UploadImagetoBlob()//string imagePath
{
try
{
var image = WebImage.GetImageFromRequest();
var imageBytes = image.GetBytes();
var blockBlob = blobContainer.GetBlockBlobReference(image.FileName);
blockBlob.Properties.ContentType = "messagesthreadimages/" + image.ImageFormat;
await blockBlob.UploadFromByteArrayAsync(imageBytes, 0, imageBytes.Length);
return Ok(blockBlob.Uri.ToString());
}
catch (Exception)
{
return BadRequest();
}
}
Examples, I hope somebody can help me with this.
What I Want => Correct
What I dont Want => Incorrect
I have faced the same issue before. Browsers download a file when they do not know the format (file type). If you monitor the files with the desktop app (no sure where this option is in the portal), you will find the file types.
These file types are set based on the blockBlob.Properties.ContentType you are setting. You need to inspect and check what exactly image.ImageFormat returns. The browser would only display the image if the this value is set to something like "image/jpeg". However since you are using "messagesthreadimages/" + image.ImageFormat, it might be setting something like "messagesthreadimages/image/jpeg".
As Neville said, you have some misunderstand when you call SetProperties method like blockBlob.Properties.ContentType.
Content-Type indicates the media type of the message content.
The image content type allows standardized image files to be included in messages. For more detail,you could refer to this link.
image/g3fax [RFC1494]
image/gif [RFC1521]
image/ief (Image Exchange Format) [RFC1314]
image/jpeg [RFC1521]
image/tiff (Tag Image File Format) [RFC2301]
I read this article and it seems that you would customize the ContentType of image.
So, you could change code as below:
blockBlob.Properties.ContentType = "image/" + image.ImageFormat;

Apps Script save as pdf doesn't include drawings and images

I want to save a Google Doc file as a pdf in the same Google Drive folder as my current file. I know I can download the file as a pdf, but then I have to upload it into the same Google Drive folder. I am trying to skip the upload step.
I have created a script to accomplish all of this, but I cannot get the images and drawings to be included in the resulting pdf.
Here is my code:
function onOpen() {
// Add a custom menu to the spreadsheet.
var ui = DocumentApp.getUi();
var menu = ui.createAddonMenu();
menu.addItem('Save As PDF','saveToPDF')
.addToUi();
}
function saveToPDF(){
var currentDocument = DocumentApp.getActiveDocument();
var parentFolder = DriveApp.getFileById(currentDocument.getId()).getParents();
var folderId = parentFolder.next().getId();
var currentFolder = DriveApp.getFolderById(folderId);
var pdf = currentDocument.getAs('application/PDF');
pdf.setName(currentDocument.getName() + ".pdf");
// Check if the file already exists and add a datecode if it does
var hasFile = DriveApp.getFilesByName(pdf.getName());
if(hasFile.hasNext()){
var d = new Date();
var dateCode = d.getYear()+ "" + ("0" + (d.getMonth() + 1)).slice(-2) + "" + ("0" + (d.getDate())).slice(-2);
pdf.setName(currentDocument.getName() + "_" + dateCode +".pdf");
}
// Create the file (puts it in the root folder)
var file = DriveApp.createFile(pdf);
// Add to source document original folder
currentFolder.addFile(file);
// Remove the new file from the root folder
DriveApp.getRootFolder().removeFile(file);
}
Is there another way to create the pdf, save to the current Google Drive folder, and not lose the images?
UPDATE
I just tested and realized that even if I export as a pdf, the images and drawings aren't included. There has to be a way to do this.
UPDATE 2
I have been testing some more and have learned a few things:
Images in the header/footer are included if they are In line, but if I use Wrap text or Break text they are not.
Images in the body can be any of the three
However, if I use the "Project Proposal" template, they include an image in the footer with Break text and it exports to pdf. I can't tell why their image is any different.
I don't want to use In line because I want the image to touch both sides of the page and In line will always leave at least 1 pixel to the left of the image.

Titanium JS: cannot use an image stored in SQLite Database in TiSocial module

My app has a bunch of images stored as blobs in the local SQLite Database. These images are taken with the device camera. I'm using Titanium Alloy, so the image was saved using the .save() method an Alloy Model.
I've started using the TiSocial module that can post an image to Twitter or Facebook. One its parameters is image and it has to be:
a local/remote path to an image you want to share
The image I want to use is set as the image property on an ImageView. The ImageView image is set like this: $.theImageView.image = args.the_image;, where args.image is the image blob, taken from the database collection.
I tried to take this image blob and set it as the image on the TiSocial module initialisation method:
Social.activityView({
text: "Hello world! Take a look at this: " + args.name,
image: args.the_image,
removeIcons:"airdrop,print,copy,contact,camera"
});
Alternatively I tried to take use the image saved on the ImageView, like this:
Social.activityView({
text: "Hello world! Take a look at this: " + args.name,
image: $.theImageView.image,
removeIcons:"airdrop,print,copy,contact,camera"
});
However neither of these worked, and no image appears in the Tweet or Facebook message dialogs. And no error appears in the console.
On the other hand, if I set the image property to an image saved in the assets folder, then it works just fine. For example:
`image: "an_image.jpg"`
I tried a solution mentioned in the comments below, which was to save the image to Ti.FileSystem, and then read the image from there. However, this still did not work.
You could try sharing remote images this way...
var largeImg = Ti.UI.createImageView({
width : Ti.UI.SIZE,
height : 'auto',
image :'http://www.google.com/doodle4google/images/splashes/featured.png'
});
var imageGoogle =largeImg.toBlob();
// share image
Social.activityView({
status : "Hello world! Take a look at this: ",
image : imageGoogle,
removeIcons:"airdrop,print,copy,contact,camera"
});
then i would suggest to add one field called img_path in your database table because you can not get path from blob so when you store any blob to alloy model then also add its path to that model so you can retrieve it later and can share.
Hope you understand.
I had some luck by saving the file to the Ti.Filesystem, and then later retrieving it and using the .getNativePath() method:
function getImage() {
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, args.alloy_id + '.jpg');
return f.read();
}
var theImage = getImage();
Social.activityView({
text: "Just tried this beer called " + args.name,
image: theImage.getNativePath(),
removeIcons:"airdrop,print,copy,contact,camera"
});

Load local HTML into WebView

Can I load a local HTML file (with images and ...) into a WebView?
Just setting the Source parameter does not do the trick.
You can load it from a file as long as the file is part of the app package, e.g.:
WebView2.Source = new Uri("ms-appx-web:///assets/text.html");
From WebView.Navigate
WebView can load content from the application’s package using
ms-appx-web://, from the network using http/https, or from a string
using NavigateToString. It cannot load content from the application’s
data storage. To access the intranet, the corresponding capability
must be turned on in the application manifest.
For a 'random' file, I suppose you could prompt user via file picker to select the file then read it into a string and use NavigateToString, but the user experience there may be a bit odd depending on what you're trying to accomplish.
I was working at this problem for a long time and I found a way to do that:
At first you should save it in InstalledLocation folder. If you haven't option to create a new .html file you can just use file.CopyAsync(htmlFolder, fname + ".html");
Look into my example:
StorageFolder htmlFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.CreateFolderAsync(#"HtmlFiles", CreationCollisionOption.GenerateUniqueName);
IStorageFile file = await htmlFolder .CreateFileAsync(fname + ".html", CreationCollisionOption.GenerateUniqueName);
and than you can easily open your .html file:
var fop = new FileOpenPicker();
fop.FileTypeFilter.Add(".html");
var file = await fop.PickSingleFileAsync();
if (file != null)
{
string myPath = file.Path.Substring(file.Path.IndexOf("HtmlFiles"));
myWebview.Navigate(new Uri("ms-appx-web:///" + myPath));
}
Remember just only from InstalledLocation you can open it with ms-appx-web:///