PhoneGap - contacts plugin - images location - javascript

I have an issue I cannot find a solution for despite scouring the internet for obvious clues.
I have a very basic PhoneGap app that uses the contacts plugin.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// get all contacts
var options = new ContactFindOptions();
options.filter = "";
options.multiple = true;
var filter = ["name", "phoneNumbers", "photos"];
navigator.contacts.find(filter, onContactSuccess, onError, options);
}
function onContactSuccess(contacts) {
var element = document.getElementById('contacts');
for (var i = 0; i < contacts.length; i++) {
// the following check is incomplete for brevity
if (contacts[i].photos) {
// this produces a valid file location
element.innerHTML += contacts[i].photo[0].value;
// this renders an image not found square
element.innerHTML += "<img src='" + contacts[i].photo[0].value + "'>";
}
}
}
The problem that eludes me is the insertion of the image. PhoneGap serve produces the following error
[phonegap] 404
/var/mobile/Containers/Data/Application/C7B8E714-47EE-42AD-9C58-6B86EE068110/tmp/photo_cXxyI
and yet using iExplore I can see the photo_cXxyI in the /tmp folder.
I'm following the post from Raymond Camden that has a demo of the contacts plugin but my version refuses to show the images.
I'm running the app on the iOS PhoneGap app and there is data being returned (first, last, phone numbers, images array).
Any ideas on where I'm going wrong? I did also notice that the temp image files accumulate in the /tmp folder. They don't ever seem to be deleted. Is this a clue or an 'undocumented' feature?

Related

How can I load multiple versions of the same video on a page after page load via javascript without downloading multiple versions of the video file?

I'm trying to load multiple versions of the same video on a page. The script runs after page load, but I have to loop through the sources to check if they have been added to the DOM already (otherwise they download the same file multiple times). If that source already exists, the other duplicates of the video must wait until the first version is downloaded, via an eventListener, before loading the duplicate source and using that cached version of the first video to populate the duplicates (so that they don't download multiple times).
It seems to work fine when I test it in the Chrome network tab, the sources are only downloaded once, but when I look at the Lighthouse diagnostics it is telling me that the js execution time needs to be reduced. Is this because of the looping?
I also keep running into the issue of PageSpeed Insights giving me the message: "Oops! Something went wrong. PageSpeed Insights encountered a problem collecting the lab data."
What am I doing wrong here?
var i = 1,
sourceID,
arraySRC = [];
document.querySelectorAll("video source").forEach(function(source, sourceIndex) {
if (source.hasAttribute("data-small-src") && source.getAttribute("data-small-src") != "") {
source.id = "vidsource-" + i;
sourceID = "vidsource-" + i;
var src = source.getAttribute("data-small-src"),
sourceLoading = false,
firstMatchID;
// loop through array to see if source value already exists
arraySRC.forEach(function(itemSRC, arrayIndex) {
// if source value already exists in array
if (itemSRC.split(",")[1] == src) {
sourceLoading = true;
firstMatchID = itemSRC.split(",")[0]
return
}
});
if (sourceLoading == false) {
const node = document.createElement("source");
source.parentElement.appendChild(node);
node.setAttribute("src", src);
} else {
document.querySelector("#" + firstMatchID).addEventListener('loadeddata', function() {
const node = document.createElement("source");
source.parentElement.appendChild(node);
node.setAttribute("src", src);
}, false);
}
// add source to array
arraySRC.push(sourceID + "," + src);
i = i + 1;
}
});
(I have left out the load event for the script since I am using a Barba.js hook)

Titanium DocumentViewer not showing document

My appcelerator alloy app has a section that displays a list of protocols used by employees in a listview(There are about 25), when a row is tapped, it should open the corresponding PDF document in the assets/protocol_pdf folder. In iOS 11.2.1, the document viewer opens, but the PDF is not displayed, only the filename followed by PDF document(see image). Everything works just fine in iOS 10 and prior.
I used the code example from http://www.appcelerator.com/blog/2015/08/appcelerator-pdf-viewer-demo/ to open the PDF.
Additionally, using the exact code from the appcelerator documentation(http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.iOS.DocumentViewer) in a new test project results in the same problem.
At this point i'm not sure how to solve the issue. I can only guess that something in where the file is saved and how it is accessed is different. Any suggestions are appreciated.
My Code:
function onItemClick(e){
var item = $.listView.sections[e.sectionIndex].items[e.itemIndex];
Ti.API.info('Opening ' + item.properties.file);
if(OS_IOS){
openResourcePDF(item.properties.file);
} else{
Alloy.Globals.Navigator.open("androidPDF", {file: item.properties.file});
}
}
function openResourcePDF(fileName){
var appFile;
appFile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, fileName);
var appfilepath = appFile.nativePath;
viewPDF(appfilepath);
}
function viewPDF(appfilepath){
docViewer = Ti.UI.iOS.createDocumentViewer({url:appfilepath});
docViewer.show();
}
Image showing how viewer brings it up:
I guess you just want to use that on iOS. Try this:
function openResourcePDF(fileName) {
var appFile;
appFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, fileName);
var appfilepath = appFile.nativePath;
viewFile(appfilepath);
}

