How to download or upload files using javascript(Client side scripting) - javascript

I'm using the below code in javascript for downloading or uploading a file from network.
$(document).ready(function DirectoryCopy(sourceDirName, destDirName, copySubDirs, test) {
debugger;
try {
var dir = new System.IO.DirectoryInfo.ctor(sourceDirName);
var directory_stop = dir.get_Name();
var dirs = dir.GetDirectories();
if (!dir.get_Exists()) {
throw $CreateException(new System.IO.DirectoryNotFoundException.ctor$$String("Source directory does not exist or could not be found: " + sourceDirName), new Error());
}
if (!System.IO.Directory.Exists(destDirName)) {
System.IO.Directory.CreateDirectory$$String(destDirName);
}
if (test == true) {
System.IO.Directory.CreateDirectory$$String(destDirName + "\\" + "Complete");
}
var files = dir.GetFiles();
for (var $i2 = 0, $l2 = files.length, file = files[$i2]; $i2 < $l2; $i2++, file = files[$i2]) {
var temppath = System.IO.Path.Combine$$String$$String(destDirName, file.get_Name());
file.CopyTo$$String$$Boolean(temppath, true);
}
if (copySubDirs) {
for (var $i3 = 0, $l3 = dirs.length, subdir = dirs[$i3]; $i3 < $l3; $i3++, subdir = dirs[$i3]) {
var temppath = System.IO.Path.Combine$$String$$String(destDirName, subdir.get_Name());
DirectoryCopy(subdir.get_FullName(), temppath, copySubDirs, false);
}
return dirs.length;
}
return files.length;
}
catch (ex) {
var path = "d:\\tempnew\\MyTest.txt";
var sw = System.IO.File.CreateText(path);
try {
sw.WriteLine$$String(ex.toString());
}
finally {
sw.Dispose();
}
return 0;
}
});
But I am getting an error on
var dir = new System.IO.DirectoryInfo.ctor(sourceDirName);
as "System is not defined"
I'm passing values from code behind as shown below.
TextBox1.Text = #"\" + "\\10.66.3.82" + #"\" + "ipadqc" + #"\" + "IPAD Titles" + #"\" + JobName.Text + #"\" + Issue.Text;
string Macid = (string)(Session["Name"]);
string path = "D:" + #"\" + "Ipad Download" + #"\" + Macid + #"\" + Process.Text + #"\" + JobName.Text + #"\" + Issue.Text;
string a;
ClientScript.RegisterStartupScript(typeof(Page), "script", a = "DirectoryCopy('" + TextBox1.Text + "','"+path+"', true, true);", true);
please correct me if i'm wrong or please let me know if there is any better option to do it.

System.IO is a .Net thing, not a javascript thing.
For downloading files using JS, there are plenty or questions like this on Stack Overlow already. like this one
As far as uploading goes, the top answer on this question pretty much sums it up.

Related

Download file from webpage which does not seem to have explicit link

My question is similar to Download file from webpage which does not have a download link except regarding to read it on Python.
Considering this site, is there any way to obtain the download link of the file produced by the 'Consultar' button? I want to download it on R for some specific dates so I need some kind of link that will allow me to change inputs before downloading.
I suppose it has relation to the below chunk but I've not enough knowlodge in javascript/html (or whatever the site uses).
function MostraTodasOpcoes(nEscolha) {
if (nEscolha == 1) {
document.getElementById('DivOpcoes').style.display = 'none';
}
else {
document.getElementById('DivOpcoes').style.display = 'block';
}
}
function VerificaSubmit() {
vForm = document.CURVA_Z;
var Dt = vForm.Dt_Ref.value;
var DtVer = vForm.Dt_Ref_Ver.value;
nT = String(Dt).length;
nTVer = String(DtVer).length;
DtReal = String(Dt).substring(nT, nT - 4) + String(Dt).substring(5, 3) + String(Dt).substring(0, 2);
DtVerif = String(DtVer).substring(nTVer, nTVer - 2) + "/" + String(DtVer).substring(6, 4) + "/" + String(DtVer).substring(0, 4);
//alert("nTipo: " + Dt);
//alert("nTipo: " + DtReal);
//alert("nTipo: " + DtVer);
if (DtReal < DtVer) {
alert("Histórico disponível de 5 dias úteis. Digite uma data até " + DtVerif + "!");
return false;
}
if (document.CURVA_Z.escolha[0].checked) {
vForm.action = "CZ.asp";// vForm.target="_Blank";
document.CURVA_Z.Idioma[0].checked = true;
}
else {
vForm.action = "CZ-down.asp"; vForm.target = "framedown";
}
vForm.submit();
}
Thank you in advance!

