Image upload with phonegap and windows8 not working like on android - windows-8

I am trying to upload a photo captured with phonegap using filetransfer;I managed with android , but it doesn't work on windows 8, in fact the problem I see is due to the url of the image; under android is file ://url but on Windows 8 it is something kind of blob:1234566778rerui2, help me plz, here is the code
<!DOCTYPE html>
<html>
<head>
<title>Exemple de transfert de fichier</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.3.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Attendre que PhoneGap soit prêt
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap est prêt
//
function onDeviceReady() {
// Récupérer l'URI d'un fichier image à partir de la source spécifiée
navigator.camera.getPicture(uploadPhoto,
function(message) { alert('Echec de récupération du fichier'); },
{ quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://un.serveur.com/upload.php", win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Réponse = " + r.response);
console.log("Envoyé = " + r.bytesSent);
}
function fail(error) {
alert("Une erreur est survenue : Code = " = error.code);
}
</script>
</head>
<body>
<h1>Exemple</h1>
<p>Transfert de fichier</p>
</body>
</html>

we have to change on the corodova.js for windows 8 because there is a bug there , you can check this link: https://groups.google.com/forum/#!topic/phonegap/h2k-GeBJ0kY

Related

MSE WebM video with no audio

I've written a MSE video player and it's loading WebMs. These are loading well, however I have a problem with video files with no audio tracks.
I've tried changing the codec depending on if there is audio
mediaSource.addSourceBuffer(`video/webm; ${videoHasAudio(asset) ? 'codecs="vp9,vorbis"' : 'codecs="vp9"'}`)`
And I thought this was working but now isn't. How do I run silent WebMs in MSE?
I have added sample MSE project here:
https://github.com/thowfeeq178/MediaSourceExtention
checkout the example in the github
overview:
we need to add one for video and one for audio like below:
// BBB : https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps.mpd
var baseUrl = "https://dash.akamaized.net/akamai/bbb_30fps/";
var initUrl = baseUrl + "bbb_30fps_480x270_600k/bbb_30fps_480x270_600k_0.m4v";
var initAudioUrl = baseUrl + "bbb_a64k/bbb_a64k_0.m4a";
var templateUrl =
baseUrl + "bbb_30fps_480x270_600k/bbb_30fps_480x270_600k_$Number$.m4v";
var templateUrlForAudio = baseUrl + "bbb_a64k/bbb_a64k_$Number$.m4a";
var sourceBuffer;
var audioSourceBuffer;
var index = 0;
var audioIndex = 0;
var numberOfChunks = 159;
var video = document.querySelector("video");
var ms = new MediaSource();
function onPageLoad() {
console.log("page loaded ..");
if (!window.MediaSource) {
console.error("No Media Source API available");
return;
}
// making source controlled by JS using MS
video.src = window.URL.createObjectURL(ms);
ms.addEventListener("sourceopen", onMediaSourceOpen);
}
function onMediaSourceOpen() {
// create source buffer
sourceBuffer = ms.addSourceBuffer('video/mp4; codecs="avc1.4d401f"');
audioSourceBuffer = ms.addSourceBuffer('audio/mp4; codecs="mp4a.40.5"');
// when ever one segment is loaded go for next
sourceBuffer.addEventListener("updateend", nextSegment);
audioSourceBuffer.addEventListener("updateend", nextAudioSegment);
// fire init segemnts
GET(initUrl, appendToBuffer);
GET(initAudioUrl, appendToAudioBuffer);
// play
video.play();
}
// get next segment based on index and append, once everything loaded unlisten to the event
function nextSegment() {
var url = templateUrl.replace("$Number$", index);
GET(url, appendToBuffer);
index++;
if (index > numberOfChunks) {
sourceBuffer.removeEventListener("updateend", nextSegment);
}
}
// get next audio segment based on index and append, once everything loaded unlisten to the event
function nextAudioSegment() {
var audioUrl = templateUrlForAudio.replace("$Number$", audioIndex);
GET(audioUrl, appendToAudioBuffer);
audioIndex++;
if (index > numberOfChunks) {
audioSourceBuffer.removeEventListener("updateend", nextAudioSegment);
}
}
// add to existing source
function appendToBuffer(videoChunk) {
if (videoChunk) {
sourceBuffer.appendBuffer(new Uint8Array(videoChunk));
}
}
function appendToAudioBuffer(audioChunk) {
if (audioChunk) {
audioSourceBuffer.appendBuffer(new Uint8Array(audioChunk));
}
}
// just network thing
function GET(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "arraybuffer";
xhr.onload = function(e) {
if (xhr.status != 200) {
console.warn("Unexpected status code " + xhr.status + " for " + url);
return false;
}
callback(xhr.response);
};
xhr.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>MSE Demo</title>
</head>
<body onload="onPageLoad()">
<h1>MSE Demo</h1>
<div>
<video muted controls width="80%"></video>
</div>
</body>
</html>

Custom Google Search (CSE): how add the query string at the end of the result links?

I'm looking for a way to configure Google Custom Search to append all search parameters to the generated urls of the search results so that on the target page the search parameters are known. E.g. if the query was "mot1 mot2" then something like "?keyword=mot1+mot2" should be appened to the page url.
If this is not possible, how can I determine the search query used to find a certain page so that I can highlight the search words on that page?
Here is my current script for Google Custom Search:
<script>
(function() {
var cx = 'xxx:xxxx';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
// AJOUT: Create a Custom Search Element
var options = {}
options[google.search.Search.RESTRICT_EXTENDED_ARGS] = {'as_sitesearch' : 'www.monsite.org/rep1/'};
var customSearchControl = new google.search.CustomSearchControl(cx, options);
})();
</script>
<gcse:search></gcse:search>
Thank's a lot ! ;-))
Whatever you are trying to do it would probably be best (and more reliably) achieved using Google CSE API.
Particularly, check out this answer to get some insight on how to use prefillQuery and execute methods to populate and trigger your customized query.
Nevertheless, if you don't need anything better, here is a quick and dirty solution for the standard setup:
(function() {
var cx = '017643444788069204610:4gvhea_mvga'; // Insert your own Custom Search engine ID here
var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true;
gcse.src = (document.location.protocol == 'https' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
function addExtraParams(){
var searchBoxWords = $("input.gsc-input").val().split(' '),
appendToQueryStr="";
for (i=0;i<searchBoxWords.length;i++){
appendToQueryStr+="&word"+i+"="+searchBoxWords[i];
}
setTimeout(
function(){
$("a.gs-title").each(function(){
$(this).attr(
"href",
$(this).attr("href")+appendToQueryStr
);
});
}
, 2000
);
};
$(document).ready(function(){
setTimeout(
function(){
$( 'input.gsc-input' ).keyup( function(e){
if ( e.keyCode == 13 ) {
addExtraParams();
}
});
$( 'input.gsc-search-button' ).click(function(){
addExtraParams();
});
}
, 1000
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<gcse:search></gcse:search>
(The embedded snippet does not capture intro key, run the code on this fiddle for full functionality)
[EDIT] For your test of this code to work, you need to move the line where you load jQuery, so you'll get something like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="recherche">`enter code here`
<script type="text/javascript">
//var cx = '015556257213647319991:iyaymywao1c';
(function() {
var cx = '015556257213647319991:iyaymywao1c'; // Insert your own Custom Search engine ID here
var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true;
gcse.src = (document.location.protocol == 'https' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
function addExtraParams(){
var searchBoxWords = $("input.gsc-input").val().split(' '),
appendToQueryStr="";
for (i=0;i<searchBoxWords.length;i++){
appendToQueryStr+="&word"+i+"="+searchBoxWords[i];
}
setTimeout(
function(){
$("a.gs-title").each(function(){
$(this).attr(
"href",
$(this).attr("href")+appendToQueryStr
);
});
}
, 2000
);
};
$(document).ready(function(){
setTimeout(
function(){
$( 'input.gsc-input' ).keyup( function(e){
if ( e.keyCode == 13 ) {
addExtraParams();
}
});
$( 'input.gsc-search-button' ).click(function(){
addExtraParams();
});
}
, 1000
);
});
</script>
<gcse:search></gcse:search>
</div>
</body>
</html>
**To thank you I give for all my solution after many many search:**
-----------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>www.religare.org</title>
</head>
<body>
<style>
/* Affichage des url long pour les livres trouvés */
.gs-webResult.gs-result .gs-visibleUrl { display:block; }
.gs-webResult.gs-result .gs-visibleUrl-short { display:none; }
/* Barre de recherche Google */
#cse {
max-width:600px;
}
/* Enlever l'image du champ de saisie */
#gsc-i-id1 {
background-image: none !important;
}
</style>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script>
// ID de mon CSE (Custom Search Engine) personnalisé chez Google: https://cse.google.com/cse
var cx = 'xxx:xxxx';
// Création de la barre de recherche Google
(function() {
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
// Configuration de la recherche (utilise la librairie http://www.google.com/jsapi ci-dessus)
google.load('search', '1');
google.setOnLoadCallback(function(){
var customSearchOptions ={};
/* Add Custom Search Option: restrict directory */
customSearchOptions [google.search.Search.RESTRICT_EXTENDED_ARGS]={"as_sitesearch": "www.religare.org/livre/christianisme/"};
var customSearchControl = new google.search.CustomSearchControl(cx, customSearchOptions );
/* Add Custom Search Option: more result per page */
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
/* Add query addition: restrict filetype */
customSearchControl.setSearchStartingCallback( this, function(control, searcher, query) {
searcher.setQueryAddition("filetype:htm OR filetype:html");
}
);
}, true);
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
// Ajouter aux URL trouvées (TITRES et IMAGES) les mot-clés recherchés en paramètre ("?mot1=val1&mot2=val2") afin que les pages cibles puissent les surligner une fois ouvertes
function addExtraParams(){
var searchBoxWords = $("input.gsc-input").val().split(' '),
appendToQueryStr="";
separator="?";
for (i=0;i<searchBoxWords.length;i++){
appendToQueryStr+=separator+"mot"+i+"="+searchBoxWords[i];
separator="&";
}
// Pour chaque URL des TITRES trouvés: ajouter la chaine de recherche en paramètre (+vider liens data inutiles préemptant href)
$("a.gs-title").each(function(){
// On ne garde que la partie gauche de l'url avant le "?" (sans ses paramètres au cas où ils auraient déjà été ajoutés)
var searchURL = this.href.split('?');
$(this).attr("href", searchURL[0]+appendToQueryStr);
$(this).attr("data-cturl", "");
$(this).attr("data-ctorig", "");
});
// Pour chaque URL des IMAGES trouvées: ajouter la chaine de recherche en paramètre (+vider liens data inutiles préemptant href)
$("a.gs-image").each(function(){
// On ne garde que la partie gauche de l'url avant le "?" (sans ses paramètres au cas où ils auraient déjà été ajoutés)
var searchURL = this.href.split('?');
$(this).attr("href", searchURL[0]+appendToQueryStr);
$(this).attr("data-cturl", "");
$(this).attr("data-ctorig", "");
});
}
// Actualiser automatiquement (chaque 500ms) l'ajout des mot-clés recherchés en paramètre des URL trouvées
// (car les url de résultat ne seront générées par Google en asynchrones qu'après le submit du formulaire de recherche, et changent si on clic sur la pagination du résultat)
// Utilise la librairie (pour les appel avec $): https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
$(document).ready(function(){
setInterval(
function(){
addExtraParams();
} , 500 );
});
</script>
<div id="cse">Chargement de la barre de recherche Google en cours...</div>
<script type="text/javascript">
// Focus automatiquement sur le chp de recherche au chargement de la page
$(window).load( function() {
var input = $('#gsc-i-id1');
input.focus();
});
</script>
</body>
</html>

Simple WebRTC Example! But why it didn't work & what did I do wrong?

I found this link on the internet which demonstrates how WebRTC works https://shanetully.com/2014/09/a-dead-simple-webrtc-example/
Its source code is here https://github.com/shanet/WebRTC-Example
Now, I am trying to follow the example and here what I did:
1- I created a folder name voicechat
2- I created 2 folders inside voicechat. That is voicechat\client & voicechat\server
3- I put the index.html & webrtc.js into voicechat\client
4- I put server.js into voicechat\server
5- I put the folder voicechat into my Tomcat webapps folder. So The path will be like this C:\apache-tomcat-7.0.53\webapps\ROOT\voicechat
6- I started my Tomcat.
7- I opened http://xxx.xxx.xxx.xxx/voicechat/client/index.html in my PC & the webpage showed webcam (webcam 1) of my PC. No problem.
8- I opened http://xxx.xxx.xxx.xxx/voicechat/client/index.html in another PC & the webpage also showed webcam (webcam 2) of other PC. But I could not see webcam 1 of my PC. And when I talked in my PC, the person sitting in other PC could not hear what I am talking and via versa.
So, why it didn't work What did I do wrong?
Here is the code of 3 files:
index.html
<html>
<head>
<script src="webrtc.js"></script>
</head>
<body>
<video id="localVideo" autoplay muted style="width:40%;"></video>
<video id="remoteVideo" autoplay style="width:40%;"></video>
<br />
<input type="button" id="start" onclick="start(true)" value="Start Video"></input>
<script type="text/javascript">
pageReady();
</script>
</body>
</html>
webrtc.js
var localVideo;
var remoteVideo;
var peerConnection;
var peerConnectionConfig = {'iceServers': [{'url': 'stun:stun.services.mozilla.com'}, {'url': 'stun:stun.l.google.com:19302'}]};
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
window.RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate || window.webkitRTCIceCandidate;
window.RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.webkitRTCSessionDescription;
function pageReady() {
localVideo = document.getElementById('localVideo');
remoteVideo = document.getElementById('remoteVideo');
serverConnection = new WebSocket('ws://127.0.0.1:3434');
serverConnection.onmessage = gotMessageFromServer;
var constraints = {
video: true,
audio: true,
};
if(navigator.getUserMedia) {
navigator.getUserMedia(constraints, getUserMediaSuccess, errorHandler);
} else {
alert('Your browser does not support getUserMedia API');
}
}
function getUserMediaSuccess(stream) {
localStream = stream;
localVideo.src = window.URL.createObjectURL(stream);
}
function start(isCaller) {
peerConnection = new RTCPeerConnection(peerConnectionConfig);
peerConnection.onicecandidate = gotIceCandidate;
peerConnection.onaddstream = gotRemoteStream;
peerConnection.addStream(localStream);
if(isCaller) {
peerConnection.createOffer(gotDescription, errorHandler);
}
}
function gotMessageFromServer(message) {
if(!peerConnection) start(false);
var signal = JSON.parse(message.data);
if(signal.sdp) {
peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp), function() {
peerConnection.createAnswer(gotDescription, errorHandler);
}, errorHandler);
} else if(signal.ice) {
peerConnection.addIceCandidate(new RTCIceCandidate(signal.ice));
}
}
function gotIceCandidate(event) {
if(event.candidate != null) {
serverConnection.send(JSON.stringify({'ice': event.candidate}));
}
}
function gotDescription(description) {
console.log('got description');
peerConnection.setLocalDescription(description, function () {
serverConnection.send(JSON.stringify({'sdp': description}));
}, function() {console.log('set description error')});
}
function gotRemoteStream(event) {
console.log('got remote stream');
remoteVideo.src = window.URL.createObjectURL(event.stream);
}
function errorHandler(error) {
console.log(error);
}
server.js
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({port: 3434});
wss.broadcast = function(data) {
for(var i in this.clients) {
this.clients[i].send(data);
}
};
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
wss.broadcast(message);
});
});
server.js is intended to be run as a node server for websocket signaling. Run it with node server.js. You shouldn't need Tomcat at all.
From the project readme:
The signaling server uses Node.js and ws and can be started as such:
$ npm install ws
$ node server/server.js
With the client running, open client/index.html in a recent version of either Firefox or Chrome.
You can open index.html with just a file URL.
I changed HTTPS_PORT = 8443 to HTTP_PORT = 8443. Do same with all the https; change it to http. Next, have only const serverConfig = { }; as the serverConfig and delete serverConfig in const httpServer = http.createServer(handleRequest); After these changes, u can now run your server with npm start.
This is the ultimate simple code can do the job. No need to install Node.js. Why need to install Node.js?
AND put that code into index.html file and start your webhost, then you done!
<!DOCTYPE html>
<html>
<head>
<script src="//simplewebrtc.com/latest.js"></script>
</head>
<body>
<div id="localVideo" muted></div>
<div id="remoteVideo"></div>
<script>
var webrtc = new SimpleWebRTC({
localVideoEl: 'localVideo',
remoteVideosEl: 'remoteVideo',
autoRequestMedia: true
});
webrtc.on('readyToCall', function () {
webrtc.joinRoom('My room name');
});
</script>
</body>
</html>

Multiple Bing Map Pushpins from SQL not showing in Firefox & Chrome but do in IE

I'm displaying a Bing Map (v7) in my Webmatrix2 website with a series of pushpins & infoboxes drawn from a SQL Express database using a JSON enquiry.
While the maps appears in all 3 browsers I'm testing (IE, FF & Chrome) the pushpins are sometimes not showing in FF & Chrome, particularly if I refresh with Cntrl+F5
This is my first JSON and Bing Maps app so expect there's a few mistakes.
Any suggestions on how to improve the code and get display consistency?
#{
Layout = "~/_MapLayout.cshtml";
}
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<link rel="StyleSheet" href="infoboxStyles.css" type="text/css">
<script type="text/javascript">
var map = null;
var pinLayer, pinInfobox;
var mouseover;
var pushpinFrameHTML = '<div class="infobox"><a class="infobox_close" href="javascript:closeInfobox()"><img src="/Images/close2.jpg" /></a><div class="infobox_content">{content}</div></div><div class="infobox_pointer"><img src="images/pointer_shadow.png"></div>';
var pinLayer = new Microsoft.Maps.EntityCollection();
var infoboxLayer = new Microsoft.Maps.EntityCollection();
function getMap() {
map = new Microsoft.Maps.Map(document.getElementById('map'), {
credentials: "my-key",
zoom: 4,
center: new Microsoft.Maps.Location(-25, 135),
mapTypeId: Microsoft.Maps.MapTypeId.road
});
pinInfobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0, 0), { visible: false });
AddData();
}
$(function AddData() {
$.getJSON('/ListSchools', function (data) {
var schools = data;
$.each(schools, function (index, school) {
for (var i = 0; i < schools.length; i++) {
var pinLocation = new Microsoft.Maps.Location(school.SchoolLat, school.SchoolLon);
var NewPin = new Microsoft.Maps.Pushpin(pinLocation);
NewPin.title = school.SchoolName;
NewPin.description = "-- Learn More --";
pinLayer.push(NewPin); //add pushpin to pinLayer
Microsoft.Maps.Events.addHandler(NewPin, 'mouseover', displayInfobox);
}
});
infoboxLayer.push(pinInfobox);
map.entities.push(pinLayer);
map.entities.push(infoboxLayer);
});
})
function displayInfobox(e) {
if (e.targetType == "pushpin") {
var pin = e.target;
var html = "<span class='infobox_title'>" + pin.title + "</span><br/>" + pin.description;
pinInfobox.setOptions({
visible: true,
offset: new Microsoft.Maps.Point(-33, 20),
htmlContent: pushpinFrameHTML.replace('{content}', html)
});
//set location of infobox
pinInfobox.setLocation(pin.getLocation());
}
}
function closeInfobox() {
pinInfobox.setOptions({ visible: false });
}
function getCurrentLocation() {
var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);
geoLocationProvider.getCurrentPosition();
}
</script>
<body onload="getMap();">
<div id="map" style="position:relative; width:800px; height:600px;"></div>
<div>
<input type="button" value="Find Nearest Schools" onclick="getCurrentLocation();" />
</div>
</body>
The JSON file is simply
#{
var db = Database.Open("StarterSite");
var sql = #"SELECT * FROM Schools WHERE SchoolLon != ' ' AND SchoolLon != 'null' ";
var data = db.Query(sql);
Json.Write(data, Response.Output);
}
Add your pinLayer, infobox, and infoboxLayer before calling the AddData function and see if that makes a difference. Also verify that school.SchoolLat and school.SchoolLon are numbers and not a string version of a number. If they are a string, then use parseFloat to turn them into a number. Other than that everything looks fine.

Getting storageVolume to work in JavaScript

In his blog post, Christian Cantrell shows how to use STORAGE_VOLUME_MOUNT in ActionScript.
He has written a Flex app called FileTile.
I would like to see a JavaScript alert box that says “You have inserted “ + e.storageVolume.name, and “You have removed a storage volume”.
<html>
<head>
<title>New Adobe AIR Project</title>
<script type="text/javascript" src="lib/air/AIRAliases.js"></script>
<script type="text/javascript" src="lib/air/AIRIntrospector.js"></script>
<script type="text/javascript" src="lib/jQuery/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
var msg = '<h1>Please insert your SwatchDog (SD) card.</h1>';
function trace() {
var message = 'Hello Max';
air.Introspector.Console.log(message);
}
function readFile(v) {
var myFile = air.File.desktopDirectory.resolvePath("MyFile.txt");
var fileStream = new air.FileStream();
fileStream.open(myFile, air.FileMode.READ);
$('#app').append('<p>' + fileStream.readUTFBytes(fileStream.bytesAvailable) + '</p>');
fileStream.close();
}
function onVolumeMount(e) {
$('#app').html('<h1>Thank you</h1><p>I can see you have multiple devices:</p>');
var volumes = air.StorageVolumeInfo.storageVolumeInfo.getStorageVolumes();
for (var i = 0; i < volumes.length; i++) {
$('#app').append(volumes[i].rootDirectory.nativePath);
}
if (e.storageVolume.isRemovable) {
if (e.storageVolume.name == 'SWATCHDOG') {
$('#app').append('<p>And SwatchDog is drive: ' + e.storageVolume.rootDirectory.nativePath + '</p>');
readFile(e.storageVolume)
} else {
$('#app').append('<p>But the one you just plugged in is not SwatchDog.</p>');
}
}
}
function onVolumeUnmount(e) {
$('#app').html('<h1>Goodbye!</h1>' + msg);
}
jQuery(function($){
var PluggedIn = false;
var volumes = air.StorageVolumeInfo.storageVolumeInfo.getStorageVolumes();
for (var i = 0; i < volumes.length; i++) {
if (volumes[i].isRemovable) {
PluggedIn = true;
if (volumes[i].name == 'SWATCHDOG') {
$('#app').append('I see you already have SwatchDog plugged in!');
readFile(volumes[i])
} else {
$('#app').append('What you have plugged in is not SwatchDog.');
}
}
}
if (!PluggedIn){
$('#app').append(msg);
}
air.StorageVolumeInfo.storageVolumeInfo.addEventListener(air.StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNT, onVolumeMount);
air.StorageVolumeInfo.storageVolumeInfo.addEventListener(air.StorageVolumeChangeEvent.STORAGE_VOLUME_UNMOUNT, onVolumeUnmount);
})
</script>
</head>
<body>
<div id="app">
</div>
<button onclick="trace();">Say Hello Max!</button>
</body>
</html>