HTML Img's failing to load

Just for fun, i'm trying to implement a "15 puzzle", but with 16 images (from 1 music photo) instead.
The thing is split into 2 scripts / sides. 1 Python CGI script that will perform the Last.FM query + splitting the image in Y x Z chunks. When the python script finishes it outputs a JSON string that contains the location (on server), extension etc.
{"succes": true, "content": {"nrofpieces": 16, "size": {"width": 1096, "height": 961}, "directoryname": "Mako", "extension": "jpeg"}}
On the other side is a HTML, JS, (CSS) combo that will query the CGI script for the images.
$(document).ready(function () {
var artiest = $("#artiest")
var rijen = $("#rijen")
var kolommen = $("#kolommen")
var speelveld = $("#speelveld")
var search = $("#search")
$("#buttonClick").click(function () {
var artiestZ = artiest.val()
var rijenZ = rijen.val()
var kolommenZ = kolommen.val()
$.getJSON("http://localhost:8000/cgi-bin/cgiScript.py", "artiest=" + artiestZ + "&rijen=" + rijenZ + "&kolommen=" + kolommenZ, function (JsonSring) {
console.log("HIIIIII")
if (JsonSring.succes === true){
console.log(JsonSring)
var baseUrl = "http://localhost:8000/"
var extension = JsonSring.content.extension
var url = baseUrl + JsonSring.content.directoryname + "/"
var amountX = rijenZ
var amountY = kolommenZ
for (var i = 0; i < amountX; i += 1){
for (var p = 0; p < amountY; p += 1){
console.log("HI")
var doc = new Image
doc.setAttribute("src", url + JsonSring.content.directoryname + i + "_" + p + "." +extension)
document.getElementById("speelveld").appendChild(doc)
}
}
}else {
// Search failed. Deal with it.
}
})
})
})
where the various id's link to various HTML elements. (Text Fields & Buttons & Div's).
Beneath is a screenshot of the full folder that contains the image files.
Now, coming to the point. All the HTML img tags with src seem correct, yet. Some images don't load, yet other do. I also noticed that all images failed to load in 2s intervals. Is there some kind of timeout, or so?
All this is being ran from a local machine, so disk speed and cpu shouldn't really affect the matter. Also, from what I understand: The call for making the img tags etc is done in a callback from the getJson, meaning it'll only run when getJson has finished / had a reply.
Does the great StackOverFlow community have an idea what's happening here?
To share my knowledge/experiences with the great StackOverflow community,
Small backstory
After progressing a bit further into the project I started to run into various issues going from JSON parsing to not having Allow-Control-Allow-Origin: * headers, making it very hard to get the Ajax Request (Client ==> Python CGI) done.
In the meantime I also started dev'ing on my main desktop (which for some reason either has massive issues with Python versioning or has none). But due to the terminal on my desktop having Python 3.4+ , there was no module CGIHTTPServer. After a small amount of digging, I found that CGIHTTPServer had been transfered into http.server, yet when running plain old python -m http.server, I noticed the CGI script wouldn't run. It would just display. Ofcourse, I forgot the option -cgi.
Main solution
The times I was succesfully using CGIHTTPServer, I had troubles. The images wouldn't load as described above. I suspect that the module just couldn't take the decent amount of requests. Meaning that when suddenly Y x Z requests came in, it would struggle to deliver all the data. ==> Connection Refused.
Since switching to python -m http.server -cgi, no problems what so ever. Currently working on a Bootstrap Grid for all those images!
Thx #Lashane and #Ruud.

Search Increasing URL For Text