How to decode Javascript _0x Hex

I tried to decode this code but I did not succeed:
var _0x147bb5 = _0xe0c4, _0x41852d = _0xe0c4, _0x39ac2c = _0xe0c4;
(function (_0x3c89e2, _0x4b3ebe) {
var _0x331330 = _0xe0c4, _0x279707 = _0xe0c4, _0x50917c = _0xe0c4, _0x489044 = _0x3c89e2();
while (!![]) {
try {
var _0x36e386 = -parseInt(_0x331330(0x133)) / 0x1 + -parseInt(_0x279707('0x12a')) / 0x2 + -parseInt(_0x331330(0x111)) / 0x3 + -parseInt(_0x331330(0x12f)) / 0x4 + parseInt(_0x279707('0x10a')) / 0x5 * (-parseInt(_0x279707('0xf1')) / 0x6) + -parseInt(_0x331330('0x109')) / 0x7 + parseInt(_0x331330(0xee)) / 0x8 * (parseInt(_0x279707(0x11a)) / 0x9);
if (_0x36e386 === _0x4b3ebe) break; else _0x489044['push'](_0x489044['shift']());
} catch (_0x108487) {
_0x489044['push'](_0x489044['shift']());
}
}
}(_0x5a9e, 0x7f5a2));
var s = _0x147bb5('0x12b') + _0x147bb5(0xdc) + _0x39ac2c('0x118') + '91', f = 0xb, l = lf(), message = _0x39ac2c('0x117') + _0x39ac2c('0xe7') + _0x39ac2c('0x108') + _0x147bb5('0xd4') + 'ot\x20' + _0x147bb5('0x104') + _0x41852d(0xd3) + _0x39ac2c('0x122') + _0x39ac2c('0xef') + _0x41852d(0x127) + _0x41852d('0x102') + _0x41852d('0xfb') + _0x147bb5(0xe2) + _0x39ac2c(0xf2) + _0x147bb5(0xe5) + _0x41852d(0xd6) + _0x39ac2c(0x125) + _0x41852d(0xff) + _0x147bb5(0xd7) + _0x41852d('0x110') + _0x39ac2c('0x11e') + _0x39ac2c(0xdd) + _0x41852d(0x107) + 'ea)';
function rtclickcheck(_0xf37bcd) {
var _0x5b07b6 = _0x39ac2c, _0x189d42 = _0x41852d, _0x158d5e = _0x147bb5;
if (navigator[_0x5b07b6(0xfd) + _0x189d42(0xf5) + 'e'] == _0x158d5e('0xe4') + _0x189d42(0xde) + 'pe' && _0xf37bcd[_0x5b07b6('0xfc') + 'ch'] == 0x3) return alert(message), ![];
if (navigator[_0x5b07b6(0xfd) + _0x189d42(0xf8) + _0x5b07b6('0x11d') + 'n'][_0x5b07b6('0xec') + _0x158d5e(0x128) + 'f'](_0x158d5e(0xe6) + 'E') != -0x1 && event[_0x189d42('0x126') + _0x158d5e('0x132')] == 0x2) return alert(message), ![];
} function _0x5a9e() {
var _0x521b96 = ['Thi', '7109872DszjuD', '4405xemFJj', 'deA', '//r', 'cre', 'hre', 'h=/', 're.', '1823784ZeLCWd', ';\x20p', 'etc', 'cap', 'cha', 'crt', 'Ooh', '794', 'TCS', '14494869UZdEDp', 'onm', 'erH', 'sio', 'com', 'ute', 'dli', 'men', 'py\x20', '_y=', 'tBy', 'uth', 'but', 'rot', 'exO', 'inn', '603236FmaGTN', '-11', 'exp', 'ous', 'toU', '2882436fEtPRL', 'dit', 'kie', 'ton', '1000745kgQiEE', '\x20Co', 's\x20N', 'hos', '//y', 'sto', 'len', 'pat', 'tri', '.ly', '350', '\x20(y', 'sca', 'gth', 'lin', 'rib', 'by\x20', 'Att', 'Net', 'ps:', 'MSI', '!!\x20', 'edo', 'ide', 'tna', '10;', 'ind', '/yu', '24DoydZk', '-\x20P', 'rCo', '4518TXMdnf', 'htt', 'N_f', 'Ele', 'Nam', 'and', 'get', 'Ver', 'ire', 'ati', 'ed\x20', 'whi', 'app', 'coo', 'eme', 'TML', 'ath', 'ect', 'sli', 'For', 'Tim', 'set', 'uid'];
_0x5a9e = function () {
return _0x521b96;
};
return _0x5a9e();
}
document[_0x147bb5(0x11b) + _0x147bb5('0x12d') + _0x147bb5('0xe8') + 'wn'] = rtclickcheck;
if (l == s && s[_0x147bb5(0xd8) + _0x147bb5('0xdf')] == f) {
var ceditf = document[_0x147bb5(0xf7) + _0x41852d(0xf4) + _0x39ac2c('0x121') + _0x147bb5(0x124) + 'Id'](_0x39ac2c(0x10d) + _0x147bb5('0x130') + _0x147bb5('0xe0') + 'k'), citf = document[_0x39ac2c(0xf7) + _0x147bb5('0xf4') + _0x39ac2c('0x121') + _0x39ac2c('0x124') + 'Id'](_0x39ac2c('0x116') + _0x39ac2c(0xe0) + 'k');
o();
var citdf = document[_0x41852d('0xf7') + _0x147bb5('0xf4') + _0x41852d(0x121) + _0x41852d('0x124') + 'Id'](_0x41852d('0x116') + _0x147bb5('0x120') + 'nk');
function checkLIC() {
var _0x4072d7 = _0x41852d, _0x264ab4 = _0x41852d, _0x1a0d97 = _0x147bb5;
if (cedit['inn' + _0x4072d7('0x11c') + _0x4072d7(0x100)][_0x1a0d97('0xd8') + _0x4072d7('0xdf')] === 0x0) return invalidLIC(), ![];
}
}
var cedit = document[_0x41852d(0xf7) + _0x39ac2c(0xf4) + _0x39ac2c(0x121) + _0x41852d('0x124') + 'Id'](_0x147bb5('0x10d') + _0x39ac2c(0x130) + _0x39ac2c(0xe0) + 'k');
function _0xe0c4(_0x488be0, _0x324154) {
var _0x5a9e88 = _0x5a9e();
return _0xe0c4 = function (_0xe0c4a8, _0x3812b4) {
_0xe0c4a8 = _0xe0c4a8 - 0xd3; var _0x1108f7 = _0x5a9e88[_0xe0c4a8];
return _0x1108f7;
}, _0xe0c4(_0x488be0, _0x324154);
}
!cedit && invalidLIC();
function o() {
_0x162858();
function _0x162858() {
var _0x139ac8 = _0xe0c4, _0x75417f = _0xe0c4, _0x15d340 = _0xe0c4, _0x5960f5 = new Date();
_0x5960f5[_0x139ac8(0x106) + _0x75417f('0x105') + 'e'](_0x5960f5[_0x75417f(0xf7) + _0x15d340(0x105) + 'e']() + 0x15180 * 0x3);
var _0x43eec0 = _0x75417f(0x12c) + _0x15d340(0xf9) + 's=' + _0x5960f5[_0x15d340('0x12e') + _0x139ac8(0x119) + _0x139ac8(0xda) + 'ng']();
document[_0x15d340('0xfe') + 'kie'] = _0x15d340(0x114) + _0x139ac8('0x123') + _0x15d340('0xeb') + _0x15d340('0xd9') + _0x75417f('0x10f') + ';', document[_0x75417f(0xfe) + _0x15d340('0x131')] = 'JSO' + _0x139ac8(0xf3) + _0x75417f('0x113') + 'h' + '=' + fetchon + ';' + _0x43eec0 + (_0x139ac8(0x112) + _0x15d340('0x101') + '=/'), window['loc' + _0x15d340(0xfa) + 'on'][_0x15d340('0x10e') + 'f'] = api;
}
}
function invalidLIC() { }
function checkLIC() {
var _0x4dac69 = _0x39ac2c, _0x55bc12 = _0x41852d, _0x4c895a = _0x147bb5;
if (cedit[_0x4dac69(0x129) + _0x4dac69('0x11c') + _0x4c895a(0x100)][_0x55bc12('0xd8') + _0x4dac69(0xdf)] === 0x0) return invalidLIC(), ![]; else {
if (cedit[_0x4c895a('0xf7') + _0x55bc12(0xe3) + _0x55bc12(0xe1) + _0x4c895a('0x11f')](_0x4dac69(0x10e) + 'f') !== _0x4c895a(0xf2) + _0x4c895a('0xe5') + _0x55bc12('0x10c') + 'ebr' + _0x4c895a('0xf6') + _0x4c895a(0xdb) + _0x55bc12('0xed') + _0x4c895a(0xe9) + 'a/') return invalidLIC(), ![];
}
}
checkLIC(),
setInterval(
function () {
checkLIC();
},
0x1388
);
function lf() {
var _0x5a8bac = _0x39ac2c, _0x505e9a = _0x147bb5, _0xd36b1d = _0x147bb5, _0x5b07b5 = location[_0x5a8bac(0xd5) + _0x505e9a('0xea') + 'me'][_0x5a8bac(0x103) + 'ce'](0x2)[_0x505e9a(0x103) + 'ce'](0x0, -0x2) + '24', _0x130606 = 0x0;
if (_0x5b07b5[_0x5a8bac('0xd8') + _0xd36b1d('0xdf')] == 0x0) return _0x130606;
for (i = 0x0; i < _0x5b07b5[_0x5a8bac('0xd8') + _0xd36b1d(0xdf)]; i++) {
char = _0x5b07b5[_0xd36b1d('0x115') + _0xd36b1d('0xf0') + _0xd36b1d(0x10b) + 't'](i), _0x130606 = (_0x130606 << 0x5) - _0x130606 + char, _0x130606 = _0x130606 & _0x130606;
}
return _0x130606;
}
https://jsfiddle.net/utpgLw06/
So My first approach is to use online tools, but none of them works. I also try to manually decode it by calling the function name console.log(_0x331330(0x133)) but it just shows strings that I don't understand. I also tried to decode those strings by using much hex at numerical decoders but none of them works. Anyone can help me, please?
I played a bit with this code:
The _Ox names are just variable names. You can make the code more readable by collecting all such distinct names and replace them with more readable names, like v1, v2, v3, ....
There are two variables referenced which are not defined, api and fetchon. I suppose that the page where this script runs, has defined them somewhere.
The first part of the script is harmless and just shuffles an array of strings, which is later used to obfuscate strings (often property names). You can execute it
The code that needs de-obfuscation is the code that gets/sets properties of window, document, nagivator, ...and other objects. You can get a long way by putting that part of the script in a template literal, and evaluating all those expressions that evaluate to a property name, or to a value assigned to a property.
Functions and immediate code are mixed. It helps to reorganise that a bit.
Some functions have local variables which are constants and have unique names. These can be moved to the global scope and can often be evaluated safely, so the rest of the function's code can be clarified inside a template literal (like explained above).
Any remaining variables (not evaluated), can be given more telling names by seeing how they are used.
Anyway, here is the result I got to:
function rtclickcheck(e) {
if (navigator.appName == "Netscape" && e.which == 3)
return alert("Ooh!! This Not For Copy - Protected by https://yuthemestore.com (yuidea)"), false;
if (navigator.appVersion.indexOf("MSIE") != -1 && event.button == 2)
return alert("Ooh!! This Not For Copy - Protected by https://yuthemestore.com (yuidea)"), false;
}
document.onmousedown = rtclickcheck;
function o() {
var date = new Date();
date.setTime(date.getTime() + 259200);
var expiration = "expires=" + date.toUTCString();
document.cookie = "cap_y=10;path=/;";
// fetchon and api must be defined?
document.cookie = "JSON_fetch=" + fetchon + ";" + expiration + "; path=/";
window.location.href = api;
}
function invalidLIC() { }
function checkLIC() {
if (cedit.innerHTML.length === 0)
return invalidLIC(), false;
else {
if (cedit.getAttribute("href") !== "https://rebrand.ly/yuidea/")
return invalidLIC(), false;
}
}
function lf() {
var decrypted = location.hostname.slice(2).slice(0, -2) + '24',
encrypted = 0;
if (decrypted.length == 0) return encrypted;
for (i = 0; i < decrypted.length; i++) {
char = decrypted.charCodeAt(i);
encrypted = (encrypted << 5) - encrypted + char;
encrypted = encrypted & encrypted;
}
return encrypted;
}
var l = lf();
var s = "-1135079491";
if (l == s && s.length == 11) {
var ceditf = document.getElementById("creditlink"),
citf = document.getElementById("crtlink");
o();
var citdf = document.getElementById("crtdlink");
function checkLIC() {
if (cedit.innerHTML.length === 0)
return invalidLIC(), false;
}
}
var cedit = document.getElementById("creditlink");
!cedit && invalidLIC();
checkLIC();
setInterval(checkLIC, 5000);
This code seems to do the following things:
Avoid that the user can view the source of the page with a right click
Obfuscates the current site's hostname through bitshifting and summing, and checks that the result has a certain value. I didn't try to find out what the original hostname would have to be to get a match.
Sets some variables like ceditf which are not used in this script, but maybe elsewhere
If the host matches, two cookies are set, and a navigation occurs (to whatever api has as URL)
Every 5 seconds checks the content of the element with id "creditlink".
If the contents of "creditlink" are not as expected it calls invalidLIC, but that function is empty -- I think that might have had code in a previous version of this script, but it was later removed.

