How to get app name programatically in native script - nativescript

I'm trying to save some files on my local File storage So, I'm doing Something like below
var folder_name = "abcde/" + viewModel.dir_path;
const documents = fileSystemModule.knownFolders.documents();
documents._path = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
const folder = documents.getFolder(folder_name);
var file = fileSystemModule.path.join(folder._path, this.pdf_url.split("/").pop());
var url = this.pdf_url;
httpModule.getFile(url, file).then(function(result) {
console.log(result);
Toast.makeText(`${result._name} is succesfully downloaded in ${folder_name}`).show();
}, function(e) {
console.log(e);
});
the only problem is the hardcoded value abcde/ I want it to be app name. whatever the app name is it should take that name.
I don't find any ways to read app name programatically. I need this to Android I'm not interested in IOS.

may be this is one could be the answer. but still this is not a proper way
const documents = fileSystemModule.knownFolders.currentApp();
console.log(documents); --> "/data/data/org.nativescript.app_name/files/app"
var str = documents;
var arr = str.split("/")[3];
console.log(arr.split(".")[2]); ---> app_name

In Android, you can set the app name for the application in strings.xml, for example:
<string name="app_name">"App_Name"</string>
Then whenever you want to reuse the app name, you can use the getString method with its name in the application.

Related

NativeScript: How to copy a file from an apps folder to a user accessible folder?

