In some SO Questions and Answer I get to know that, with the following way one can upload files via spread Sheet to Google Drive. In that point, Is there a similar way that can be done in android ? I have searched but no luck. Lately I had used Drive Api, but I cannot overcome the consent screen problem, though I have tried several times. So, I want something with the following way. Is there any android way of the following procedure?
Code.gs:
var dropBoxId = "012345679abcdefg"; // Drive ID of 'dropbox' folder
var logSheetId = "abcdefghijklmnopqrstu123"; // Drive ID of log spreadsheet
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('InputForm.html');
}
function uploadFiles(formObject) {
try {
// Create a file in Drive from the one provided in the form
var folder = DriveApp.getFolderById(dropBoxId);
var blob = formObject.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + formObject.myName);
// Open the log and record the new file name, URL and name from form
var ss = SpreadsheetApp.openById(logSheetId);
var sheet = ss.getSheets()[0];
sheet.appendRow([file.getName(), file.getUrl(), formObject.myName]);
// Return the new file Drive URL so it can be put in the web app output
return file.getUrl();
} catch (error) {
return error.toString();
}
}
InputForm.html:
<form id="myForm">
<input type="text" name="myName" placeholder="Your full name..."/>
<input name="myFile" type="file" />
<input type="button" value="Submit"
onclick="google.script.run
.withSuccessHandler(updateUrl)
.withFailureHandler(onFailure)
.uploadFiles(this.parentNode)" />
</form>
<div id="output"></div>
<script>
function updateUrl(url) {
var div = document.getElementById('output');
div.innerHTML = 'Got it!';
}
function onFailure(error) {
alert(error.message);
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
Related
I've built a mobile app based on Cordova, for both iOS and Android, i need to make secure communication between app and server. Request to server, in javascript, are like this:
request.open("GET", 'http://url/service?firstElement='+elem+'&secondElement='+elem2, false);
I've tried to use RSA encryption generating public and private key locally using pidCrypt libraries, the 2048bits key requires too long time to be generates, so i've used 512bits.
The server is not be able to decrypt the message.
I'm looking for a better solution.
Try Using Send Ajax Request, Like This. I assume that you use php for Dynamic code (Server Side).
Here is Sample of HTML file which presant on your cordova, phonegap directory.
<form method = "post" action = "#!">
<div class="col-md-4">
<span class="help-block">Name</span><input type="text" name="username" class="form-control" />
</div>
<br>
<div class="col-md-4">
<span class="help-block">Password</span><input type="text" name="password" class="form-control" />
</div>
<input type = "submit" value = "Save" class = "btn btn-success right" onClick="UpdateRecord();"/>
</form>
<script>
function UpdateRecord()
{
var name = $("[name='username']").val();
var host = $("[name='password']").val();
jQuery.ajax({
type: "POST",
url: "php/login.php",
/* Or */
/*url: "https://www.yoursite.com/page",*/
data: "username="+ username+"& password="+ password,
dataType: "html",
cache: false,
success: function(response){
if(response == 'true') {
$.session.set("myVar", username);
window.location.href='profile.html';
}
else {
$("#errorMessage").html("Invalid Entry, Please Try Again");
}
}
});
}
</script>
And PHP File for Handle Query.
Please Not that code is not tested and it may change as per your need. You can perform any encryption method and use any function here.
<?php
include 'config.php';
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if(!empty($username) && !empty($password))
{
//$result = mysql_query("SELECT * FROM ".$db.".users WHERE username='$username' and password ='$password'");
$result=mysql_query("select * from ".$db.".users WHERE email = '$username' ");
while($data = mysql_fetch_row($result))
{
$original_password = $data[3];
$salt = $data[4];
$hashedPass = sha1($salt.$password);
$fullusername = $data[16]." ".$data[17]; // Used Only for create full name session
if ($original_password == $hashedPass)
{
$_SESSION['username'] = $fullusername;
$_SESSION['useremail'] = $username;
$_SESSION['UserID'] = $data[0];
echo 'true';
}
}
}
?>
Edit
request.open("GET", 'http://url/service?firstElement='+elem+'&secondElement='+elem2, false);
Avoid to use GET method while sending sensitive data.
Edit, Helpful Link
Local storage protection in phonegap application
I have created a youtube channel and uploaded few videos there. Channel is public, now i want to display those all uploaded videos in my android app through channel URL which is: https://www.youtube.com/channel/UCjD0Dhs3o7UiUQdZpSBADAA
I have also done some research but i am getting tutorial to display videos by hardcoded ids not from channel for example: https://github.com/youtube/yt-android-player
Any one guide me is it possible? i would really appreciate your help in matter.
Thank You!
It is working fine for me. You can refer this answer for showing youtube channel videos into the website:
$(document).ready(function () {
youtubeApiCall();
$("#pageTokenNext").on("click", function (event) {
event.stopImmediatePropagation();
$("#pageToken").val($("#pageTokenNext").val());
youtubeApiCall();
});
$("#pageTokenPrev").on("click", function (event) {
event.stopImmediatePropagation();
$("#pageToken").val($("#pageTokenPrev").val());
youtubeApiCall();
});
});
// Get Uploads Playlist
function youtubeApiCall() {
$.get(
"https://www.googleapis.com/youtube/v3/channels", {
part: 'contentDetails',
forUsername: 'bharatpillai007',
//id: {YOUTUBE CHANNEL ID}, //or you can call forUsername: {USER NAME} parameter of the your youtube channel
key: 'AIzaSyCKCyYrVLEKR7VR4BFlrC5AhhzYQGRIet4'
}, function (data) {
$.each(data.items, function (i, item) {
pid = item.contentDetails.relatedPlaylists.uploads;
getVids(pid);
});
}
);
}
//Get Videos
function getVids(pid) {
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", {
part: 'snippet',
maxResults: 10, // Defualt 5. You can set 1 to 50
playlistId: pid,
key: 'AIzaSyCKCyYrVLEKR7VR4BFlrC5AhhzYQGRIet4',
pageToken: $("#pageToken").val()
}, function (data) {
var results;
$.each(data.items, function (i, item) {
if (typeof data.prevPageToken === "undefined") {
$("#pageTokenPrev").hide();
} else {
$("#pageTokenPrev").show();
}
if (typeof data.nextPageToken === "undefined") {
$("#pageTokenNext").hide();
} else {
$("#pageTokenNext").show();
}
$("#pageTokenNext").val(data.nextPageToken);
$("#pageTokenPrev").val(data.prevPageToken);
results = '<li>' + item.snippet.title + '</li>';
$('#results').append(results);
});
}
);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row-fluid">
<ul id="results"></ul>
<input type="hidden" id="pageToken" value="" />
<div class="btn-group" role="group" aria-label="...">
<button type="button" id="pageTokenPrev" value="" class="btn btn-default">Prev</button>
<button type="button" id="pageTokenNext" value="" class="btn btn-default">Next</button>
</div>
</div>
After reading different Youtube apis i found following steps to consume Youtube Channel Videos in your Android app.
1) Create an application in your Google Account
2) Enable youtube services
3) and then you will get developer key
use that developer key to make api calls.
4)
String url = "https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UCjD0Dhs3o7UiUQdZpSBADAA&key=" + DeveloperKey.DEVELOPER_KEY;
Use cannel id in above URL along with developer key to get list of videos under your channel.
5) You will get basic information of each video but still you cannot play that video in your android video player in order to do that you must have RTSP url
and that url you can obtain by passing video id to http://gdata.youtube.com/feeds/mobile/videos/1FJHYqE0RDg
That's all.
I'm having 2 strange problems with the code I'm using to pull in some data to use in a listview. Here is my javascript:
function getOrders(status, url) {
$(function () {
//check if url from pagination
if (!url) {
url = api_url + '/orders/?callback=?&status=' + status;
} else {
url = root_url + url + '&callback=?';
}
$.mobile.loading('show');
$.getJSON(url, null, function (d) {
//declare a variable with which to build our output (it's best to buffer output and only do one append at the end since DOM manipulation is CPU expensive)
var output = '';
//iterate through the data (we could also get rid of the jQuery here by using `for (key in data) {
$.each(d.objects, function (index, value) {
output += '<li><a id="' + value.reference + '" href="view_order.html" class="view_order"><h3>' + value.reference + ' - ' + value.client.company + '</h3><p>' + value.order_date + ' ' + value.user.username + '</p></a></li>';
});
$('#orders_list').html(output).listview('refresh');
//if paginated, update next button
if (d.meta.next) {
$("#id_ordersNext").attr('href', d.meta.next);
$("#id_ordersNext").show();
} else {
$("#id_ordersNext").hide();
}
if (d.meta.previous) {
$("#id_ordersPrevious").attr('href', d.meta.previous);
$("#id_ordersPrevious").show();
} else {
$("#id_ordersPrevious").hide();
}
$("#id_ordersTotal").html(d.meta.total_count);
$.mobile.loading('hide');
});
});
}
$(function () {
//bind the nav
$(".order_nav").die();
$(".order_nav").live('click', function () {
$(".order_nav").each(function () {
$(this).removeClass('ui-btn-active');
});
$(this).addClass('ui-btn-active');
getOrders($(this).attr('href'));
return false;
});
//bind the view order
$(".view_order").die();
$(".view_order").live('click', function () {
//save var
window.viewOrderReference = $(this).attr('id');
$.mobile.changePage("view_order.html");
});
$("#id_ordersNext,#id_ordersPrevious").die();
$("#id_ordersNext,#id_ordersPrevious").live('click', function () {
getOrders(null, $(this).attr('href'));
return false;
});
//default view
getOrders('Order Placed');
});
Here is the html I'm using for the page that's being loaded via JQMobile:
<div data-role="page" data-needs-auth='true'>
<script src="js/list_orders.js"></script>
<div class="headerDiv" data-role='header' data-theme='b'>Home
<h1>Jubilee Distributors</h1>
Login</div>
<div data-role='navbar'>
<ul>
<li>Placed</li>
<li>Picked</li>
<li>Delivered</li>
</ul>
</div>
<div data-role="content">
<ul data-role='listview' id="orders_list" data-filter="true"><li>No records found</li></ul>
<p>Previous <span id='id_ordersTotal' class='record-count'></span> records found Previous
</p>
</div>
<div id='footerDiv' data-role="footer"></div>
</div>
This all works fine in any browser on a desktop, but when I run it on an Android device 2 things happen, or rather don't.
The last line in the $(function() - getOrders('Order Placed'), doesn't seem to execute, or if it does, it's not updating the list with the returned result. If I click the first link with the "Orders Placed" it works no probs.
The addClass is not actually adding the class.
Like I said, this all works fine in any desktop browser, but not on the Android device.
Any ideas?
EDIT: Fixed the second problem, however the first problem still exists.. It works if I navigate to the page, then away from it, then back again tho.
Fixed this error by changing the dom ready function to pageinit.
I am turning a HTML app into a .apk using https://build.phonegap.com and everything works great appart from my file selector.
<input name="file" type="file" id="file">
I want to be able to select images only (it doesnt matter if it can select more - but its the images I am looking for) from both camera and file system..
In the web version http://carbonyzed.co.uk/websites/assent/1/photos.html this works great from my phone, but when converted to .apk, this functionality is lost, and I can't seem to find anything on here, or online relating to this issue.
At least for me, the input file doesn't work in Phonegap.
You need use the Phonegap API to get picture and select the source where come from, like photolibrary, camera or savedphotoalbum.
See more info about camera.getPicture: http://docs.phonegap.com/en/2.1.0/cordova_camera_camera.md.html#camera.getPicture
and about Camera.PictureSourceType parameter of cameraOptions method: http://docs.phonegap.com/en/2.1.0/cordova_camera_camera.md.html#cameraOptions
Ended up using the Child Browser system like so
In the head
<script src="childbrowser.js"></script>
in the body
<button class="button-big" onClick="window.plugins.childBrowser.showWebPage('URL_TO_GO_HERE',
{ showAddress: false });" style="width: 100%;">UPLOAD PHOTOS</button>
which has a standard fileuploader like
<input name="file" type="file" id="file">
then it let me select from root storage, works in phonegap 2.2 onwards on both iOS and Android OS
To capture an image I used this in the head
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureImage() {
// Launch device camera application,
// allowing user to capture up to 2 images
navigator.device.capture.captureImage(captureSuccess, captureError, {limit: 2});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://my.domain.com/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
</script>
and this in the body
<input type="button" class="button-big" style="width: 100%;" onclick="captureImage();" value="TAKE PHOTO">
copy and past and it works a dream,
Check it out in this image
any questions, just email comment,
or email me... support#carbonyzed.co.uk
I am trying to create an offline video player that would download video content from my site for later viewing offline via an HTML5 video element. The code below works fine in Chrome for the desktop, but not on mobile (Nexus S smartphone, Nexus 7 tablet, 4.1 since only that runs chrome, which is required for the filesystem api). I am using the filesystem API that is supported by chrome on both the desktop and mobile.
I have confirmed it is correctly storing the file on the mobile device and I can retrieve the file correctly, but for some reason after retrieving the video from the localsystem chrome does not want to play the video. This is true whether I am using the html5 video element or whether I am navigating directly to the filesystem URL. When I use the html5 video element it returns the error media_err_not_supported. I have confirmed that the device can play the video if I navigate directly to it on my server (without first storing it using the filesystem api), so the issue is not a codec or video format problem. I am also using the video/mp4 mime type in both cases.
Again, this works on desktop, but not mobile. Any ideas?
Here is the code we are using:
<!DOCTYPE html >
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
var _fs;
var filename = "test3.mp4";
var diskSpaceRequired = 10 * 1024 * 1024;
$(document).ready(function () {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
function onInitFs(fs) {
_fs = fs;
getVideo(fs);
}
if (!!window.requestFileSystem) {
window.webkitStorageInfo.requestQuota(
window.webkitStorageInfo.PERSISTENT,
diskSpaceRequired, // amount of bytes you need
function () { },
function () {}
);
window.requestFileSystem(window.PERSISTENT, diskSpaceRequired, onInitFs, function () { alert('error'); });
} else {
alert('not supported');
}
$("#play").on('click', playVideo);
$("#ourVideo").on('error', function(e) { console.log('ERROR!!!', e, arguments);
console.log($("#ourVideo")[0].error);
});
});
function playVideo() {
_fs.root.getFile(filename, {}, function (fileEntry) {
$("#ourVideo").attr('src', fileEntry.toURL());
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (e) {
$("#ourVideo").get(0).play();
};
reader.readAsText(file);
}, errorHandler);
}, errorHandler);
}
function getVideo(fs) {
fs.root.getFile(filename, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fetchResource(fileWriter);
}, errorHandler);
}, errorHandler);
}
function errorHandler(e) {
console.log('error', e);
}
function fetchResource(fileWriter) {
console.log('fetchresource');
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.open("GET", "http://mydomain.com/trailer.mp4", true);
xhr.onload = function(e) {
if (this.status == 200) {
var bb = new WebKitBlobBuilder();
bb.append(this.response);
var blob = bb.getBlob("video\/mp4");
fileWriter.write(blob);
} else {
console.log(this.status);
}
};
xhr.send();
}
</script>
<title>foo</title>
</head>
<body>
<input type="button" value="Play Video" id="play"/>
<video id="ourVideo" controls="">
<source id="vidSource" type="video/mp4"/>
</video>
</body>
</html>
The problem looks like your android chrome coudn't access the android file system correctly, For that you can use nanoHttpd server for access android local files in device or sdcard.
for NanoHttpd server use this one class in your application and pass the media file location as http://localhost:8081/sdcard/(your_media_location).mp4
or get nanoHttpd from https://gist.github.com/1893396
I think this is more accurate to access sdcard files than directly calling for them
try change html part to
</head>
<body>
<input type="button" value="Play Video" id="play"/>
<video id="ourVideo" controls="">
<source src="video1.mp4" type= "video/mp4">
<source src="video1.ogv" type= "video/ogg">
</video>
</body>
you can convert your mp4 to ogv using
http://video.online-convert.com/convert-to-ogg
and put ogv file in the same location in mp4
**for more information check out these
http://www.broken-links.com/2010/07/08/making-html5-video-work-on-android-phones/
HTML5 <video> element on Android does not play