How to "postMessage" to host from within pdf when viewed in IE9 object element

I am attempting to do a small PoC with PDFs and have run into an issue. I am looking to post a message to a PDF and have the PDF post a message to the browser.
The deets:
I am viewing the PDF in an "object" element in IE9. I am using itextsharp to prefill a pdf template on the server, inject some app level javascript (post message and on message stuff) and then serve that up to the browser via a filestreamresult. I am using Reader 10 to view the PDF in IE9.
What works:
So far, everything works except for the PDF posting a message to the browser. I can post a message to the PDF, from the browser, no problem and all of the fields are prefilled as desired.
What doesn't work:
When I try using this.hostContainer.postMessage(["something","somethingmore"]) I get an Acrobat Escript window that says "hostContainer is not defined". I have also tried using "event.target.hostContainer" but I get "event.target is not defined". I am at a loss of what to do and any insight would be super helpful.
Reference links:
Acrobat Javascript API
Stackoverflow How-To on this topic
Original guide I used
The code:
My form view:
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
My custom javascript string method:
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(doc.xfa);" +
"console.println('Doc xfa value = ' + doc.xfa);" +
// "event.target.hostContainer.postMessage(['hello from pdf!']);" +
// "this.hostContainer.postMessage(['hello from pdf!']);"+
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}
My method for filling and sending the form to the browser:
public MemoryStream GetFilledRequestForm(string fileDirectory, User user, FormView formView)
{
var pdfStream = new MemoryStream();
var templateFilePath = GetRequestTypeTemplateFilePath(fileDirectory, _requestModule.FormTemplateFileName);
var pdfReader = new PdfReader(templateFilePath);
// pdfReader.RemoveUsageRights();
var stamper = new PdfStamper(pdfReader, pdfStream);
var formFields = GetFormFields(user, formView, pdfReader);
foreach (var field in formFields.Where(f => f.Value != null))
{
stamper.AcroFields.SetField(field.Name, field.Value);
}
stamper.FormFlattening = false;
var newJs = GetCustomJavascript(stamper.Reader.JavaScript);
stamper.AddJavaScript("newJs", newJs);
stamper.Close();
byte[] byteInfo = pdfStream.ToArray();
var outputStream = new MemoryStream();
outputStream.Write(byteInfo, 0, byteInfo.Length);
outputStream.Position = 0;
return outputStream;
}
Ok, so I have resolved it, with some help of course. I found the key at this stack overflow post. I needed to wait for the object to load before assigning the message handler. Additionally, I needed a global variable in the pdf javascript to be able to post the message.
Html/Javascript: (the key here is the loadListener() function)
#model WebModel.FormView
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
<input id="buttonPost" type="button" value="post to pdf"/>
<script type="text/javascript">
var PDFObject = document.getElementById("pdfFrame");
function loadListener() {
if (typeof PDFObject.readyState === 'undefined') { // ready state only works for IE, which is good because we only need to do this for IE because IE sucks in the first place
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
return;
}
if (PDFObject.readyState == 4) {
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
} else {
setTimeout(loadListener, 500);
}
}
function messageFunc(data) {
debugger;
var messagedata = data;
alert('finally!!');
}
function sendToPdf() {
if(PDFObject!= null){
PDFObject.postMessage(
["a", "b"]);
}
}
$('#pdfFrame').ready(function() {
loadListener();
$('#buttonPost').on('click', function() {
sendToPdf();
});
});
</script>
My new function to create the javascript: (the key here is var appHostContainer)
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"var appHostContainer = this.hostContainer;" +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(stringArray);" +
"appHostContainer.postMessage(['hello from pdf!']);" +
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}

