Store Address book contact in sqlite titanium - titanium

So i am building an application that takes contact information from the address book and stores it into a Titanium Model for use later on in the user journey.
All other information is storing and returning correctly however the image of the contact always comes back blank for some reason.
The code for storing the address book information is as follows
if (Ti.Contacts.contactsAuthorization == Ti.Contacts.AUTHORIZATION_AUTHORIZED){
var people = Titanium.Contacts.getAllPeople();
var totalContacts = people.length;
var addressbook = [];
Alloy.Collections.contactsModel.numberOfContacts();
Ti.API.info(numberOfContacts);
if(totalContacts > 0){
var phoneContacts = [];
for (var index = 0; index < totalContacts; index++){
var person = people[index];
phoneContacts.push({
name:person.fullName,
phoneNumber:person.phone,
profileImage:person.image,
contactID:person.identifier
});
}
Alloy.Collections.contactsModel.reset(phoneContacts);
Alloy.Collections.contactsModel.each(function(_m) {
_m.save();
});
}
} else if (Ti.Contacts.contactsAuthorization == Ti.Contacts.AUTHORIZATION_UNKNOWN){
Ti.Contacts.requestAuthorization(function(e){
//Authorization is unknown so requesting for authorization
if (e.success) {
} else {
}
});
} else {
}
}
The model definition is as follows
exports.definition = {
config: {
columns: {
"friendID": "INTEGER PRIMARY KEY AUTOINCREMENT",
"contactID": "string",
"name": "string",
"phoneNumber": "string",
"emailAddress": "string",
"profileImage": "blob"
},
adapter: {
type: "sql",
collection_name: "contactsModel",
idAttribute:"friendID"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
// extended functions and properties go here
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
collection.trigger('sync');
},
}
}
*/
});
return Collection;
}
};
The image was working fine when collecting it from the address book and putting it into a list view. However when it's saved and then i attempt to retrieve it and put it into a list view where the problem occurs.
Thanks guys.

Something to consider is not to put all the information in the database. The reason is that when it changes on the device, those changes will not reflect in the records you've stored.
Here's how I approach it:
var db = Ti.Database.open( 'person' );
db.execute( "CREATE TABLE IF NOT EXISTS people( " +
"id INTEGER PRIMARY KEY, identifier TEXT, pid INTEGER);" );
var person = db.execute( 'SELECT id, identifier, pid FROM people' );
while( person.isValidRow( ) ) {
var contact,
contact_id;
if( OS_IOS ) {
contact_id = person.fieldByName( 'identifier' );
}
if( OS_ANDROID ) {
contact_id = person.fieldByName( 'pid' );
}
contact = Ti.Contacts.getPersonByIdentifier( contact_id );
var p_image = contact.image || "/images/user";
...
}
Essentially, I store the contact's ID in the database and then use that identifier to retrieve the user's info.
Note that the user's record does not always have an image, so it is a good idea to provide a default.

Related

I'm creating an erp connector for a company with google data studio, but I don't know how this process works

const cc = DataStudioApp.createCommunityConnector();
function getAuthType() {
return cc.newAuthTypeResponse()
.setAuthType(cc.AuthType.USER_TOKEN)
.setHelpUrl('https://api.sigecloud.com.br/swagger/ui/index#/')
.build();
}
function resetAuth() {
var userTokenProperties = PropertiesService.getUserProperties();
userTokenProperties.deleteProperty('dscc.username');
userTokenProperties.deleteProperty('dscc.password');
}
function isAuthValid() {
var userProperties = PropertiesService.getUserProperties();
var userName = userProperties.getProperty('dscc.username');
var token = userProperties.getProperty('dscc.token');
var res = UrlFetchApp.fetch(`https://api.sigecloud.com.br/request/Pedidos/GetTodosPedidos&Authorization-Token${token}&User=${userName}&page=12&App=API APP`, { 'muteHttpExceptions': true });
return res.getResponseCode() == 200;
}
function getConfig() {
}
function getSchema() {
}
function getData() {
}
This is Manifest:
{
"timeZone": "America/Sao_Paulo",
"dependencies": {},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"dataStudio":{
"name": "Two Dogs Connector with Sige",
"description": "The unofficial conecctor to acess Sige Data",
"company": "Mateus C Rocha",
"logoUrl": "https://images.sympla.com.br/62ea7b9d69ec5.png",
"addOnUrl": "https://twodogs.com/br/quem-somos/",
"supportUrl": "https://twodogs.com/br/quem-somos/"
}
}
This error appears when I add the implementation ID generated when I select the test implementation option, in the google script
My api needs to receive: Page, user(constant value), token(constant value) and App(constant value)...
I don't know how it works, but I was hoping it wouldn't show errors, as I followed the documentation https://developers.google.com/looker-studio/connector/get-started

How to disable a graphql filter if the variable is not set?