For stekhn, here's the proper link: var location = "http://www.roblox.com/Trade/inventoryhandler.ashx?filter=0&userid=" + i + "&page=1&itemsPerPage=14";
I'm trying to create a Javascript script where I can search through a users inventory, detect if they have what I'm looking for in their inventory and output the userID if they have it.
If I type in bluesteel, I need a Javascript script which will search through http://snackyrite.com/site.ashx?userid=1 and detect if it has the text 'bluesteel' is on it - if it is, I need it to display the user id, which is 1.
You may be thinking that's easy and I can easily find the script for that - well there's a catch, my objective isn't only to get it to search userid=1, I need it to search from userid=1 up to userid=45356
If the word 'bluesteel' is found on userid=5, userid=3054 and userid=12 (these are just examples), I need it to display 5, 3054 and 12 (the ID's) on the same page where the script was ran from.
This is the script I've tried, but the userid won't increase (I'm not sure how to do that).
var location = http://snackyrite.com/site.ashx?userid=1;
if(location.indexOf("bluesteel") > -1) {
output.userid
}
I do apologize, Javascript isn't my best.
Use a loop:
for (var i = 1; i <=45356; i++) {
var loc = "http://snackyrite.com/site.ashx?userid="+i;
// get contents of location
if (contents.indexOf("bluesteel") > -1) {
console.log(i);
}
}
Since getting the contents will presumably use AJAX, the if will probably be in the callback function. See Javascript infamous Loop issue? for how to write the loop so that i will be preserved in the callback function.
This kind of web scraping can't be done in the Browser (client-side JavaScript).
I would suggest building a scraper with Node.js.
Install Node.js
Install request npm i request
Install cheerio npm i cheerio
Create a file scraper.js
Run node scraper.js
Code for scraper.js
// Import the scraping libraries
var request = require("request");
var cheerio = require("cheerio");
// Array for the user IDs which match the query
var matches = [];
// Do this for all possible users
for (var i = 1; i <= 45356; i++) {
var location = "http://snackyrite.com/site.ashx?userid="+i;
request(location, function (error, response, body) {
if (!error) {
// Load the website content
var $ = cheerio.load(body);
var bodyText = $("body").text();
// Search the website content for bluesteel
if (bodyText.indexOf("bluesteel") > -1) {
console.log("Found bluesteel in inventory of user ", i);
// Save the user ID, if bluesteel was found
matches.push(i);
}
// Something goes wrong
} else {
console.log(error.message);
}
});
console.log("All users with bluesteel in inventory: ", matches);
}
The above code seems kind of complicated, but I think this is the way it should be done. Of corse you can use any other scraping tool, library.

trouble with IE, YUI, and Flash

Ok, so this is my first post so I'll try not to sound to noobish here.....
I am working on a project on my corporate site and am having issues with some video. I am grabbing some video through an AJAX call and placing it into a YUI panel to create my own video lightbox. Everything is working fine in all browsers except, of course, IE(8 specifically since we just gave up supporting 7). I can get the panel to open and display the flash player but it won't load the .flv or the player controls. Like I said, fine in all other browsers. Here is the main script I am working with:
/**
* Function to lazy load, then show the video panel with the content of the link passed in inside the panel
*/
var showVideoPanel = function(e, linkEl){
Event.preventDefault(e);
if(!YAHOO.env.getVersion("videoPanel")) {
var successHandler = function() {
videoPanel = new COUNTRY.widget.VideoPanel("videoPanel", " ");
showVideoPanel(e, linkEl);
};
//this is not likely to go off (404 is not considered an error)
var failureHandler = function() {
window.location = linkEl.href;
return;
};
COUNTRY.loadComponent("videoPanel", successHandler, failureHandler);
}
else {
COUNTRY.util.Ajax.getRemoteContent('GET', linkEl.href, videoPanel.body, {
success: function(o){
var start, end, el;
el = Dom.get(videoPanel.body);
start = o.responseText.indexOf('<object');
end = o.responseText.indexOf('</object>', start);
el.innerHTML = o.responseText.substring(start, end);
},
failure: function(o){
el = Dom.get(videoPanel.body);
el.innerHTML = "The requested content is currently unavailable. Please try again later.";
}
});
var bod = Dom.get(videoPanel.body);
COUNTRY.util.Flash.flashControl(bod.getElementsByTagName("FORM")[0]);
videoPanel.show(linkEl);
}
};
This part of the code looks like it probably doesn't do what you intended:
start = o.responseText.indexOf('<object');
end = o.responseText.indexOf('</object>', start);
el.innerHTML = o.responseText.substring(start, end);
This code will include the tag, but not include the tag. I suspect you're trying to either get both tags or neither tag.
I solved this originally by dumping the the data from the AJAX call into an object tag, which solved the problem and worked cross browser perfectly.
We have since changed how we serve media, so I ended up using Vimeo to host the videos which was very simple and works wonderfully.

Categories