I want to copy storage.db to documents or downloads folder. It's very easy to get the file path:
const filePath = application.android.context.getDatabasePath("storage.db").getAbsolutePath();
But, what isn't that easy is to copy that file to a folder users have access to. I searched this whole forum, and I found nothing useful for my case.
I'm using NativeScript 4.0.1 with vanilla JS.
If you want to share the DB file, the easiest way is to use nativescript-share-file plugin, send the file path and it will give you a nice dialog with intent picker, user may choose to Email the file Or save it to local folder etc.,
const shareFile = new ShareFile();
shareFile.open({
path: filePath,
});
I finally found the solution. I've seen so many users trying to achieve this, and I hope this will help all of you.
Add this to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Install nativescript-permissions:
npm i nativescript-permissions
Asking for permission:
const permissions = require('nativescript-permissions');
permissions.requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, "");
Require the necessary modules:
const fileSystemModule = require("tns-core-modules/file-system");
const application = require("application");
Then, create this function where you need to use it:
function copyFile() {
var myInput = new java.io.FileInputStream(appModule.android.context.getDatabasePath("storage.db").getAbsolutePath());
var myOutput = new java.io.FileOutputStream("/storage/emulated/0/databases/storage.db");
try {
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.class.getField("TYPE").get(null), 1024);
var length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
}
catch (err) {
console.info("Error", err);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
exports.copyFile = copyFile;
In my case, the file storage.db will be copied to /storage/emulated/0/databases. If you need to create a folder, just do the following:
try {
var javaFile = new java.io.File("/storage/emulated/0/newfolder");
if (!javaFile.exists()) {
javaFile.mkdirs();
javaFile.setReadable(true);
javaFile.setWritable(true);
}
}
catch (err) {
console.info("Error", err);
}
If the destination folder has a file with the same name as the one you want to copy, you need to remove it first. That's why you should create a specific folder to guarantee it's empty.

How can i get the picture filename from a google drive url?

I have a lot of picture links in my Google Sheet:
https://drive.google.com/file/d/1BDj24_6uz-ZQlGWLy0o1_DES6tJI3NMu/view?usp=sharing
I want to get the filename behind the link. When i open the link and save the image the image filename is: "FILENAME.jpg" or something similar
I want to get this information in Sheets.
How can i do that?
An Apps Script Solution
Thanks to #Tanaike for obtaining clarifications in the comments.
First enter your links in the format shown below in a Google Sheet.
The name of the titles is not important, but this particular script starts getting names from the 2nd row.
If you don't know how to create a script, there are tutorials here offered by Google. You should create the script from the same Sheet. That is, from the menu in the Sheet:
In the script editor, copy and paste the following code:
function getNames() {
var activeRange = SpreadsheetApp.getActiveSheet().getDataRange();
var height = activeRange.getHeight();
var links = SpreadsheetApp.getActiveSheet()
.getRange("A2:A" + height)
.getValues();
var nameValues = [];
links.forEach((row) => {
try {
var link = row[0];
var fileID = getIdFromLink(link);
var name = DriveApp.getFileById(fileID).getName();
nameValues.push([name]);
} catch (e) {
nameValues.push(["NO NAME FOUND"]);
}
});
var nameRange = SpreadsheetApp.getActiveSheet().getRange("B2:B" + height);
nameRange.setValues(nameValues);
}
function getIdFromLink(link) {
var regex = new RegExp(
/(?<=https:\/\/drive\.google\.com\/file\/d\/)(.+)(?=\/)/
);
return regex.exec(link)[0];
}
Run the getNames function. The first time it will ask you to grant some permissions, grant them. Then it should fill in the files names.
References
Apps Script Overview
Spreadsheet service in Apps Script
Drive service in Apps Script

Load JSON From External Storage

I am building an app for an LG Smart TV. I need to load json data from a USB drive when it's inserted into the smart TV.
I'm not sure how to do this, never worked on an app like this.
My question is how do I gain access to external storage and load json data into my app?
Using the SCAP API (v1.2+)
function readFile() {
var successCb = function (cbObject) {
var data_text = cbObject.data;
// do something with the json string
};
var failureCb = function (cbObject) {
var errorCode = cbObject.errorCode;
var errorText = cbObject.errorText;
// do something with the error
};
// Read the whole file from the beginning, as a text file.
var options = {
path: "file://usb:[INDEX]/[FILE_PATH]",
position: 0,
encoding: 'utf8'
};
var storage = new Storage();
storage.readFile(successCb, failureCb, options);
}
The filepath for a usb is file://usb:[INDEX]/[FILE_PATH] [INDEX] is the usb index (could have multiple USBs connected).
Additional help can be found here: http://webossignage.developer.lge.com/api/scap-api/scap16/storage/?wos_flag=readFile#readFile
You can use getStorageInfo() to check if your usb is available.

tuneup.js reports "Can't find variable" for test() method

enter code hereBecause I can't get pass/fail logging to work correctly with the 4.6 version of Instruments, I'm trying to use the tuneup.js library, but I keep getting the following error whenever I try to run the test:
Can't find variable: test
Here's the code:
//We want to use the tuneup library to add extra capabilities
#import <tuneup_js/tuneup.js>
#import <tuneup_js/test.js>
var target = UIATarget.localTarget();
var target = UIATarget.localTarget();
var app = UIATarget.localTarget().frontMostApp();
test("Test1", function(target, app) {
//Do UI automation stuff
var titleDisplayed = tableView.cells()[0].name();
var StoryName = "My Dogs!";
UIALogger.logMessage("My Story Title: " + titleDisplayed);
UIALogger.logMessage("Innocuous Message-1.");
assertEquals(titleDisplayed, StoryName);
}); // <------Error points to this line!
//End test
Any idea what I'm doing wrong? The tuneup.js library is in a folder called tuneup_js which is in the root of the directory which contains my test script (an Instruments trace file), and I don't get any import errors on start.
The problem is that Instruments cant find the *tuneup_js* library so it doesn't find the test function .You need to add the imports in quotes and you dont need to add tuneup_js/test.js because tuneup_js/tuneup.js includes all the classes needed
//We want to use the tuneup library to add extra capabilities
#import "tuneup_js/tuneup.js"
var target = UIATarget.localTarget();
var target = UIATarget.localTarget();
var app = UIATarget.localTarget().frontMostApp();
test("Test1", function(target, app) {
//Do UI automation stuff
var titleDisplayed = tableView.cells()[0].name();
var StoryName = "My Dogs!";
UIALogger.logMessage("My Story Title: " + titleDisplayed);
UIALogger.logMessage("Innocuous Message-1.");
assertEquals(titleDisplayed, StoryName);
});

Unable to set firefox bookmark description for in Add-On Kit API

I found the nsINavBookmarksService, however since Firefox 3, it does not seem to have any API methods for getting/setting the Bookmark description. (API doc)
I've seen other Add-Ons modify the description as a method of synchronized data storage (which is exactly what I'm trying to do). I'm guessing perhaps the description is a non-gecko standard, and that's why it is not directly supported, but then there must be a completely different interface for manipulating Bookmarks that I haven't discovered.
Can anyone help with this newbie problem?
Starting with Firefox 3 the bookmarks have been merged into the Places database containing all of your browsing history. So to get the bookmarks you do a history query, like this (first line is specific to the Add-on SDK which you appear to be using):
var {Cc, Ci} = require("chrome");
var historyService = Cc["#mozilla.org/browser/nav-history-service;1"]
.getService(Ci.nsINavHistoryService);
var options = historyService.getNewQueryOptions();
var query = historyService.getNewQuery();
query.onlyBookmarked = true;
var result = historyService.executeQuery(query, options);
result.root.containerOpen = true;
for (var i = 0; i < result.root.childCount; i++)
{
var node = result.root.getChild(i);
console.log(node.title);
}
That's mostly identical to the code example here. Your problem is of course that nsINavHistoryResultNode has no way of storing data like a description. You can set annotations however, see Using the Places annotation service. So if you already have a node variable for your bookmark:
var annotationName = "my.extension.example.com/bookmarkDescription";
var ioService = Cc["#mozilla.org/network/io-service;1"]
.getService(Ci.nsIIOService);
var uri = ioService.newURI(node.uri, null, null);
var annotationService = Cc["#mozilla.org/browser/annotation-service;1"]
.getService(Ci.nsIAnnotationService);
annotationService.setPageAnnotation(uri, annotationName,
"Some description", 0, Ci.nsIAnnotationService.EXPIRE_NEVER);
For reference: nsIAnnotationService.setPageAnnotation()

Resources