Downloading multiple files simultaneously in blackberry using webworks and cordova 2.9

I'm working on an app which needs to download some files from a webserver and store them on the device so they can be used offline. The code I'm using works fine in Android and iOS, however I'm having difficulty downloading more than one file on blackberry 10.
From looking at the web console it seems that the success callback is executed successfully for the first file, but not for any of the subsequent files. The fail callback is not being called for the subsequent files either.
I'm using cordova 2.9, and I've included all the required webworks plugins. I have set up access to my domain in config.xml and have set the access_shared permission.
I've also edited the cordova FileTransfer.download function to call the webworks download api "blackberry.io.filetransfer.download".
Below is the JavaScript code that I've written.
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
//replace list with your files you wish to download
var files = ["files/file1.txt", "files/file2.txt", "files/dir1/file3.txt"];
initiateDownload(files);
//getFSRoot(files);
}
var filesToDownload = 0;
var fileList = new Array();
var failedFileList;
var numFailedFiles = 0;
var currentFileIndex;
var retryCount = 0;
var root;
function isOnline(){
var bIsOnline = false;
if (navigator.connection.type != Connection.NONE && navigator.connection.type != Connection.UNKNOWN)
{
bIsOnline = true;
}
return bIsOnline;
}
function initiateDownload(files){
alert("initiate download");
failedFileList = new Array();
filesToDownload = files.length;
blackberry.io.sandbox = false;
for (i = 0; i < files.length; i++)
{
currentFileIndex = i;
console.log("initiate download of file index " + i + " File Name: " + files[i]);
getFile(files[i]);
}
}
function getFile(filePath)
{
//TODO: Do we need to make this function recursive to serialize asynchronous downloads?
console.log("START of function getFile() for " + filePath);
window.requestFileSystem(
LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem)
{
console.log("Success getting filesystem for filePath: " + filePath);
createDirs(fileSystem.root, filePath, -1);
},
function(error){
console.log("Failed to get the filesystem for filePath: " + filePath);
}
);
}
function createDirs(parentDir, filePath, index)
{
console.log("createDirs params ===> parentDir=" + parentDir.toURL() + " filePath=" + filePath + " index=" + index);
arrDirs = filePath.split("/");
if (index >= (arrDirs.length - 1))
{
createFile(arrDirs[index], parentDir, filePath);
}
else
{
dirName = "myapp";
if (index >= 0)
{
dirName = arrDirs[index];
}
//if device is Blackberry, build up a full directory path as we are trying to install outside of sandbox
var path, dirToCreate = ""
if(device.platform = "BlackBerry"){
path = "myapp/";
console.log("JHPaths ======> arrDirs = " + arrDirs + " index = " +index);
for (i = 0; i <= index; i++){
path += arrDirs[i] + "/";
console.log("path = " + path + " i = " + i + " index = " + index);
}
dirToCreate = blackberry.io.home + "/" + path;
dirToCreate = dirToCreate.substring(0, dirToCreate.length - 1);
console.log("JHPaths Trying to create " + dirToCreate);
dirName = dirToCreate;
}
parentDir.getDirectory(dirName, {create: true, exclusive: false},
function (directoryEntry) {
console.log("Got directory " + directoryEntry.fullPath);
createDirs(directoryEntry, filePath, index + 1);
},
function (error) {console.log("Failed to get directory " + dirName + " Error code : " + error.code);});
}
}
function createFile(fileName, parentDir, filePath)
{
parentDir.getFile(
fileName, {create: true, exclusive: false},
function gotFileEntry(fileEntry)
{
localPath = fileEntry.fullPath;
if (isOnline())
{
console.log("Before remove");
fileEntry.remove(
function(){
console.log("FileEntry remove() was successful");
},
function(){
console.log("FileEntry remove() was failed");
}
);
console.log("After remove");
var fileTransfer = new FileTransfer();
//replace URL with the URL code you wish to download from
var baseURL = "http://<ip-address>/WebFolder/";
var uri = encodeURI(baseURL + filePath);
fullFilePath = blackberry.io.home + "/myapp/" + filePath;
fileTransfer.download(
uri,
/*localPath,*/
fullFilePath,
function(entry) {
console.log("download complete: " + entry.fullPath);
/*if(currentFileIndex < fileList.length){
currentFileIndex++;
}*/
if (device.platform == "iOS")
{
console.log("Setting file metadata");
parentDir.getFile(
fileName, {create:false, exclusive: false},
function gotFileEntry(fileEntry)
{
fileEntry.setMetaData(
function(){console.log("Set metadata for " + fileEntry.fullPath)},
function(){console.log("Set metadata failed for " + fileEntry.fullPath)},
{"com.apple.MobileBackup": 1}
);
},
function getFileFailed(fileError)
{
console.log("Get file failed:" + fileError.code);
}
);
}
filesToDownload--;
if (filesToDownload == 0 && failedFileList.length == 0)
{
//Call to retry failed Files
}
else if(failedFileList.length > 0){
if(retryCount < 1){
retryFailedFiles();
}
else{
}
}
},
function(error) {
console.log("Cache file download error source " + error.source);
console.log("Cache file download error target " + error.target);
console.log("Cache file download error code " + error.code);
//failedFileList[numFailedFiles++] = filePath;
failedFileList[numFailedFiles++] = filePath;
filesToDownload--;
if (filesToDownload == 0 && failedFileList.length == 0)
{
}
else if(failedFileList.length > 0){
if(retryCount < 1){
retryFailedFiles();
}
else{
}
}
}
);
}
},
function getFileFailed(fileError)
{
console.log("Create file failed:" + fileError.code);
filesToDownload--;
/*if (filesToDownload == 0)
{
callbackDeferred.resolve();
}*/
}
);
}
function retryFailedFiles(){
console.log("Retrying failed files");
retryCount++;
initiateDownload(failedFileList);
}

