WebOS : how to test if a file exists? - webos

Is it possible to test if a file exists in WebOS before proceeding with a download using the download manager service?
By default the method "download" will add an underscore + number to avoid overwriting, but what i'm trying to do is to avoid downloading a file if it already exists on the local /media/internal/files folder...
I looked all over the web but to no avail...
Any clue?
Thanks!

Probably the most straightforward way is to use an Ajax request to try to read the file.
http://forums.precentral.net/web-os-development/196320-how-parse-text-file-pres-file-system-into-app.html
If you can't read the file, it obviously hasn't been downloaded yet.
Edited to add the following from the webOS 1.4 release notes:
For Ajax.Request, if the file being requested does not exist, the request no longer gets a "404", which is considered a failure, but a "0", which is considered a success. You will need to modify your code to look for a transport.status of 0 for a file that does not exist, or 200 for a file that does. See the Mozilla documentation for more information. Example:
new Ajax.Request('/media/internal/my.file', {
method: 'get',
onSuccess: function(transport) {
//This is new for 1.4, we have to check the status of
//the transport object to see if the file exists or not.
if (transport.status == 200)
Mojo.Log.info('200 = http ok, file exists')
else if (transport.status == 0)
Mojo.Log.info('0 = response was empty, file does not exist')
},
onFailure: function(transport) {
Mojo.Log.info('In 1.3.5 if the file didn’t exist the request would return here')
}
});

You can also create a private service that leverages NodeJS.
http://nodejs.org/docs/v0.3.1/api/fs.html#fs.statSync

Related

Vimeo CORS Issue

