How do I add user input in Plivo's SMS API? - java

I am using Plivo's SMS API to send SMS messages. Is it possible to have an user input prompt for “SENDERS NAME”, “RECEIVER NAME” and “MESSAGE” in Plivo’s SMS API without having them to be hardcoded before I run the .js file?
var plivo = require('plivo');
(function main() {
'use strict';
var client = new plivo.Client("<MY API KEY>", "<MY API TOKEN>");
client.messages.create(
"+1<SENDER NUMBER>", // Sender's phone number with country code
"+1<RECEIVER NUMBER>", // Receiver's phone Number with country code
"<MESSAGE>", // Message
{
method: "GET", // Method used to trigger message URL.
url: "http://example.com/sms_status/" // The URL to which with the status of the message is sent
},
).then(function(response) {
console.log(response);
}, );
})();

Plivo's Developer Evangelist here. It depends upon your use case. Ideally not hardcoding values means storing values at some place like a Google Sheet, or having a front end to accept values from a user or a database. I suggest to the easiest way at this point is to prompt users right after running your js script.
const prompt = require('prompt-sync')();
var plivo = require('plivo');
const from = prompt('Please enter source number?');
const to = prompt('Please enter destination number?');
const text = prompt('Please enter the text you would like to send?');
console.log(`User input details are, From: ${from}, To:${to}, Text: ${text}`);
var client = new plivo.Client("auth_id", "auth_token");
client.messages.create({
src: from,
dst: to,
text: text,
}).then(function(response) {
console.log(response);
});
If you'd like to use a front end to prompt the user you can try this project.
If you'd like to store values using a Google Sheet and trigger an SMS whenever a row is updated you can use an automation tool like Zapier.

Related

how to read data from a web UI and share using NFC card

I am new to NFC ,what we want is that we have a web page where we have all user details like Name, Email, Facebook URL, Linked in URL and is stored in a database. Now my question is is it possible that an NFC card or any app can read that data and share using the NFC card.
Please bear with my question and may be wrong .
Web NFC allows you to read and write NFC tags on Chrome for Android.
To write a simple text record, pass a string to the NDEFReader write() method.
const ndef = new NDEFReader();
await ndef.write("Hello World");
Scannibg nearby NFC tags is pretty easy as well:
const ndef = new NDEFReader();
await ndef.scan();
ndef.addEventListener("reading", ({ message, serialNumber }) => {
console.log(`> Serial Number: ${serialNumber}`);
console.log(`> Records: (${message.records.length})`);
});
I'd recommend you read https://web.dev/nfc and play with https://googlechrome.github.io/samples/web-nfc/ to see if that's what you're looking for.
In your specific case, I'd store data in a JSON format and read them later:
const encoder = new TextEncoder();
const data = {
firstname: "François",
lastname: "Beaufort"
};
const jsonRecord = {
recordType: "mime",
mediaType: "application/json",
data: encoder.encode(JSON.stringify(data))
};
const ndef = new NDEFReader();
await ndef.write({ records: [jsonRecord] });
// Scan NFC tags and go trough |message.records|.
// Once you have a record, check its |mediaType| and read |data|.
if (record.mediaType === "application/json") {
const textDecoder = new TextDecoder();
console.log(`JSON: ${JSON.parse(decoder.decode(record.data))}`);
}

How to build a short Dynamic Link with a Desktop Fallback URL on Android?

