Firebase Deep Link short URL - firebase

Can the links for Firebase deep links be shortened? Do they have that feature? Links generated are too long and that is not good.

UPDATE
Firebase now supports shorten dynamic links programmatically.
I've faced the same problem getting a long and not user friendly URL when creating a dynamic link programmatically.
The solution I've found is to use the Google URL Shortener API that works brilliant.
That link points to the Java library, I'm using it in Android, but you can do also a simple http request.
I'll post my Android code in case you need it:
private void createDynamicLink() {
// 1. Create the dynamic link as usual
String packageName = getApplicationContext().getPackageName();
String deepLink = "YOUR DEEPLINK";
Uri.Builder builder = new Uri.Builder()
.scheme("https")
.authority(YOUR_DL_DOMAIN)
.path("/")
.appendQueryParameter("link", deepLink)
.appendQueryParameter("apn", packageName);
final Uri uri = builder.build();
//2. Create a shorten URL from the dynamic link created.
Urlshortener.Builder builderShortener = new Urlshortener.Builder (AndroidHttp.newCompatibleTransport(), AndroidJsonFactory.getDefaultInstance(), null);
final Urlshortener urlshortener = builderShortener.build();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
Url url = new Url();
url.setLongUrl(uri.toString());
try {
Urlshortener.Url.Insert insert=urlshortener.url().insert(url);
insert.setKey("YOUR_API_KEY");
url = insert.execute();
Log.e("url.getId()", url.getId());
return url.getId();
} catch (IOException e) {
e.printStackTrace();
return uri.toString();
}
}
#Override
protected void onPostExecute(String dynamicLink) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getResources().getString(R.string.share_subject));
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, dynamicLink);
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_using)));
Log.e("dynamicLink", dynamicLink);
}
}.execute(null, null, null);
}
Hope it helps!!

The links can be shortened in the Firebase console in the Dynamic Links tab. Tap on 'New Dynamic Link', which gives you an option to create a short link from an existing link.

This can be done programmatically using the Firebase Dynamic Links REST API, for example:
POST https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=api_key
Content-Type: application/json
{
"longDynamicLink": "https://abc123.app.goo.gl/?link=https://example.com/&apn=com.example.android&ibi=com.example.ios"
}
See https://firebase.google.com/docs/dynamic-links/short-links
And I just had to code it for Android - here's the code in case it helps someone:
at the top of the activity:
lateinit private var dynamicLinkApi: FbDynamicLinkApi
private var remoteCallSub: Subscription? = null // in case activity is destroyed after remote call made
in onCreate (not really but to keep it simple, actually you should inject it):
val BASE_URL = "https://firebasedynamiclinks.googleapis.com/"
val retrofit = Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
dynamicLinkApi = retrofit.create(FbDynamicLinkApi::class.java)
then when it's time to shorten a URL:
remoteCallSub = dynamicLinkApi.shortenUrl(getString(R.string.fbWebApiKey), UrlRo(dynamicLink))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ url -> Log.d("Shortened: $url") },
{ e -> Log.e("APP","Error with dynamic link REST api", e) })
Don't forget to unsubscribe in onDestroy:
override fun onDestroy() {
super.onDestroy()
remoteCallSub?.unsubscribe()
}
And here's the classes you need for the dynamic API:
interface FbDynamicLinkApi {
#POST("v1/shortLinks")
fun shortenUrl(#Query("key") key: String, #Body urlRo: UrlRo): Observable<ShortUrlRo>
}
data class UrlRo(val longDynamicLink: String, val suffix: SuffixRo = SuffixRo())
data class SuffixRo(val option: String = "UNGUESSABLE")
data class ShortUrlRo(val shortLink: String, val warnings: List<WarningRo>, val previewLink: String)
data class WarningRo(val warningCode: String, val warningMessage: String)

This cannot be done programmatically as of the moment.

Try This , its working fine in my case,
https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[api-key]
{
"dynamicLinkInfo": {
"dynamicLinkDomain": "peg3z.app.goo.gl",
"link": "[Your Long Url Which you want to make short]",
"androidInfo": {
"androidPackageName": "com.xyz"//
},
"iosInfo": {
"iosBundleId": "com.dci.xyz"
}
}
}
'Content-Type: text/plain'

Related

Save object list in Xamarin Essentials

my first question is here
however since I was advised that questions should not change the original matter I created a new one.
I am saving user settings and I would like to save it in the list, I have had a look on setting by James however I found that that its not possible to save it in the list. So ia have decided to use Xamarin Essentials.
First I tried to save only a string value, which after some struggle I managed to work out and now I am trying to save an object
static void AddToList(SettingField text)
{
var savedList = new List<SettingField>(Preference.SavedList);
savedList.Add(text);
Preference.SavedList = savedList;
}
private void ExecuteMultiPageCommand(bool value)
{
var recognitionProviderSettings = new RecognitionProviderSettings
{SettingFields = new List<SettingField>()};
var set = new SettingField()
{
ProviderSettingId = "test",
Value = "test"
};
AddToList(set);
NotifyPropertyChanged("IsMultiPage");
}
and then the sterilization and des
public static class Preference
{
private static SettingField _settingField;
public static List<SettingField> SavedList
{
get
{
//var savedList = Deserialize<List<string>>(Preferences.Get(nameof(SavedList), "tesr"));
var savedList = Newtonsoft.Json.JsonConvert.DeserializeObject<SettingField>(Preferences.Get(nameof(SavedList), _settingField)) ;
SavedList.Add(savedList);
return SavedList ?? new List<SettingField>();
}
set
{
var serializedList = Serialize(value);
Preferences.Set(nameof(SavedList), serializedList);
}
}
static T Deserialize<T>(string serializedObject) => JsonConvert.DeserializeObject<T>(serializedObject);
static string Serialize<T>(T objectToSerialize) => JsonConvert.SerializeObject(objectToSerialize);
}
}
But Preferences.Get doesn't take object, is there any other way how can I save my setting to a object list? Please advise
I would recommend you to use SecureStorage. You can save your strings only into it. So the place where you have serilized your object as json. Just convert your json to string with .ToString() and save it into secure storage.
You may continue saving your serialized json object as string in Shared preferences but it is recommended to use SecureStorage Instead.