I am trying to upload a video to Vimeo via Ajax but I am running into CORS problems with Firefox.
Here is the code I am using. It is only at the last stage of posting the file does CORS protection prevent the upload.
I have checked the headers and Cross Origin is set correctly.
$.ajax({
url:'https://api.vimeo.com/me',
crossDomain:true,
headers:{Authorization: 'bearer ',Accept:'application/vnd.vimeo.*+json;version=3.2'},
error:function(){
videoError('Couldn\'t get a quota');
},
success:function(uploadQuota){
if(uploadQuota.upload_quota.space.free > 0 && (uploadQuota.upload_quota.quota.sd == true || uploadQuota.upload_quota.quota.hd == true)){
//Get Upload Ticket
$.ajax({
url:'https://api.vimeo.com/me/videos',
data:{type:'POST'},
type:'POST',
dataType:'json',
crossDomain:true,
headers:{Authorization: 'bearer ',Accept:'application/vnd.vimeo.*+json;version=3.2'},
error:function(){
videoError('Couldn\'t get a ticket');
},
success:function(uploadTicket){
if(uploadTicket.ticket_id != ''){
//Upload File
var videoData = new FormData();
$.each($('#video_upload')[0].files, function(i, file) {
videoData.append('file_data', file);
});
$.ajax({
url:uploadTicket.upload_link_secure,
type:'POST',
headers:{Authorization: 'bearer ',Accept:'application/vnd.vimeo.*+json;version=3.2'},
data: videoData,
cache: false,
contentType: 'multipart/form-data',
processData: false,
crossDomain:true,
//dataType:'jsonp',
error:function(){
videoError('Error uploading video. Please contact FDN with the ticket id:'+uploadTicket.ticket_id);
},
success:function(uploadData,status){
//Copy id to text box
}
});
} else {
//If none, process error
}
}
});
} else {
//If none, process error
}
}
});
Is there anything obvious that I have missed or can try?
Short Answer: Vimeo POST uploads were not designed for client side JavaScript. The PUT upload system has 100% support for CORS.
Long Answer:
Vimeo POST uploads were developed to provide an incredibly easy upload experience. We give you a form. You put the form in the html of your page, The user uses the form, and everything is set. This does not support progress bars. This is not resumable.
When uploading videos, we must perform some post-processing before the video will become available. The current POST upload system handles this automatically, by redirecting the client after the upload is complete. Unfortunately there are some problems with CORS and redirects (I'm having trouble finding the details, but if I remember right the spec states to handle certain redirects as an error case).
Right now you must complete the upload yourself. We are working on improving this, but for the moment you have to find the url in the "location" header of the response from your POST. Make a GET request to this url and your upload will be complete.
Vimeo PUT uploads were designed as the fully featured advanced upload system. They are resumable, the streaming design easily supports progress bars. You can query the status of the upload, and start and stop everything on command. CORS is 100% supported. This will require use of the HTML5 file object, which has limited support for ie 9 and lower.
[Edit] There is now an unofficial Client side video upload script for the streaming workflow. You can find it here: https://github.com/websemantics/vimeo-upload
As #Dashron mentioned, the "Simple HTTP POST uploading" should be used for simple cases. For example, if you want to resume an upload you should use the "Resumable HTTP PUT uploads".
However, there are two pieces of information missing on almost all references to similar problems that I would like to share.
1) Be Careful when using vimeo-upload
As #PaulLoomijmans mentioned in a comment to #Dashron the vimeo-upload (github.com/websemantics/vimeo-upload) requires you to expose your token, which is not good for security reasons.
I actually just left a suggestion in the repository that it would still be very useful if we were able to use it with an upload_url from vimeo since then we would not have to expose our token.
2) You can check upload progress using the POST upload method
If like myself, you just want to be able to report to the user the upload progress while using the simplified upload process of the "Simple HTTP POST uploading" you can actually do so without the PUT method.
Even though not clearly documented, when using the "Simple HTTP POST uploading" you also have an "upload_link_secure" in the initial response (https://developer.vimeo.com/api/upload/videos#generate-an-upload-ticket) and you can use this as you would to with the "Resumable HTTP PUT uploads" to check your upload progress.
As such, even when using "Simple HTTP POST uploading" you can follow the information on "verify the upload" from "Resumable HTTP PUT uploads" (here: https://developer.vimeo.com/api/upload/videos#verify-the-upload). Probably the resume functionality described there will not work but you can check the upload progress and show it to the user while the upload is being made. I actually implemented it to show a progress bar in my webapp.
I hope this helps someone, as I went back and forth between the two upload methods due to the limitations/complexity that each entails.

Localhost returns 404.3 when fetching json through ajax (Windows 8.1)

So I have been getting the infamous 404.3 error when trying to use AXAJ to access a .json file launching the site (or more of a test app hehe) through WebMatrix on localhost.
Yes, I am aware of the IIS configuration. I am on Windows 8.1(x64), so I had to even turn on MIME types functionality separately. I configured a MIME type for .json with application/javascript. Then I went and added a handler to *.json, pointed it to C:\WINDOWS\system32\inetsrv\asp.dll. I set the verbs to GET and POST (those are what I use in my ajax function). I also tried unchecking the "Invoke the handler only if request is mapped to..." to no avail.
I am using one function to send data to PHP file which writes it to the JSON file and then another to fetch data from the JSON file directly. Writing through PHP works. Fetching doesn't. I am completely at a loss, does anyone have any ideas? The code I am using to fetch the data is your bog-standard ajax:
function getDate(path, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
httpRequest.open('GET', path);
httpRequest.send();
}
When I host this on my server space, it works totally fine. But I want to get it to work locally for testing purposes as well.
If writing to the file works but fetching doesn't work. Then you should check for the link of the file.
The error 404 as the name refers to, is an error for the file name. There isn't any other sort of error, even the Ajax request is working fine and giving the error 404 (file not found). So the only thing that you can do is, to make sure that while fetching the data, you use the correct link.
Here can be a help, when you send the Request through Ajax, there is a Network tab in your Browser's console. Open it, and look for the request. It would in red color denoting an error and click it. You'll see that the link you're providing isn't valid.
Look for the errors in the File Link then and update it.
The lengths I go to, to clean up my profile...
When you require a JSON format, or any file for that matter you have to specify in your request what data type you need, IIS will not make any assumptions. So
xhr.setRequestProperty('Content-Type', 'application/json');
is something one must not forget. I set also the X-Requested-With header. Note that to reproduce this issue I used IIS that is installed on Windows 10 Pro, so not exactly the same system (3 years later - holy crap!).

ASP.NET FileContentResult always 404 in production

I have an ASP.NET MVC 3 web app that's behaving strangely. There's an action that allows me to download a test file:
[HttpGet]
public ActionResult Download()
{
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "test_file.txt",
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(System.Text.Encoding.Unicode.GetBytes("HELLO THERE"), "text/plain");
}
In debug mode it works no problem, I get a file download as expected ("test_file.txt", with contents "HELLO THERE").
When published, and deployed with IIS 6, a 404 error is always returned. Anyone know why the difference and how to fix it?
Turns out the issue was a combination of routing and IIS configuration. I had some parameters for the action, one of which contained a file extension. I had set up a route so that the parameters were in the format
../Download/[text].txt
instead of
../Download?[text].txt
IIS was reading this as trying to access a file on the file system. I removed the custom route and all was resolved.

Get remote xml file by AJAX and parse it with jquery

I'm developing a HTML5 application for Blackberry OS 5+.
I'm using jQuery to download and XML file and show it using this function:
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "http://xxx.com/yyy/mTop",
dataType: "xml",
success: function(xml) {
$(xml).find('item').each(function(){
var tipo = $(this).find('tipo').text();
var porcentaje = $(this).find('porcentaje').text();
$('<div class="items"></div>').html('<p>' + tipo + ' - ' + porcentaje + '</p>').appendTo('#page-wrap');
});
}
});
});
But I'm getting this error:
XMLHttpRequest cannot load http://xxx.com/yyy/mTop. Origin file:// is not allowed by Access-Control-Allow-Origin.
How can I parse a remote XML file?
Maybe I need to convert XML retrieved to a DOM object for use with jQuery.
That's because of Same Origin Policy:
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites
you should use JSONP instead.
And the reason why you dont have a file location in your link ( url: "http ://xxx.com/yyy/mTop" ) is becouse the site "produces" an xml the moment you visit the folder, slowing down the website each time you reach it..
What you must do is:
go to http ://xxx.com/yyy/mTop on your browser
right click - view source code - copy to notepad - save as .xml
upload file to another folder
then change your code url to this url: "http ://xxx.com/yyy/mTop/yourdailyXMLcopy. xml
and keep updating the file daily..else you will kill the server querying each time any user uses your thing for a huge job...
Part of your problem is your file path is to a folder and not an XML file. Start there and see if you're problem still exists.