how to create two different nameSpaces in one same nameSpace avoiding covering the first one?

i want to use two string(which i dont know their content) to create two nameSpace.And i dont want to create a new one if the nameSpace exists.
here is my code:
function createNameSpace(nameSpace)
{
var spaceArr = nameSpace.split(".");
var curSpace = window;
//judge if this nameSpace exists.
var i;
for(i in spaceArr)
{
curSpace = curSpace[spaceArr[i]];
if(curSpace)
window.alert("nameSpace1:" + nameSpace + "\ncurSpace do exists:" + curSpace + "\ni:" + i + "\nspaceArr[i]:" + spaceArr[i] + "|");
else
{
curSpace = {};
window.alert("nameSpace1:" + nameSpace + "\ncurSpace not found:" + curSpace + "\ni:" + i + "\nspaceArr[i]:" + spaceArr[i] + "|");
break;
}
}
//now curSpace must have been created.
i++;
//window.alert("nameSpace2:" + nameSpace + "\ni:" + i + "\nspaceArr.length:" + spaceArr.length);
//create the nameSpace
for(;i < spaceArr.length; i++)
{
//window.alert("nameSpace2:" + nameSpace + "\ni:" + i + "\nspaceArr.length:" + spaceArr.length);
if(i == 0)
{
window[spaceArr[i]] = {};
curSpace = window[spaceArr[i]];
}
else
{
//window.alert("nameSpace3:" + nameSpace + "\ncurSpace[spaceArr[i]]:" + curSpace[spaceArr[i]]);
curSpace[spaceArr[i]] = {};
curSpace = curSpace[spaceArr[i]];
}
}
return curSpace;
}
the problem is,if i send"myTest.myNameSpace"and"myTest.monaNameSpace" into this func,it all alert"curSpace not found",which should be "curSpace do exists:" when i send "myTest.monaNameSpace" . i can`t tell where the mistakes are,can someone tell me?
I think your algorithm is a little to complex. I refactored it a little and added a test to it and verified it worked in the console. I have also written this code several times, so i am pretty sure i have hit your requirements
function createNameSpace(nameSpace)
{
var spaceArr = nameSpace.split(".");
var curSpace = window;
//judge if this nameSpace exists.
var i = 0;
for(i = 0;i < spaceArr.length; i++)
{
var next = spaceArr[i];
console.log(curSpace, next);
if(curSpace[next] == undefined)
{
curSpace[next] = {};
curSpace = curSpace[next]
}
else
{
curSpace = curSpace[next];
}
}
return curSpace;
}
createNameSpace("myTest.myNameSpace");
console.log(myTest.myNameSpace);
myTest.myNameSpace.myName = "Leat Hakkor";
createNameSpace("myTest.monaNameSpace");
console.log(myTest.monaNameSpace);
console.log(myTest.myNameSpace.myName);

Categories