Switching feature in Handlebars Templates

So, we have created many templates using handlebars. Out of the many, we have one handlebar where we would like to make some changes that should only go live after a certain date. To do so, we wanted to create sort of a toggle switch, something like:
{{if switch on}}
display new content
{{else}}
display old content
Below is the generic template parser where I am trying to create a switch that I can inject in the if part of my template. Any suggestions?
/**
* Creates HTML output of the specified context for the given templateId and templateVersion combination
* we implicitly assume certain json fields (template specific) to be present in the content
*/
#Timed("handlebarsService.parseTemplateToHtml")
fun parseTemplateToHtml(htmlTemplateLocation: String, model: Map<String, Any>, locale: Locale): String {
val modelWithLanguage = model.toMutableMap()
modelWithLanguage[languageTag] = locale.language
//modelWithLanguage[switch] = "off"
val context = Context.newBuilder(modelWithLanguage)
.resolver(MapValueResolver.INSTANCE)
.build()
val template = try {
handlebars.compile(htmlTemplateLocation)
} catch (e: IOException) {
throw PdfGenerationException(e, "Internal error while compiling template")
}
return try {
template.apply(context)
} catch (e: IOException) {
throw PdfGenerationException(e, "Internal error while applying template")
}
}
}
private const val languageTag = "languageTag"
//private const val switch ="off"

flutter with firebase - detect the url string whether it is image(jpg) or video(avi)

I'm beginner with these Google's products and got 'serious' problem.
I uploaded photos and videos to firebase storage and urls of the photos and videos in the firebase storage is generated and stored automatically in firebase database. In my flutter lib, I could call those urls by my own code and display the url's image on the avd screen.
Image.network(url) is the code to display image url from firebase. But I also wanna display video url's asset simultaneously with single code. That is, videos and photos should be in single screen! In this case, Image.network(url) doesn't work anymore..
If I change that image.network code for video format according to video_player plug-in, I cannot display image asset anymore and if I stay same with that Image.network(url) code, I cannot display video url from firebase. So here is the question:
How can I detect whether the firebase's url string is image or video with my flutter code, and display that asset on the 'single screen' whatever the file format is(at least video and photo) with integrated flutter code?
url example
It's not much of a deal since type of the media is in the URL. You can parse it as a
Uri object then extract the type.
import 'dart:core';
enum UrlType { IMAGE, VIDEO, UNKNOWN }
void main() async {
var imageUrl =
'https://firebasestorage.googleapis.com/v0/b/myAppCodeNameForFirebase.appspot.com/o/Posts%20Pictures%2Fiufri095620200814.jpg?alt=media&token=89b6c22f-b8dd-4cff-9395-f53fc0808824';
var videoUrl =
'https://firebasestorage.googleapis.com/v0/b/myAppCodeNameForFirebase.appspot.com/o/Posts%20Pictures%2Fiufri095620200814.mp4?alt=media&token=89b6c22f-b8dd-4cff-9395-f53fc0808824';
print(getUrlType(imageUrl));
print(getUrlType(videoUrl));
}
UrlType getUrlType(String url) {
Uri uri = Uri.parse(url);
String typeString = uri.path.substring(uri.path.length - 3).toLowerCase();
if (typeString == "jpg") {
return UrlType.IMAGE;
}
if (typeString == "mp4") {
return UrlType.VIDEO;
} else {
return UrlType.UNKNOWN;
}
}
Let me give you an idea.
Consider implementing this scenario.
var url = 'domain.com/file.jpg?querySegment';
In your widget area,
child: url.contains('.mp4?') ? VideoWidget() : ImageWidget()
also, even with multiple conditions,
child: (url.contains('.jpg?') || url.contains('.png?')) ? ImageWidget() : VideoWidget()
May this suits your case.
Improving upon the accepted answer, here is what I have in my code. I needed a way to identify many types of videos and images from the passed url.
Using path package to idetify the extension
Have a list of video and image extension
import 'package:path/path.dart' as p;
enum UrlType { IMAGE, VIDEO, UNKNOWN }
class UrlTypeHelper {
static List<String> _image_types = [
'jpg',
'jpeg',
'jfif',
'pjpeg',
'pjp',
'png',
'svg',
'gif',
'apng',
'webp',
'avif'
];
static List<String> _video_types = [
"3g2",
"3gp",
"aaf",
"asf",
"avchd",
"avi",
"drc",
"flv",
"m2v",
"m3u8",
"m4p",
"m4v",
"mkv",
"mng",
"mov",
"mp2",
"mp4",
"mpe",
"mpeg",
"mpg",
"mpv",
"mxf",
"nsv",
"ogg",
"ogv",
"qt",
"rm",
"rmvb",
"roq",
"svi",
"vob",
"webm",
"wmv",
"yuv"
];
static UrlType getType(url) {
try {
Uri uri = Uri.parse(url);
String extension = p.extension(uri.path).toLowerCase();
if (extension.isEmpty) {
return UrlType.UNKNOWN;
}
extension = extension.split('.').last;
if (_image_types.contains(extension)) {
return UrlType.IMAGE;
} else if (_video_types.contains(extension)) {
return UrlType.VIDEO;
}
} catch (e) {
return UrlType.UNKNOWN;
}
return UrlType.UNKNOWN;
}
}
/// Usage
if(UrlTypeHelper.getType(message) == UrlType.IMAGE) {
/// handle image
}
else if(UrlTypeHelper.getType(message) == UrlType.VIDEO) {
/// handle video
}