jquery $.ajax() in safari and chrome doesn't work

I want use $.ajax to read some infomation from xml file,here is my js code :
$.ajax({
type: "get",
url: "Database/App_all.xml",
dataType: "xml",
timeout: 2000,
beforeSend: function () {
},
success: function (xml) {
$(xml).find("app[id='id-1']").appendTo($("#contain"));
},
error: function () {
alert("ajax failed!");
}
});
However, the code only work great in firefox and opera.
It doesn't work in chrome(7.0.517.24 ) and safari(5.0.1),failed without any alert,not even the alert("ajax failed").
Is there any bug in $.ajax in chrome and safari?so how to solve the problem?
thank you very much:)
You should use chrome's or safari's built-in developer tools (ctrl+shift+i) to track JS errors and track actual AJAX requests.
Is your code wrapped in document.ready? Is there any erros in javascript console? Also try to output something after success callback line.
Another cause for this could be incorrect mime-type for your XML file returned by server. It should be [Content-type: text/xml]. You can check that in chrome's or safari's built-in developer tools - just look for headers tab when xml resource is selected. If it 's actual problem, you may need to tweak web-server configuration (main config or .htaccess for apache) to return correct mime-type.
First thank you gajendra.bang and Māris Kiseļovs give me your advices,I have konw what's wrong with my code,after I get a bad resault ,I trying to know what the $.ajax get from xml exactly,so I use firebug check the div#contain I found that:
 <div id="contain">
<auther>cocept</auther>
 </div>
yes,I think the <auther></auther> must the problem,I don't even konw the $.ajax would get the tagname as well
so I rewrite it :
success: function (xml) {
$("#contain").html($(xml).find("app[id='id-1']").find("auther").text());
}
then the div$contain is:
 <div id="contain">
cocept
 </div>
so ,the chrome and safari could show again!
I suppose you have problem with reading of the local file per ajax. Ajax can be used to read a file from the same web server, but there are some security restriction if you read it not per HTTP.
In firefox and opera you can read local files (with url like file:///C:/Program%20Files/My/Database/App_all.xml) per ajax without any problem.
In Internet Explorer you should use dataType: 'text' and then convert the text to XML (read more here).
To be able to read local files in Chrome you have to restart chrome with another parameters:
chrome.exe --allow-file-access-from-files
(Be sure that all other instances of chorme closed before starting Chrome.exe in the way).
This is a problem for local files... You should try uploading them on a web server and check from there
$(xml).find("app[id='id-1']").appendTo($("#contain"));
what is xml basically returning, an element with "#" like "#mydiv" or class like ".mydiv"
I think you are trying to access an element and if you are not returning it with "#", try
$("#"+xml).find("app[id='id-1']").appendTo($("#contain"));

Resources