Download a file with Tidesdk - tidesdk

How can I download a file and store it locally? I've searched the doc and google and couldn't find an example of it.
I tried this:
this.copyRemote = function(path,path2){
reader = Ti.Network.createHTTPClient();
writer = Ti.Filesystem.getFile(path2);
reader.open('GET',path);
reader.receive(writer);
}
But Tidesdk crashes while trying to download the file, the last messages on console are:
[12:42:39:647] [Ti.Network.HTTPClient] [Debug] Changing readyState from 0 to 1 for url:https://buttonpublish.com/api/images/7/image257189x142.jpg
[12:42:39:671] [Ti.Proxy] [Debug] Looking up proxy information for: https://buttonpublish.com/api/images/7/image257189x142.jpg
[12:

Seems like there has been success on the TideSDK Google Group using the code below:
var httpClient = Ti.Network.createHTTPClient();
httpClient.open('GET', path);
httpClient.receive(function(data) {
var file = Ti.Filesystem.getFile(path2);
var fileStream = file.open(Ti.Filesystem.MODE_APPEND);
fileStream.write(data);
fileStream.close();
});
Hope that helps, at least to point in the right direction.

I found that this works for my needs, which are just to get the file onto the machine:
function downloadFile( url ){
Ti.Platform.openApplication( url );
}
This opens the URL using the machine's default browser. One downside to this approach is that the user is normally prompted to confirm the download. I use the downloadFile function in case I want to change how this works in the future.

Related

Reading JS library from CDN within Mirth

I'm doing some testing around Mirth-Connect. I have a test channel that the datatypes are Raw for the source and one destination. The destination is not doing anything right now. In the source, the connector type is JavaScript Reader, and the code is doing the following...
var url = new java.net.URL('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.fp.min.js');
var conn = url.openConnection();
conn.setRequestMethod('GET');
if(conn.getResponseCode() === 200) {
var body = org.apache.commons.io.IOUtils.toString(conn.getInputStream(), 'UTF-8');
logger.debug('CONTENT: ' + body);
globalMap.put('_', body);
}
conn.disconnect();
// This code is in source but also tested in destination
logger.debug('FROM GLOBAL: ' + $('_')); // library was found
var arr = [1, 2, 3, 4];
var _ = $('_');
var newArr = _.chunk(arr, 2);
The error I'm getting is: TypeError: Cannot find function chunk in object.
The reason I want to do this is to build custom/internal libraries with unit test and serve them with an internal/company CDN and allow Mirth to consume them.
How can I make the library available to Mirth?
Rhino actually has commonjs support, but mirth doesn't have it enabled by default. Here's how you can use it in your channel.
channel deploy script
with (JavaImporter(
org.mozilla.javascript.Context,
org.mozilla.javascript.commonjs.module.Require,
org.mozilla.javascript.commonjs.module.provider.SoftCachingModuleScriptProvider,
org.mozilla.javascript.commonjs.module.provider.UrlModuleSourceProvider,
java.net.URI
)) {
var require = new Require(
Context.getCurrentContext(),
this,
new SoftCachingModuleScriptProvider(new UrlModuleSourceProvider([
// Search path. You can add multiple URIs to this array
new URI('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/')
],null)),
null,
null,
true
);
} // end JavaImporter
var _ = require('lodash.min');
require('lodash.fp.min')(_); // convert lodash to fp
$gc('_', _);
Note: There's something funky with the cdnjs lodash fp packages that don't detect the environment correctly and force that weird two stage import. If you use https://cdn.jsdelivr.net/npm/lodash#4.17.15/ instead you only need to do var _ = require('fp'); and it loads everything in one step.
transformer
var _ = $gc('_');
logger.info(JSON.stringify(_.chunk(2)([1,2,3,4])));
Note: This is the correct way to use fp/chunk. In your OP you were calling with the standard chunk syntax.
Additional Commentary
I think it's probably ok to do it this way where you download the library once at deploy time and store it in the globalChannelMap, then retrieve it from the map where needed. It would probably also work to store the require object itself in the map if you wanted to call it elsewhere. It will cache and reuse the object created for future calls to the same resource.
I would not create new Require objects anywhere but the deploy script, or you will be redownloading the resource on every message (or every poll in the case of a Javascript Reader.)
Edit: I guess for an internal webhost, this could be desirable in a Javascript Reader if you intend for it to pick up changes immediately on the next poll without a redeploy, assuming you would be upgrading the library in place instead of incrementing a version
The benefit to using Code Templates, as Vibin suggested is that they get compiled directly into your channel at deploy time and there is no additional fetching step at runtime. Making the library available is as simple as assigning it to your channel.
Even though importing third party libraries could be an option, I was actually looking into this for our team to write our own custom functions, write unit-test for them, and lastly be able to pull that code inside Mirth. I was experimenting with lodash but it was not my end goal to use it, it is. My solution was to do a REST GET call with java in the global script. Your URL would be the GitHub raw URL of the code you want to pull in. Same code of my original question but like I said, the URL is the raw GitHub URL for the function I want to pull in.

PhantomJs onResourceReceived URL decode issue

I'm creating a web scraping bot in PhantomJs, I'm using onResourceReceived to sniff the the requests of the site and retrieve them using this simple code:
page.onResourceReceived = function(response)
{
if (response.url.match("XXXXXXX"))
{
console.log(response.url);
}
};
My problem is that response.url automatically update the data to a URL-decoded version of this. I need to check some parameters but instead of receiving something like this :
xxx.com?...&events=event20%2Cevent4%%2Cevent89%3D7%2Cevent50%2Cevent51%2Cevent52%2Cevent53%2Cevent54%2Cevent55%2Cevent56&...
I get this
xxx.com?... &events=event20%2Cevent4%2Cevent89%3D7&....
It looks like when %3D is reached it cuts the value and continues to the next property.
Is there a way to access the raw version of this data?
Thanks a lot for the help.

Storing Data in firebase using VBA

Is there any way to upload files using VBA to firebase?
Web code for uploading files in firebase
var storageRef = firebase.storage.ref("folderName/file.jpg");
var fileUpload = document.getElementById("fileUpload");
fileUpload.on(‘change’, function(evt) {
var firstFile = evt.target.file[0]; // get the first file uploaded
var uploadTask = storageRef.put(firstFile);
uploadTask.on(‘state_changed’, function progress(snapshot) {
console.log(snapshot.totalBytesTransferred); // progress of upload
});
});
But how do I use this in VBA? any help is appreciated. Also if you can point to me in right direction.
I did some research on Firebase. Currently you cannot use VBA to upload files directly to FB Storage, through API.
You can try using JS, as mentioned by you.
Another alternative will be Google Cloud Storage. Which is the back-end for firebase storage.
two ways of doing this.. Assuming there is a website where you can upload files, in such case you can use the standard IE object to navigate to a specific website, find the controls, select the files and using submit or click function upload the file..
The other way is to write a web-service and call it from vba. Both suggestions involves in calling the website/service.
Dim IE As Object
Set IE = CreateObject("internetexplorer.application")
IE.Navigate "Your upload page.."
Do While IE.ReadyState <> 4 Or IE.Busy = True
DoEvents
Loop
we don't have enough information so I just continue with the logic.
Find the upload document/filename field. insert your filename
IE.Document.getElementById("txt_upload_field").Value = myFileName
find the button/element to upload and perform click/submit action.
wait for your website and read the result
or you can write your own web service and perform a web-request using XMLHTTP. I personally would go for web-service.
there is also a third way. FTPing to your server..!

Google Maps from Firefox addon (without SDK)

I need to add a map in my adddon and I know how to do what I need in a "common webpage", like I did here: http://jsfiddle.net/hCymP/6/
The problem is I really don't know how to to the same in a Firefox Addon. I tryed importing the scripts with LoadSubScript and also tryed adding a chrome html with the next line:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
But nothing works. The best solution I found was to add part of the code in this file (the code of the script src) in my function, to import this file with loadSubScript, and all my function is executed but an empty div is returned.
Components.utils.import("resource://gre/modules/Services.jsm");
window.google = {};
window.google.maps = {};
window.google.maps.modules = {};
var modules = window.google.maps.modules;
var loadScriptTime = (new window.Date).getTime();
window.google.maps.__gjsload__ = function(name, text) { modules[name] = text;};
window.google.maps.Load = function(apiLoad) {
delete window.google.maps.Load;
apiLoad([0.009999999776482582,[[["https://mts0.googleapis.com/vt?lyrs=m#227000000\u0026src=api\u0026hl=en-US\u0026","https://mts1.googleapis.com/vt?lyrs=m#227000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"m#227000000"],[["https://khms0.googleapis.com/kh?v=134\u0026hl=en-US\u0026","https://khms1.googleapis.com/kh?v=134\u0026hl=en-US\u0026"],null,null,null,1,"134"],[["https://mts0.googleapis.com/vt?lyrs=h#227000000\u0026src=api\u0026hl=en-US\u0026","https://mts1.googleapis.com/vt?lyrs=h#227000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"h#227000000"],[["https://mts0.googleapis.com/vt?lyrs=t#131,r#227000000\u0026src=api\u0026hl=en-US\u0026","https://mts1.googleapis.com/vt?lyrs=t#131,r#227000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"t#131,r#227000000"],null,null,[["https://cbks0.googleapis.com/cbk?","https://cbks1.googleapis.com/cbk?"]],[["https://khms0.googleapis.com/kh?v=80\u0026hl=en-US\u0026","https://khms1.googleapis.com/kh?v=80\u0026hl=en-US\u0026"],null,null,null,null,"80"],[["https://mts0.googleapis.com/mapslt?hl=en-US\u0026","https://mts1.googleapis.com/mapslt?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt/ft?hl=en-US\u0026","https://mts1.googleapis.com/mapslt/ft?hl=en-US\u0026"]],[["https://mts0.googleapis.com/vt?hl=en-US\u0026","https://mts1.googleapis.com/vt?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt/loom?hl=en-US\u0026","https://mts1.googleapis.com/mapslt/loom?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt?hl=en-US\u0026","https://mts1.googleapis.com/mapslt?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt/ft?hl=en-US\u0026","https://mts1.googleapis.com/mapslt/ft?hl=en-US\u0026"]]],["en-US","US",null,0,null,null,"https://maps.gstatic.com/mapfiles/","https://csi.gstatic.com","https://maps.googleapis.com","https://maps.googleapis.com"],["https://maps.gstatic.com/intl/en_us/mapfiles/api-3/13/11","3.13.11"],[3047554353],1.0,null,null,null,null,1,"",null,null,1,"https://khms.googleapis.com/mz?v=134\u0026",null,"https://earthbuilder.googleapis.com","https://earthbuilder.googleapis.com",null,"https://mts.googleapis.com/vt/icon"], loadScriptTime);
};
//I can't use document.write but use loadSubScript insthead
Services.scriptloader.loadSubScript("chrome://googleMaps/content/Google-Maps-V3.js", window, "utf8"); //chrome://MoWA/content/Google-Maps-V3.js", window, "utf8");
var mapContainer = window.content.document.createElement('canvas');
mapContainer.setAttribute('id', "map");
mapContainer.setAttribute('style',"width: 500px; height: 300px");
mapContainer.style.backgroundColor = "red";
var mapOptions = {
center: new window.google.maps.LatLng(latitude, longitude),
zoom: 5,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
}
var map = new window.google.maps.Map(mapContainer,mapOptions);
return mapContainer;
Can you help me? I'm developing a "Firefox for Android" addon and that's why I need to do things like *window.content.*document.createElement because document is not declared, only window and I think thats may be the problem... But I can't declare everything if I don't know what Google Maps uses.
Added: I also read that Google Maps API Team has specific code that disallows you from copying the main script locally. In particular, that code "expires" every so many hours. I'm combined part of this script: https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false because I can't execute this directly (Error: write called on an object that does not implement interface HTMLDocument). So I don't have any alternative!
Use an iframe (type=content if in XUL) to display web content. There you can include whatever scripts you like. The content in the iframe will not have any special privileges, or at least should not. If you need to communicate with the privileged add-on part of your code, you can use e.g. regular HTML events (createEvent, addEventListener and friends) or the postMessage web API to pass messages.
Do not try to load remote code directly into other pages, or worse, into the browser, as this is a compatibility and security nightmare.
Because loading remote code and/or code not properly reviewed for running in a privileged context, the platform will refuse to load such scripts from remote sources (http, etc.) via loadSubScript, etc.
Should be noted, that if you'd later like to host your add-on on addons.mozilla.org and still do include remote scripts in privileged code, your add-on will be rejected until you fix it.
Also, mozilla might blocklist your add-on even if you host elsewhere if it is discovered that there are known security vulnerabilities in your add-on, per the Add-on Guidelines.

How can I download a dynamically created server side file using Flex?

I want to Export a table from my database to an excel file on the server and then download it. The following is the code that I developed for this purpose:
import flash.net.FileReference;
import flash.net.URLRequest;
public function sqlDownloadExcel():void {
var http:HTTPService = new HTTPService;
var parm:Object = new Object;
var sql:String;
sql = "insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\\inetpub\wwwroot\\myApp\\App_Data\\myExport.xls;', 'SELECT * FROM [Sheet1$]') SELECT * FROM myTable";
parm.sql = sql;
parm.db = "myDatabase";
http.url = "http://mywebsite.com/SQLconnector/sqlconnector.asp?irand="+Math.random();
http.showBusyCursor = true;
http.request = sql;
http.addEventListener(ResultEvent.RESULT, function(e:ResultEvent):void {sqlDownloadExcelResult(e);});
http.addEventListener(FaultEvent.FAULT, mssqlFault);
http.method = "POST";
sqlToken = http.send(parm);
}
public function sqlDownloadExcelResult(event:ResultEvent):void{
var request:URLRequest = new URLRequest("http://mywebsite/myApp/App_Data/myExport.xls");
var fileRef:FileReference = new FileReference();
fileRef.download(request);
}
The code creates the Excel file on the server correctly, but running the fileRef.download(request) functions causes the following error:
Error #2176: Certain actions, such as those that display a pop-up window, may only be invoked upon user interaction, for example by a mouse click or button press.
Any advice would be much appreciated.
Thank you
You can't do what you want. Security restrictions prevent your app from trying to download anything to the clieht machine without user input. That is why you're seeing the error.
I recommend creating the excel sheet on the server, saving it to the server, and then sending a URL back to your Flex app. Use navigateToURL() to open it; and the browser should handle it based on the client's browsers settings. It may download automatically; or open automatically; or it may prompt the user what it wants to do.
If necessary, you can create a server side script to routinely clean out the generated files.
Based on the code you provided, it looks like you are 90% of the way there. Just instead of using FileReference to try to download the file, use navigateToURL() to open that URLRequest.
Alternatively, you could modify your UI to say "You're file is ready, click here to get it" or something similar. Then you have user interaction and can open the download window after the user clicks the button.

Resources