Get Image from File Storage [Backendless]

My users upload some images to the FileStorage at Backendless.
This is the upload sequence:
Backendless.Files.Android.upload(image1_scaled, Bitmap.CompressFormat.PNG,
100, "profileImage", "images", new AsyncCallback<BackendlessFile>() {
#Override
public void handleResponse(BackendlessFile response) {
fileMapping.profile_url = response.getFileURL();
Backendless.Data.of(FileMapping.class).save(fileMapping,
new AsyncCallback<FileMapping>() {
#Override
public void handleResponse(FileMapping response) {
toast_error("Image stored");
}
#Override
public void handleFault(BackendlessFault fault) {
System.out.println("ERROR" + fault.getCode());
}
});
}
#Override
public void handleFault(BackendlessFault fault) {
}
});
And that works flawlessly. Now I need to fetch back the image with the API to display it.
So I need to make a BackendlessCollection<FileMapping> userFiles = Backendless.Data.of(FileMapping.class) call to receive the URL back from that table. And then supposedly do a httpRequest with the url to get back the byte data.
What I can't work out is what sort of .find method to use? Do I .findById() ? And if so, what ID do I use? The "path", "name" ,"table" etc?
Could anyone show an example fitting my case here, with a table storing the url's and such?
Thanks.
You'd this something like this (showing sync call for simplicity, but make sure to change it to Async on Android):
BackendlessCollection<FileMapping> fileMappings;
fileMappings = Backendless.Data.of( FileMapping.class ).find();
Iterator<FileMapping> iterator = fileMappings.getCurrentPage().iterator();
while( iterator.hasNext() )
{
FileMapping fileMapping = iterator.next();
Log.i( "MyApp", "file URL is " + fileMapping.profile_url );
}

Flex prevent URL encoding of params with HTTPRequest

I'm trying to port an existing AJAX app to Flex, and having trouble with the encoding of parameters sent to the backend service.
When trying to perform the action of deleting a contact, the existing app performs a POST, sending the the following: (captured with firebug)
contactRequest.contacts[0].contactId=2c33ddc6012a100096326b40a501ec72
So, I create the following code:
var service:HTTPService;
function initalizeService():void
{
service = new HTTPService();
service.url = "http://someservice";
service.method = 'POST';
}
public function sendReq():void
{
var params:Object = new Object();
params['contactRequest.contacts[0].contactId'] = '2c33ddc6012a100097876b40a501ec72';
service.send(params);
}
In firebug, I see this sent out as follows:
Content-type: application/x-www-form-urlencoded
Content-length: 77
contactRequest%2Econtacts%5B0%5D%2EcontactId=2c33ddc6012a100097876b40a501ec72
Flex is URL encoding the params before sending them, and we're getting an error returned from the server.
How do I disable this encoding, and get the params sent as-is, without the URL encoding?
I feel like the contentType property should be the key - but neither of the defined values work.
Also, I've considered writing a SerializationFilter, but this seems like overkill - is there a simpler way?
Writing a SerializtionFilter seemed to do the trick:
public class MyFilter extends SerializationFilter
{
public function MyFilter()
{
super();
}
override public function serializeBody(operation:AbstractOperation, obj:Object):Object
{
var s:String = "";
var classinfo:Object = ObjectUtil.getClassInfo(obj);
for each (var p:* in classinfo.properties)
{
var val:* = obj[p];
if (val != null)
{
if (s.length > 0)
s += "&";
s += StringUtil.substitute("{0}={1}",p,val);
}
}
return s;
}
}
I'd love to know any alternative solutions that don't involve doing this though!

Resources