I have implemented deep link in my Android App to share content. The problem is on Android I can't find a way to set a Fallback URL when the user open the short link on his desktop.
With the Firebase DynamicLink.Builder I can set iOS fallback URL because my app doesn't exist on iOS but I can't find a way to set the dfl parameters in my link.
Which lead the user to an error page like this :
Here how I build my short dynamic link:
//link example : https://app.example.com/details/ebLvAV9fi9S7Pab0qR3a
String link = domainUri + "/details/" + object.getUid();
FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLink(Uri.parse(link))
.setDomainUriPrefix(domainUri)
.setAndroidParameters(new DynamicLink.AndroidParameters.Builder().setMinimumVersion(1).build())
// Fallback Url for iOS
.setIosParameters(new DynamicLink.IosParameters.Builder("").setFallbackUrl(Uri.parse(RMP_WEB_BASE_URL)).build())
.setSocialMetaTagParameters(
new DynamicLink.SocialMetaTagParameters.Builder()
.setTitle(title)
.setDescription(description)
.setImageUrl(Uri.parse(imageUrl))
.build())
.buildShortDynamicLink()
.addOnCompleteListener(new OnCompleteListener<ShortDynamicLink>() {
#Override
public void onComplete(#NonNull Task<ShortDynamicLink> task) {
if (task.isSuccessful() && task.getResult() != null) {
shortLink = task.getResult().getShortLink();
//Create Shareable Intent
//...
}
}
});
I have read that I need to specify a Desktop Fallback URL like the iOS one but DynamicLink.Builder doesn't seems to include one.
I would like to redirect my user to the home page https://example.com when they open the link from a non-android device.
I have tried to use setLongLink(longLink) in the DynamicLink.Builder with the parameters ?dfl=https://example.com but it doesn't seems to work and it even break my dynamic link on android.
This is a Swift solution but may be helpful to others-
Unfortunately, there is currently no built-in method to handle this programmatically through the Firebase url editor. You must manually add an 'ofl' parameter to the link. The easiest way to do this:
// Grab link from Firebase builder
guard var longDynamicLink = shareLink.url else { return }
// Parse URL to string
var urlStr = longDynamicLink.absoluteString
// Append the ofl fallback (ofl param specifies a device other than ios or android)
urlStr = urlStr + "&ofl=https://www.google.com/"
// Convert back to a URL
var urlFinal = URL(string: urlStr)!
// Shorten the url & check for errors
DynamicLinkComponents.shortenURL(urlFinal, options: nil, completion:{ [weak self] url,warnings,error in
if let _ = error{
return
}
if let warnings = warnings{
for warning in warnings{
print("Shorten URL warnings: ", warning)
}
}
guard let shortUrl = url else {return}
// prompt the user with UIActivityViewController
self?.showShareSheet(url: shortUrl)
})
The final URL can then be used to present the shareable panel with another function like:
self.showShareSheet(url: finalUrl) which triggers the UIActivityViewController
Credit to http://ostack.cn/?qa=168161/ for the original idea
More about ofl: https://firebase.google.com/docs/dynamic-links/create-manually?authuser=3#general-params

How to open a page dynamically in android when user clicks on pushNotification message sent through php