I am working on a page with configurable filters. The graphql query looks like:
query GetPlayers(
$offset: Int
$limit: Int
$skillIds: [uuid!] = null
$playerTypeIds: [Int!] = null
$availability: Int = null
$timezones: [String!] = null
$search: String = null
) {
player(
order_by: { total_xp: desc }
offset: $offset
limit: $limit
where: {
availability_hours: { _gte: $availability }
timezone: { _in: $timezones }
player_type_id: { _in: $playerTypeIds }
Player_Skills: { Skill: { id: { _in: $skillIds } } }
_or: [
{ username: { _ilike: $search } }
{ ethereum_address: { _ilike: $search } }
]
}
) {
id
}
}
I would like the default behavior to be to return all entries. I am using Hasura 1.3.3 and null is interpreted as {} which will return all entries. The only problem is the Player_Skills: { Skill: { id: { _in: $skillIds } } } line. There is a join table with foreign keys referring to the players and skills tables, and that line will only return players who have at least one entry in that table.
Is it possible to form a query that will ignore the skills filter if $skillIds is null?

How can i reset the data after I delete/update from list?

I am working on a project. I am using Angular 2 as a front end and firebase as backend. TO access the data from Firebase i am using express. I am using REST methodology. Now all i am facing an issue here is to rest the data after i delete anything or update anything in the List. I am posting Delete and Update code. Please let me know whether i am doing any mistake or what.
router.route('/contacts/:id').get(function(req , res) {
//Show contact based on ID which is passed as perameter
var contactId = req.params.id;
contactRef.child(contactId).once('value' , function(snapshot) {
if(snapshot.exists()) {
var contactVal = snapshot.val();
res.json(contactVal);
} else {
res.json({message : "Contact does not exist"});
}
})
}).delete(function(req,res) {
//Deletes the Contact based on the ID which we are passing as perameter
var contactId = req.params.id;
console.log(contactId);
contactRef.child(contactId).remove(function(){
console.log("deleted")
});
res.json({message : "Contact with contact id "+ contactId +" has been removed"});
}).put(function(req, res) {
//Updates the contact based on ID passed in the perameter.
var contactId = req.params.id;
console.log(req.body);
contactRef.child(contactId).update();
contactRef.child(contactId).once(req.body , function(snapshot) {
//
if(snapshot.exists()) {
console.log("Contact Id" + contactId)
var contactVal = snapshot.val();
res.json({"contact ID " : contactId} );
} else {
res.json({message : "Contact does not exist"});
}
})
})
This is the code i am using but not having any idea what to do. Please let me whether i am doing anything wrong then.

Restrict access to RPC endpoints

I wonder if deepstream provides ready-to-use solution to make endpoints private/public. If it doesn't I wonder how I can track proper deepstream calls on server side to allow only certain endpoints? I believe I need to provider permissionHandler that implements canPerformAction and check whether it's an RPC call required authorization and whether a caller authorized properly to do that. Is that right thinking? I'm looking at documentation and understand that I'm interested in topic P but I don't know what is a right action to check.
https://deepstream.io/docs/constants.html
Thanks in advance!
You're spot on with your approach. Here's a code sample on how to permission different users for different RPCs. In a real-world use-case you would most likely get the variables users and rpcs from a database.
So now whenever a client calls ds.rpc.make( 'set-user-data',... the server looks up which permission the rpc requires ('canEditUser') and if the user has that permission (mike: true, lisa: false)
var DeepstreamServer = require( 'deepstream.io' );
var server = new DeepstreamServer();
var C = server.constants;
var users = {
'mike': { canEditUser: true },
'lisa': { canEditUser: false }
};
var rpcs = {
'set-user-data': 'canEditUser'
};
server.set( 'permissionHandler', {
isValidUser: function( connectionData, authData, callback ) {
if( !authData.username ) {
callback( 'no username specified' );
}
else if( users[ authData.username ] ) {
callback( null, authData.username );
}
},
canPerformAction: function( username, message, callback ) {
var isIncomingRpc = message.topic === C.TOPIC.RPC && message.action === C.ACTIONS.REQUEST;
if( isIncomingRpc ) {
var rpcName = message.data[ 0 ];
if( rpcs[ rpcName ] === undefined ) {
callback( 'Unknown RPC ' + rpcName );
return;
}
var userPermissions = users[ username ];
var requiredRpcPermissions = rpcs[ rpcName ];
var isPermissioned = userPermissions[ requiredRpcPermissions ];
callback( null, isPermissioned );
}
}
});
server.start();

google directory api -> Get phone numer from user.phones[].primary

I use this code to logger successfully log : user fullname and user primaryEmail.
from property of AdminDirectory.Users.list
But I don't understand how I can get the phone user .
The syntax user.phones[].primary doesn't work
function listAllUsers() {
var pageToken, page;
do {
page = AdminDirectory.Users.list({
domain: 'example.com',
orderBy: 'givenName',
maxResults: 100,
pageToken: pageToken
});
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i++) {
var user = users[i];
Logger.log(user.name.fullName, user.primaryEmail,user.phones[].primary);
}
} else {
Logger.log('No users found.');
}
pageToken = page.nextPageToken;
} while (pageToken);
}
The parameters user.phones[] doesnt' work see google reference
You are attempting to access an array (that's what the [] indicates), therefore you must specify an index.
If you want to access the primary variable of the first value in the phones array, then you would use:
user.phones[0].primary