I have a PHP code for sending pushNotifications to registered mobiles. The notification includes fields of database like "Collection Title", "Community" and a "Collection handle (unique ID)". After the message is received on mobile, when the user clicks on that message, I want a webview of that particular collection handle in android app.
I have searched through various posts, however I am unable to get the desired code.
Any help in this regard would be highly appreciated.
Excerpts of "sendnotification.php" file
$sql1 = "SELECT community.name as inst, collection.name as coll,
handle.handle as handle FROM community2collection, collection2item, handle, community, collection WHERE community2collection.collection_id = collection2item.collection_id AND community.community_id = community2collection.community_id AND collection.collection_id = collection2item.collection_id AND collection2item.item_id = handle.resource_id
ORDER BY handle.handle_id desc limit 2";
$result1 = pg_exec($cnn, $sql1);
$numrows1 = pg_numrows($result1);
echo "numrows1=" . $numrows1;
for($ri = 0; $ri < $numrows1; $ri++) {
$row = pg_fetch_array($result1, $ri);
echo "row=" . $ri;
$pushMessage = $row[1]. " submitted by " .$row[0];
if(isset($gcmRegIds) && isset($pushMessage)) {
$message = array('message' => $pushMessage);
echo $pushMessage;
$pushStatus = sendPushNotification($gcmRegIds, $message);
echo $pushStatus;
echo "row2field=" .$row[2];
Here I want to create the URL dynamically for specific handle in the notification in android app i.e. based on field $row(2) in the code above. I am using GCM service for sending notifications.

Accessing Shoutcast Current Stream Information

i am creating an internet radio application for android. So far i have successfully streamed and played using the shoutcast url for various stations.This is my code :
String url = "http://185.33.22.13:7704";
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try
{
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
}
catch (IOException e)
{
e.printStackTrace();
}
mediaPlayer.start();
Next i would want to get the information of stream to be shown in my application.
I want to retrieve the information shown in green box:
People have posted about FFmpegMediaMetadataRetriever but github is way out of my league to understand also tried thier apk file which does nothing when given the above http link.Please suggest me a simple and robust solution to retrieve the data from SHOUTcast DNAS status.
Thanks in advance !
Shoutcast V1 has a special page with bitrate and other information.
If your shoutcast is running on
http://185.33.22.13:7704
then this page url will be:
http://185.33.22.13:7704/7.html
The body of that page looks like this:
<HTML><meta http-equiv="Pragma" content="no-cache"></head><body>214,1,312,1000,213,64,Ferry Tayle - The Way Back Home (Edit) (feat. Poppy)</body></html>
Split that text by commas and you will get:
Current listeners
Stream status
Peak listeners
Maximum number of listeners (from server start)
Unique listeners
Bitrate
Song title
Here is an example in javascript (Nodejs) that gets the data from 7.html page and parses it:
var request = require('request'),
options = {
url: 'http://185.33.22.21:7704/7.html',
headers: {
'User-Agent': 'Mozilla/5.0'
}
},
regex = /<body>(.*?)<\/body>/i;
request(options, function (error, response, body) {
var match = regex.exec(body),
data = match[1].split(',');
console.log("7.html: ", body);
console.log("Current listeners: ", data[0]);
console.log("Stream status: ", data[1]);
console.log("Peak listeners: ", data[2]);
console.log("Maximum number of listeners: ", data[3]);
console.log("Unique listeners: ", data[4]);
console.log("Bitrate: ", data[5]);
console.log("Metada: ", data[6]);
});
Please note that setting "User-Agent" header is required.
If you have admin password from that server - then another way is to get XML data directly from shoutcast admin page using the following URL:
http://185.33.22.13:7704/admin.cgi?mode=viewxml

passing parameter from javascript to servlet

I am retrieving all the contacts of a user from gmail and yahoo, I have added the checkbox, the user needs to select the desired email id to which he need to send email. I need to collect all user selected email id's and save them in a string send that string to another servlet where I am sending emails.
I was able to add the check box dynamically but I am not able to collect the emails and save them in a string. This is the code I have written to add check box before all the emails,
kindly help me to put those selected email id's in a string
I used the following code, but still I am not able to do it.You can have a look at the demo of this app http://ec2-50-16-183-101.compute-1.amazonaws.com/SocialAuthNew/
To get the contacts from Gmail type google in the text box and for yahoo type yahoo and click on submit button
List<Contact> contactsList = provider.getContactList();
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><script type='text/javascript'>");
out.println("function getAllContacts(size){ var selected_list='';");
out.println("for(var c=0;c<size;c++){if(document.getElementById('mailCheckbox'+c).checked==true){selected_list=selected_list+document.getElementById('lblmail'+c).innerHTML+':';}}");
out.println("document.getElementById('final_mailing_list').innerHTML=selected_list;}</script>");
out.println("<title></title>");
out.println("</head>");
out.println("<body>");
for(int i=0;i<contactsList.size();i++){
System.out.println(contactsList.get(i).getFirstName()+" : "+contactsList.get(i).getLastName()+":"+contactsList.get(i).getEmail());
out.println("<h1> Imported conatcts from your mail are:-</h1>");
out.println("<input type='checkbox' id='mailCheckBox"+i+"' name='mailCheckbox'></input>");
/* out.println(contactsList.get(i).getFirstName());
out.println(contactsList.get(i).getLastName());*/
out.println("<label id='lblmail"+i+"'>"+contactsList.get(i).getEmail()+"</label>");
}
int size=contactsList.size();
out.println("<input type='button' value='GetContact' onclick='getAllContacts("+size+");'/> ");
out.println("<div id='final_mailing_list'></div></body>");
out.println("</html>");
}
Try this:
1) Wrap your email in a DOM element to make it easier to access
out.println("<span>" + contactsList.get(i).getEmail() + "</span>");
2) Using something like e.g. JQuery for normalizing access to the DOM on the client, do
function getSelectedEmails() {
var emails = [];
$('body').find('input[name="mailCheckbox"]:checked').each(function() {
emails.push($(this).closest('span').text());
});
return emails;
}
This returns the emails in an array - which you can easily concatenate into a string if you want with e.g.
var emailString = emails.join(", ");
...although I think using an array is usually better (perhaps JSON encoded if you need to serialize it).
s using array is much easier. i have used array and gave the check box name as check1 and on the click of submit button i have called the following function. this function alerts the value of the selected check boxes and passes the action to servlet
<script>
function onCallForInterview()
{
var selectedIds;
var count=0;
for (i=0; i<document.frm.check1.length; i++)
{
if (document.frm.check1[i].checked==true)
{
if(count==0){
selectedIds=document.frm.check1[i].value;
count=count+1;
}
else
selectedIds=selectedIds+","+document.frm.check1[i].value;
}
}
alert(selectedIds);
document.frm.action="<%=contextPath%>/SearchCandInfo? action=selectcanforinterview&ids="+selectedIds;
document.frm.submit();
}
</script>
A slightly more primitive way to achieve this,
Create a bunch of Check-Box as you are doing now but with the difference that all of htem should have the same name i.e. do the following correction in your code
out.println("<input type='checkbox' id='mailCheckBox' name='mailCheckbox'></input>");
Now retrieve all the values of such text boxes on your server side using following call on request object,
String[] emailIds = request.getParameterValues("mailCheckBox");
Hope this helps.

Categories