Esempio n. 1
0
 protected async override void OnNavigatedTo(NavigationEventArgs e)
 {
     store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly);
     RemoteIdHelper remoteIdHelper = new RemoteIdHelper();
     await remoteIdHelper.SetRemoteIdGuid(store);
     base.OnNavigatedTo(e);
 }
Esempio n. 2
0
 private async void CreateContactStore()
 {
     contacts = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly);
     if (contacts.RevisionNumber <1)
     {
         Contacts cons = new Contacts();
         cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(SearchCompleted);
         cons.SearchAsync(String.Empty, FilterKind.None, "Searching");
     }
 }
Esempio n. 3
0
    public async Task<string> GetTaggedRemoteId(ContactStore store, string remoteId)
    {
      var taggedRemoteId = String.Empty;
      var extendedProperties = await store.LoadExtendedPropertiesAsync();

      if (extendedProperties.ContainsKey(ContactStoreKey))
      {
        taggedRemoteId = string.Format("{0}_{1}", extendedProperties[ContactStoreKey], remoteId);
      }

      return taggedRemoteId;
    }
Esempio n. 4
0
 public async Task TrySetRemoteIdGuid(ContactStore store)
 {
   var extendedProperties = await store.LoadExtendedPropertiesAsync().AsTask();
   if (!extendedProperties.ContainsKey(ContactStoreKey))
   {
     // the given store does not have a local instance id so set one against store extended properties
     var guid = Guid.NewGuid();
     extendedProperties.Add(ContactStoreKey, guid.ToString());
     
     var readonlyProperties = new ReadOnlyDictionary<string, object>(extendedProperties);
     await store.SaveExtendedPropertiesAsync(readonlyProperties);
   }
 }
Esempio n. 5
0
 public async Task SetRemoteIdGuid(ContactStore store)
 {
     IDictionary<string, object> properties;
     properties = await store.LoadExtendedPropertiesAsync().AsTask<IDictionary<string, object>>();
     if (!properties.ContainsKey(ContactStoreLocalInstanceIdKey))
     {
         // the given store does not have a local instance id so set one against store extended properties
         Guid guid = Guid.NewGuid();
         properties.Add(ContactStoreLocalInstanceIdKey, guid.ToString());
         System.Collections.ObjectModel.ReadOnlyDictionary<string, object> readonlyProperties = new System.Collections.ObjectModel.ReadOnlyDictionary<string, object>(properties);
         await store.SaveExtendedPropertiesAsync(readonlyProperties).AsTask();
     }
 }
Esempio n. 6
0
        private async void GetContact(string id)
        {

            //通过联系人的Id获取联系人的信息
         
            //创建联系人存储
            conStore = await ContactStore.CreateOrOpenAsync();
            //查找联系人
            storCon = await conStore.FindContactByIdAsync(id);
            //获取联系人信息
            properties = await storCon.GetPropertiesAsync();
            name.Text = storCon.GivenName;
            telphone.Text = properties[KnownContactProperties.Telephone ].ToString();
           
        }
Esempio n. 7
0
        public async Task<string> GetTaggedRemoteId(ContactStore store, string remoteId)
        {
            string taggedRemoteId = string.Empty;

            System.Collections.Generic.IDictionary<string, object> properties;
            properties = await store.LoadExtendedPropertiesAsync().AsTask<System.Collections.Generic.IDictionary<string, object>>();
            if (properties.ContainsKey(ContactStoreLocalInstanceIdKey))
            {
                taggedRemoteId = string.Format("{0}_{1}", properties[ContactStoreLocalInstanceIdKey], remoteId);
            }
            else
            {
                // handle error condition
            }

            return taggedRemoteId;
        }
Esempio n. 8
0
    public async Task<string> GetUntaggedRemoteId(ContactStore store, string taggedRemoteId)
    {
      var remoteId = String.Empty;

      var properties = await store.LoadExtendedPropertiesAsync();
      if (properties.ContainsKey(ContactStoreKey))
      {
        var localInstanceId = properties[ContactStoreKey] as String;
        
        if (!String.IsNullOrEmpty(localInstanceId) &&
            taggedRemoteId.Length > localInstanceId.Length + 1)
        {
          remoteId = taggedRemoteId.Substring(localInstanceId.Length + 1);
        }
      }

      return remoteId;
    }
Esempio n. 9
0
 /// <summary>
 /// 获取联系人列表
 /// </summary>
 private async void GetContacts()
 {
     conStore = await ContactStore.CreateOrOpenAsync();
     ContactQueryResult conQueryResult = conStore.CreateContactQuery();
     //查询联系人
     IReadOnlyList<StoredContact> conList = await conQueryResult.GetContactsAsync();
     List<Item> list = new List<Item>();
     foreach (StoredContact storCon in conList)
     {
         var properties = await storCon.GetPropertiesAsync();
         list.Add(new Item 
         {
             Name=storCon .GivenName ,
             Id =storCon .Id ,
         });
     }
     conListBox.ItemsSource = list;
 }
Esempio n. 10
0
        public async Task<string> GetUntaggedRemoteId(ContactStore store, string taggedRemoteId)
        {
            string remoteId = string.Empty;

            System.Collections.Generic.IDictionary<string, object> properties;
            properties = await store.LoadExtendedPropertiesAsync().AsTask<System.Collections.Generic.IDictionary<string, object>>();
            if (properties.ContainsKey(ContactStoreLocalInstanceIdKey))
            {
                string localInstanceId = properties[ContactStoreLocalInstanceIdKey] as string;
                if (taggedRemoteId.Length > localInstanceId.Length + 1)
                {
                    remoteId = taggedRemoteId.Substring(localInstanceId.Length + 1);
                }
            }
            else
            {
                // handle error condition
            }

            return remoteId;
        }
Esempio n. 11
0
 protected async override void OnNavigatedTo(NavigationEventArgs e)
 {
     if (NavigationContext.QueryString.Keys.Contains("id"))
     {
         id = NavigationContext.QueryString["id"];
     }
     contactStore = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly);
     storedContact = await contactStore.FindContactByIdAsync(id);
     if (storedContact != null)
     {
         var properties = await storedContact.GetPropertiesAsync();
         if (properties.Keys.Contains(KnownContactProperties.FamilyName))
         {
             name.Text = properties[KnownContactProperties.FamilyName].ToString();
         }
         if (properties.Keys.Contains(KnownContactProperties.Telephone))
         {
             tel.Text = properties[KnownContactProperties.Telephone].ToString();
         }
     }
     base.OnNavigatedTo(e);
 }
Esempio n. 12
0
 /// <summary>
 /// 获取联系人
 /// </summary>
 private async void GetContacts()
 {
     //创建联系人存储
     conStore = await ContactStore.CreateOrOpenAsync();
     //联系人查询的结果
     conQueryResult = conStore.CreateContactQuery();
     //联系人集合
     conList = await conQueryResult.GetContactsAsync();
     //显示联系人的集合
    
     List<Item> list = new List<Item>();
     foreach (StoredContact storCon in conList)
     {
         var properties = await storCon.GetPropertiesAsync();
         list.Add(new Item
             {
                 Name = storCon.GivenName,
                 Id =storCon .Id 
             });
     }
     conListBox.ItemsSource = list;
 }    
Esempio n. 13
0
 private async void GetContact(string p)
 {
     //创建联系人存储
     conStore = await ContactStore.CreateOrOpenAsync();
     //联系人查询结果
     ContactQueryResult conQueryResult = conStore.CreateContactQuery();
     //查询联系人
     IReadOnlyList<StoredContact> conList = await conQueryResult.GetContactsAsync();
     List<Item> list = new List<Item>();
     foreach (StoredContact strCon in conList)
     {
         if (strCon.GivenName.Contains(p))
         {
             list.Add(new Item
             {
                 Name = strCon.GivenName,
                 Id = strCon.Id,
             });
         }
     }
     conListBox.ItemsSource = list;
 }
Esempio n. 14
0
        private async Task ImportAsync(ContactStore store)
        {
            var contacts = await store.FindContactsAsync();

            var importedPhones = new Dictionary <string, Contact>();

            foreach (var contact in contacts)
            {
                foreach (var phone in contact.Phones)
                {
                    importedPhones[phone.Number] = contact;
                }
            }

            var importedPhonesCache = GetImportedPhones();

            var importingContacts = new TLVector <TLInputContactBase>();
            var importingPhones   = new List <string>();

            foreach (var phone in importedPhones.Keys.Take(1300).ToList())
            {
                if (!importedPhonesCache.ContainsKey(phone))
                {
                    var contact   = importedPhones[phone];
                    var firstName = contact.FirstName ?? string.Empty;
                    var lastName  = contact.LastName ?? string.Empty;

                    if (string.IsNullOrEmpty(firstName) && string.IsNullOrEmpty(lastName))
                    {
                        if (string.IsNullOrEmpty(contact.DisplayName))
                        {
                            continue;
                        }

                        firstName = contact.DisplayName;
                    }

                    if (!string.IsNullOrEmpty(firstName) || !string.IsNullOrEmpty(lastName))
                    {
                        var item = new TLInputPhoneContact
                        {
                            Phone     = phone,
                            FirstName = firstName,
                            LastName  = lastName,
                            ClientId  = importedPhones[phone].GetHashCode()
                        };

                        importingContacts.Add(item);
                        importingPhones.Add(phone);
                    }
                }
            }

            if (importingContacts.IsEmpty())
            {
                return;
            }

            //base.IsWorking = true;
            _protoService.ImportContactsAsync(importingContacts, result =>
            {
                //Telegram.Api.Helpers.Execute.BeginOnUIThread(delegate
                //{
                //    this.IsWorking = false;
                //    this.Status = ((this.Items.get_Count() == 0 && this.LazyItems.get_Count() == 0 && result.Users.Count == 0) ? string.Format("{0}", AppResources.NoContactsHere) : string.Empty);
                //    int count = result.RetryContacts.Count;
                //    if (count > 0)
                //    {
                //        Telegram.Api.Helpers.Execute.ShowDebugMessage("contacts.importContacts error: retryContacts count=" + count);
                //    }
                //    this.InsertContacts(result.Users);
                //});

                _aggregator.Publish(new TLUpdateContactsReset());
                SaveImportedPhones(importedPhonesCache, importingPhones);
            },
                                              fault =>
            {
                Telegram.Api.Helpers.Execute.BeginOnUIThread(delegate
                {
                    //this.IsWorking = false;
                    //this.Status = string.Empty;
                    Telegram.Api.Helpers.Execute.ShowDebugMessage("contacts.importContacts error: " + fault);
                });
            });
        }
Esempio n. 15
0
        private async Task initContactStore()
        {
            // Khởi tạo Id để có thể generate thành Id của Contact trên Store khi sync 
            App.ContactStore = await Windows.Phone.PersonalInformation.ContactStore.CreateOrOpenAsync(
                ContactStoreSystemAccessMode.ReadWrite,
                ContactStoreApplicationAccessMode.LimitedReadOnly);

            App.RemoteIdHelper = new RemoteIdHelper();
            await RemoteIdHelper.SetRemoteIdGuid(App.ContactStore);
        }
 public ContactController(ContactStore contactStore)
 {
     _contactStore = contactStore ?? throw new ArgumentNullException(nameof(ContactStore));
 }
Esempio n. 17
0
        protected void ProcessMessages(ProtocolTreeNode[] nodes)
        {
            foreach (ProtocolTreeNode node in nodes)
            {
                if (node.tag.Equals("message"))
                {
                    ProtocolTreeNode body         = node.GetChild("body");
                    ProtocolTreeNode media        = node.GetChild("media");
                    ProtocolTreeNode paused       = node.GetChild("paused");
                    ProtocolTreeNode composing    = node.GetChild("composing");
                    ProtocolTreeNode notification = node.GetChild("notification");
                    string           jid          = node.GetAttribute("from");

                    if (body != null || media != null)
                    {
                        //extract and save nickname
                        if (node.GetChild("notify") != null && node.GetChild("notify").GetAttribute("name") != null)
                        {
                            string  nick = node.GetChild("notify").GetAttribute("name");
                            Contact c    = ContactStore.GetContactByJid(jid);
                            if (c != null)
                            {
                                c.nickname = nick;
                                ContactStore.UpdateNickname(c);
                            }
                        }

                        try
                        {
                            this.getChat(jid, true, false).AddMessage(node);
                        }
                        catch (Exception)
                        { }

                        //refresh list
                        this._loadConversations();
                    }
                    if (paused != null)
                    {
                        try
                        {
                            if (this.getChat(jid, false, false) != null)
                            {
                                this.getChat(jid, false, false).SetOnline();
                            }
                        }
                        catch (Exception e)
                        {
                            //throw e;
                        }
                    }
                    if (composing != null)
                    {
                        try
                        {
                            if (this.getChat(jid, false, false) != null)
                            {
                                this.getChat(jid, false, false).SetTyping();
                            }
                        }
                        catch (Exception e)
                        {
                            //throw e;
                        }
                    }
                    if (notification != null)
                    {
                        if (notification.GetAttribute("type") == "picture")
                        {
                            ChatWindow.GetImageAsync(notification.GetChild("set").GetAttribute("jid"), false);
                        }
                    }
                }
                else if (node.tag.Equals("presence"))
                {
                    string jid = node.GetAttribute("from");
                    if (node.GetAttribute("type") != null && node.GetAttribute("type").Equals("available"))
                    {
                        try
                        {
                            if (this.getChat(jid, false, false) != null)
                            {
                                this.getChat(jid, false, false).SetOnline();
                            }
                        }
                        catch (Exception e)
                        {
                            //throw e;
                        }
                    }
                    if (node.GetAttribute("type") != null && node.GetAttribute("type").Equals("unavailable"))
                    {
                        try
                        {
                            if (this.getChat(jid, false, false) != null)
                            {
                                this.getChat(jid, false, false).SetUnavailable();
                            }
                        }
                        catch (Exception e)
                        {
                            //throw e;
                        }
                    }
                }
                else if (node.tag.Equals("iq"))
                {
                    string jid = node.GetAttribute("from");

                    if (node.children.First().tag.Equals("query"))
                    {
                        DateTime lastseen = DateTime.Now;
                        int      seconds  = Int32.Parse(node.GetChild("query").GetAttribute("seconds"));
                        lastseen = lastseen.Subtract(new TimeSpan(0, 0, seconds));
                        try
                        {
                            if (this.getChat(jid, false, false) != null)
                            {
                                getChat(jid, false, false).SetLastSeen(lastseen);
                            }
                        }
                        catch (Exception e)
                        {
                            //throw e;
                        }
                    }
                    else if (node.children.First().tag.Equals("group"))
                    {
                        string  subject = node.children.First().GetAttribute("subject");
                        Contact cont    = ContactStore.GetContactByJid(jid);
                        if (cont != null)
                        {
                            cont.nickname = subject;
                            ContactStore.UpdateNickname(cont);
                        }
                        else
                        {
                        }
                    }
                    else if (node.children.First().tag.Equals("picture"))
                    {
                        string  pjid       = node.GetAttribute("from");
                        string  id         = node.GetAttribute("id");
                        byte[]  rawpicture = node.GetChild("picture").GetData();
                        Contact c          = ContactStore.GetContactByJid(pjid);
                        if (c != null)
                        {
                            Image img = null;
                            using (var ms = new MemoryStream(rawpicture))
                            {
                                try
                                {
                                    img = Image.FromStream(ms);
                                    string targetdir = Directory.GetCurrentDirectory() + "\\data\\profilecache";
                                    if (!Directory.Exists(targetdir))
                                    {
                                        Directory.CreateDirectory(targetdir);
                                    }
                                    img.Save(targetdir + "\\" + c.jid + ".jpg");
                                    try
                                    {
                                        if (this.getChat(pjid, false, false) != null)
                                        {
                                            this.getChat(pjid, false, false).SetPicture(img);
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        throw e;
                                    }
                                }
                                catch (Exception e)
                                {
                                    throw e;
                                }
                            }
                        }
                        if (picturesToSync.Remove(pjid))
                        {
                            this.requestProfilePicture();
                        }
                    }
                    else if (node.children.First().tag.Equals("error") && node.children.First().GetAttribute("code") == "404")
                    {
                        string pjid = node.GetAttribute("from");
                        picturesToSync.Remove(pjid);
                        this.requestProfilePicture();
                    }
                }
            }
        }
 public DirectAddCommand(ContactStore store, IEnumerable <Contact> contacts)
 {
     this.store    = store;
     this.contacts = contacts;
 }
Esempio n. 19
0
        protected void ExecuteImport()
        {
            //start sync
            ContactsService GContactService = new ContactsService("Contact Infomation");

            GContactService.setUserCredentials(email, password);

            ContactsQuery query = new ContactsQuery(ContactsQuery.
                                                    CreateContactsUri("default"));
            ContactsFeed feed = null;

            try
            {
                feed = GContactService.Query(query);
            }
            catch (Exception exe)
            {
                this.setLabelText("Invalid email or password", Color.Red);
                return;
            }

            //start
            this.showProgressBar(feed.TotalResults);
            this.setLabelText("Importing...", Color.Black);

            int progress   = 0;
            int startIndex = 0;

            while (feed.Entries.Count > 0)
            {
                startIndex      += feed.ItemsPerPage;
                query.StartIndex = startIndex;
                PhoneNumbers.PhoneNumberUtil util = PhoneNumbers.PhoneNumberUtil.GetInstance();
                foreach (ContactEntry entry in feed.Entries)
                {
                    this.setProgress(progress);
                    progress++;

                    if (entry.Phonenumbers.Count > 0)
                    {
                        foreach (PhoneNumber number in entry.Phonenumbers)
                        {
                            string numb = string.Empty;
                            try
                            {
                                PhoneNumbers.PhoneNumber num = util.Parse(number.Value, "NL");
                                numb = num.CountryCode.ToString() + num.NationalNumber.ToString();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Exception was thrown: " + ex.Message);
                                continue;
                            }
                            if (!ContactStore.numberExists(numb + "@s.whatsapp.net"))
                            {
                                Contact contact = new Contact(0, numb + "@s.whatsapp.net", "", "", entry.Name.GivenName, entry.Name.FamilyName);
                                ContactStore.AddContact(contact);
                            }
                        }
                    }
                }
                feed = GContactService.Query(query);
            }

            //done!
            this.doExit();
        }
        public async Task RefreshContacts(CancellationToken?cancellationToken = null)
        {
            RefreshingContacts = true;
            Contacts.Clear();
            signalContacts.Clear();
            SignalServiceAccountManager accountManager = new SignalServiceAccountManager(App.ServiceUrls, App.Store.Username, App.Store.Password, (int)App.Store.DeviceId, App.USER_AGENT);
            ContactStore contactStore = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AllContactsReadOnly);

            List <PhoneContact> intermediateContacts = new List <PhoneContact>();

            if (contactStore != null)
            {
                HashSet <string> seenNumbers = new HashSet <string>();
                var contacts = await contactStore.FindContactsAsync();

                ContactAnnotationStore contactAnnotationStore = await ContactManager.RequestAnnotationStoreAsync(ContactAnnotationStoreAccessType.AppAnnotationsReadWrite);

                ContactAnnotationList contactAnnotationList;
                var contactAnnotationLists = await contactAnnotationStore.FindAnnotationListsAsync();

                if (contactAnnotationLists.Count == 0)
                {
                    contactAnnotationList = await contactAnnotationStore.CreateAnnotationListAsync();
                }
                else
                {
                    contactAnnotationList = contactAnnotationLists[0];
                }

                foreach (var contact in contacts)
                {
                    var phones = contact.Phones;
                    foreach (var phone in contact.Phones)
                    {
                        if (phone.Kind == ContactPhoneKind.Mobile)
                        {
                            string formattedNumber = null;
                            try
                            {
                                formattedNumber = ParsePhoneNumber(phone.Number);
                            }
                            catch (NumberParseException)
                            {
                                Debug.WriteLine($"Couldn't parse {phone.Number}");
                                continue;
                            }
                            if (!seenNumbers.Contains(formattedNumber))
                            {
                                seenNumbers.Add(formattedNumber);
                                PhoneContact phoneContact = new PhoneContact
                                {
                                    Id          = contact.Id,
                                    Name        = contact.FullName,
                                    PhoneNumber = formattedNumber,
                                    OnSignal    = false
                                };
                                if (contact.SourceDisplayPicture != null)
                                {
                                    using (var stream = await contact.SourceDisplayPicture.OpenReadAsync())
                                    {
                                        BitmapImage bitmapImage = new BitmapImage();
                                        await bitmapImage.SetSourceAsync(stream);

                                        phoneContact.Photo = bitmapImage;
                                    }
                                }
                                intermediateContacts.Add(phoneContact);
                            }
                        }
                    }
                }

                // check if we've annotated a contact as a Signal contact already, if we have we don't need to ask Signal about them
                for (int i = 0; i < intermediateContacts.Count; i++)
                {
                    var annotatedContact = await contactAnnotationList.FindAnnotationsByRemoteIdAsync(intermediateContacts[i].PhoneNumber);

                    if (annotatedContact.Count > 0)
                    {
                        intermediateContacts[i].OnSignal = true;
                        signalContacts.Add(intermediateContacts[i]);
                        intermediateContacts.RemoveAt(i);
                        i--;
                    }
                }

                var signalContactDetails = accountManager.getContacts(intermediateContacts.Select(c => c.PhoneNumber).ToList());
                foreach (var contact in intermediateContacts)
                {
                    var foundContact = signalContactDetails.FirstOrDefault(c => c.getNumber() == contact.PhoneNumber);
                    if (foundContact != null)
                    {
                        contact.OnSignal = true;
                        ContactAnnotation contactAnnotation = new ContactAnnotation();
                        contactAnnotation.ContactId           = contact.Id;
                        contactAnnotation.RemoteId            = contact.PhoneNumber;
                        contactAnnotation.SupportedOperations = ContactAnnotationOperations.Message | ContactAnnotationOperations.ContactProfile;
                        await contactAnnotationList.TrySaveAnnotationAsync(contactAnnotation);

                        signalContacts.Add(contact);
                    }
                }
                Contacts.AddRange(signalContacts);
            }
            else
            {
                ContactsVisible = false;
            }
            RefreshingContacts = false;
        }
        /// <summary>
        /// Loads up the contact store using the contactsRT APIs.
        /// Checks to make sure the store can be loaded and errors out accordingly
        /// </summary>
        private async Task LoadContactsFromStoreAsync()
        {
            //Try loading the contact atore
            try
            {
                store = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AllContactsReadOnly);
            }
            catch (Exception ex)
            {
                ContactsStatusText = "We couldn't load the contact store.";
                Debug.WriteLine("Potential contact store bug: " + ex, "error");
            }

            //If we can access the store without crashing (There seems to be a bug with the store).
            //Check to make sure we actually have access.
            if (store == null)
            {
                //Launch the settings app to fix the security settings
                Debug.WriteLine("Could not open contact store, is app access disabled in privacy settings?", "error");
                return;
            }
            Debug.WriteLine("Contact store opened for reading successfully.", "informational");
            //Load the contacts into the ListView on the page
            ContactReader reader = store.GetContactReader();
            await DisplayContactsFromReaderAsync(reader, true);
            return;
        }
 internal RemoveCommand(ContactStore store, IReadOnlyDictionary <string, string> args)
     : base(Commands.Remove, args, store)
 {
 }
Esempio n. 23
0
        internal async void PickButton_Click(object sender, RoutedEventArgs e)
        {
            if (UIEnabled)
            {
                UIEnabled = false;
                ContactPicker contactPicker = new ContactPicker();
                contactPicker.SelectionMode = ContactSelectionMode.Fields;
                contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);
                var contact = await contactPicker.PickContactAsync();

                if (contact != null)
                {
                    // The contact we just got doesn't contain the contact picture so we need to fetch it
                    // see https://stackoverflow.com/questions/33401625/cant-get-contact-profile-images-in-uwp
                    ContactStore contactStore = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AllContactsReadOnly);

                    // If we do not have access to contacts the ContactStore will be null, we can still use the contact the user
                    // seleceted however
                    if (contactStore != null)
                    {
                        Contact realContact = await contactStore.GetContactAsync(contact.Id);

                        if (realContact.SourceDisplayPicture != null)
                        {
                            using (var stream = await realContact.SourceDisplayPicture.OpenReadAsync())
                            {
                                BitmapImage bitmapImage = new BitmapImage();
                                await bitmapImage.SetSourceAsync(stream);

                                ContactPhoto = bitmapImage;
                            }
                        }
                        else
                        {
                            ContactPhoto = null;
                        }
                    }
                    ContactName = contact.Name;
                    if (contact.Phones.Count > 0)
                    {
                        var originalNumber = contact.Phones[0].Number;
                        if (originalNumber[0] != '+')
                        {
                            // need a better way of determining the "default" country code here
                            var formattedPhoneNumber = PhoneNumberFormatter.FormatE164("1", originalNumber);
                            if (string.IsNullOrEmpty(formattedPhoneNumber))
                            {
                                ContactNumber = originalNumber;
                                MessageDialog message = new MessageDialog("Please format the number in E.164 format.", "Could not format number");
                                await message.ShowAsync();
                            }
                            else
                            {
                                ContactNumber = formattedPhoneNumber;
                            }
                        }
                    }
                }
                UIEnabled = true;
            }
        }
 internal LoadCommand(ContactStore store, IReadOnlyDictionary <string, string> args)
     : base(Commands.Load, args, store)
 {
 }
Esempio n. 25
0
        async protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (contactStore == null)
            {
                contactStore = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite,
                                                                    ContactStoreApplicationAccessMode.ReadOnly);
            }

            remoteIdHelper = new RemoteIdHelper();
            await remoteIdHelper.SetRemoteIdGuid(contactStore);

            App app = Application.Current as App;

            if (app.ReadFile != null)
            {
                Debug.WriteLine("Deleting contacts");
                StatusTextBlock.Text = "Removing old contacts...";
                try
                {
                    await DeleteContacts();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    StatusTextBlock.Text = ex.ToString();
                    return;
                }
                StatusTextBlock.Text = "Reading " + app.ReadFile.Name + "...";
                Debug.WriteLine("Filename is " + app.ReadFile.Name);
                ImportContacts(app.ReadFile);
                if (readDoc == null)
                {
                    return;
                }
                await ParseXmlResponse(readDoc);

                StatusTextBlock.Text = "Import completed.";
                app.ReadFile         = null;
                readDoc = null;
            }
            else if (app.SaveFile != null)
            {
                await GetChanges();

                CachedFileManager.DeferUpdates(app.SaveFile);
                await FileIO.WriteTextAsync(app.SaveFile, xmlContactsFiledata);

                var status = await CachedFileManager.CompleteUpdatesAsync(app.SaveFile);

                app.SaveFile = null;
                if (status == FileUpdateStatus.Complete)
                {
                    StatusTextBlock.Text = "Conacts saved.";
                }
                else
                {
                    StatusTextBlock.Text = "Contacts not saved " + status.ToString();
                }
            }
            else if (app.aborted)
            {
                StatusTextBlock.Text = "Aborted.";
            }
            else
            {
                StatusTextBlock.Text = "";
            }
        }
        public static async Task <TLUserBase> UpdateContactInternalAsync(TLUserBase contact, IFileManager fileManager, ContactStore store, bool updateOrCreate)
        {
            TLUserBase delayedContact = null;
            var        remoteId       = contact.Index.ToString(CultureInfo.InvariantCulture);
            var        phoneContact   = await store.FindContactByRemoteIdAsync(remoteId);

            if (updateOrCreate)
            {
                phoneContact = phoneContact ?? new StoredContact(store);
            }

            if (phoneContact == null)
            {
                return(delayedContact);
            }

            phoneContact.RemoteId   = remoteId;
            phoneContact.GivenName  = contact.FirstName.ToString(); //FirstName
            phoneContact.FamilyName = contact.LastName.ToString();  //LastName

            var userProfilePhoto = contact.Photo as TLUserProfilePhoto;

            if (userProfilePhoto != null)
            {
                var location = userProfilePhoto.PhotoSmall as TLFileLocation;
                if (location != null)
                {
                    var fileName = String.Format("{0}_{1}_{2}.jpg",
                                                 location.VolumeId,
                                                 location.LocalId,
                                                 location.Secret);
                    using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (isoStore.FileExists(fileName))
                        {
                            using (var file = isoStore.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                            {
                                await phoneContact.SetDisplayPictureAsync(file.AsInputStream());
                            }
                        }
                        else
                        {
                            fileManager.DownloadFile(location, userProfilePhoto, new TLInt(0));
                            delayedContact = contact;
                        }
                    }
                }
            }

            var emptyPhoto = contact.Photo as TLPhotoEmpty;

            if (emptyPhoto != null)
            {
                try
                {
                    await phoneContact.SetDisplayPictureAsync(null);
                }
                catch (Exception ex)
                {
                }
            }

            var props = await phoneContact.GetPropertiesAsync();

            var mobilePhone = contact.Phone.ToString();

            if (mobilePhone.Length > 0)
            {
                props[KnownContactProperties.MobileTelephone] = mobilePhone.StartsWith("+")
                    ? mobilePhone
                    : "+" + mobilePhone;
            }

            var usernameContact = contact as IUserName;

            if (usernameContact != null)
            {
                var username = usernameContact.UserName.ToString();

                if (username.Length > 0)
                {
                    props[KnownContactProperties.Nickname] = username;
                }
            }

            await phoneContact.SaveAsync();

            return(delayedContact);
        }
Esempio n. 27
0
 void Instance_OnGetSyncResult(int index, string sid, Dictionary <string, string> existingUsers, string[] failedNumbers)
 {
     ContactStore.OnSyncResult(existingUsers, failedNumbers);
 }
 public CommandFactory(ContactStore store)
 {
     this.store = store;
 }
Esempio n. 29
0
        private async Task ImportAsync(ContactStore store)
        {
            var contacts = await store.FindContactsAsync();

            var importedPhones = new Dictionary <string, Contact>();

            foreach (var contact in contacts)
            {
                foreach (var phone in contact.Phones)
                {
                    importedPhones[phone.Number] = contact;
                }
            }

            var importedPhonesCache = GetImportedPhones();

            var importingContacts = new List <TdWindows.Contact>();
            var importingPhones   = new List <string>();

            foreach (var phone in importedPhones.Keys.Take(1300).ToList())
            {
                if (!importedPhonesCache.ContainsKey(phone))
                {
                    var contact   = importedPhones[phone];
                    var firstName = contact.FirstName ?? string.Empty;
                    var lastName  = contact.LastName ?? string.Empty;

                    if (string.IsNullOrEmpty(firstName) && string.IsNullOrEmpty(lastName))
                    {
                        if (string.IsNullOrEmpty(contact.DisplayName))
                        {
                            continue;
                        }

                        firstName = contact.DisplayName;
                    }

                    if (!string.IsNullOrEmpty(firstName) || !string.IsNullOrEmpty(lastName))
                    {
                        var item = new TdWindows.Contact
                        {
                            PhoneNumber = phone,
                            FirstName   = firstName,
                            LastName    = lastName
                        };

                        importingContacts.Add(item);
                        importingPhones.Add(phone);
                    }
                }
            }

            if (importingContacts.IsEmpty())
            {
                return;
            }

            _protoService.Send(new TdWindows.ImportContacts(importingContacts), result =>
            {
                if (result is TdWindows.ImportedContacts)
                {
                    //_aggregator.Publish(new TLUpdateContactsReset());
                    SaveImportedPhones(importedPhonesCache, importingPhones);
                }
            });
        }
 public AddCommandResult(ContactStore store, ICommand command, IEnumerable <Contact> contacts)
     : base(command, contacts)
 {
     this.store = store;
 }
 protected Command(string verb, IReadOnlyDictionary <string, string> args, ContactStore store)
 {
     Verb  = verb;
     Args  = args;
     Store = store;
 }
 public AddCommand(ContactStore store, IReadOnlyDictionary <string, string> args)
     : base(Commands.Add, args, store)
 {
 }
Esempio n. 33
0
        private async void AddContact(string firstName, string lastName)
        {
            /// https://docs.microsoft.com/en-us/windows/uwp/contacts-and-calendar/integrating-with-contacts
            /// https://stackoverflow.com/questions/34647386/windows-phone-10-is-possible-to-edit-add-new-contact-programmatically-in-wind

            ContactStore contactstore = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AllContactsReadWrite);

            IReadOnlyList <ContactList> contactLists = await contactstore.FindContactListsAsync();


            ContactList lists2 = await contactstore.GetContactListAsync("24,d,d");

            if (lists2 != null)
            {
                var contact1 = new Contact();
                contact1.FirstName = firstName;
                contact1.LastName  = lastName;
                await lists2.SaveContactAsync(contact1);

                return;
            }


            ContactList contactList = null;

            //if there is no contact list we create one
            if (contactLists.Count == 0)
            {
                try
                {
                    contactList = await contactstore.CreateContactListAsync("MyList");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            //otherwise if there is one then we reuse it
            else
            {
                foreach (var c in contactLists)
                {
                    if (c.DisplayName == "MyList")
                    {
                        contactList = c;
                        break;
                    }
                }
            }

            var contact = new Contact();

            contact.FirstName = "Bob";
            contact.LastName  = "Doe";
            ContactEmail email = new ContactEmail();

            email.Address = "*****@*****.**";
            email.Kind    = ContactEmailKind.Other;
            contact.Emails.Add(email);
            await contactList.SaveContactAsync(contact);
        }
Esempio n. 34
0
        private void ContactsList_Load(object sender, EventArgs e)
        {
            string nickname = "WhatsAPINet";

            this.username = this.getUsername();
            this.password = this.GetPassword();

            if (!this.checkCredentials())
            {
                bool validCredentials = false;
                do
                {
                    //throw new Exception("Please enter credentials!");
                    WappCredentials creds = new WappCredentials();
                    DialogResult    r     = creds.ShowDialog();
                    if (r != System.Windows.Forms.DialogResult.OK)
                    {
                        //cancelled, close application
                        Application.Exit();
                        return;
                    }
                    this.username = this.getUsername();
                    this.password = this.GetPassword();
                    if (!string.IsNullOrEmpty(this.username) && !string.IsNullOrEmpty(this.password))
                    {
                        WappSocket.Create(username, password, "WinApp.NET", false);
                        WappSocket.Instance.Connect();
                        WappSocket.Instance.Login();
                        if (WappSocket.Instance.ConnectionStatus == WhatsAppApi.WhatsApp.CONNECTION_STATUS.LOGGEDIN)
                        {
                            validCredentials = true;
                            //write to config
                            Configuration      config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                            AppSettingsSection app    = config.AppSettings;
                            app.Settings.Remove("Username");
                            app.Settings.Add("Username", this.username);
                            app.Settings.Remove("Password");
                            app.Settings.Add("Password", this.password);
                            config.Save(ConfigurationSaveMode.Modified);
                        }
                        else
                        {
                            WappSocket.Instance.Disconnect();
                        }
                    }
                } while (!validCredentials);
            }
            ContactStore.CheckTable();
            MessageStore.CheckTable();

            WappSocket.Create(this.username, this.password, nickname, true);
            WappSocket.Instance.Connect();
            WappSocket.Instance.Login();
            WappSocket.Instance.sendNickname(nickname);

            WAlistener = new Thread(new ThreadStart(Listen));
            WAlistener.IsBackground = true;
            WAlistener.Start();

            //this.SyncWaContactsAsync();
            Thread t = new Thread(new ThreadStart(SyncWaContactsAsync));

            t.IsBackground = true;
            t.Start();

            Thread alive = new Thread(new ThreadStart(KeepAlive));

            alive.IsBackground = true;
            alive.Start();

            int vertScrollWidth = SystemInformation.VerticalScrollBarWidth;

            this.flowLayoutPanel1.Padding = new Padding(0, 0, vertScrollWidth, 0);
        }
        public async Task RefreshContacts()
        {
            CancellationTokenSource cancelSource = new CancellationTokenSource();

            RefreshingContacts = true;
            Contacts.Clear();
            signalContacts.Clear();
            ContactStore contactStore = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AllContactsReadOnly);

            List <PhoneContact> intermediateContacts = new List <PhoneContact>();

            if (contactStore != null)
            {
                HashSet <string> seenNumbers = new HashSet <string>();
                var contacts = await contactStore.FindContactsAsync();

                ContactAnnotationStore contactAnnotationStore = await ContactManager.RequestAnnotationStoreAsync(ContactAnnotationStoreAccessType.AppAnnotationsReadWrite);

                ContactAnnotationList contactAnnotationList;
                var contactAnnotationLists = await contactAnnotationStore.FindAnnotationListsAsync();

                if (contactAnnotationLists.Count == 0)
                {
                    contactAnnotationList = await contactAnnotationStore.CreateAnnotationListAsync();
                }
                else
                {
                    contactAnnotationList = contactAnnotationLists[0];
                }

                foreach (var contact in contacts)
                {
                    var phones = contact.Phones;
                    foreach (var phone in contact.Phones)
                    {
                        if (phone.Kind == ContactPhoneKind.Mobile)
                        {
                            string formattedNumber = null;
                            try
                            {
                                formattedNumber = ParsePhoneNumber(phone.Number);
                            }
                            catch (NumberParseException)
                            {
                                Logger.LogDebug("RefreshContacts() could not parse number");
                                continue;
                            }
                            if (!seenNumbers.Contains(formattedNumber))
                            {
                                seenNumbers.Add(formattedNumber);
                                PhoneContact phoneContact = new PhoneContact
                                {
                                    Id          = contact.Id,
                                    Name        = contact.FullName,
                                    PhoneNumber = formattedNumber,
                                    OnSignal    = false
                                };
                                if (contact.SourceDisplayPicture != null)
                                {
                                    using (var stream = await contact.SourceDisplayPicture.OpenReadAsync())
                                    {
                                        BitmapImage bitmapImage = new BitmapImage();
                                        await bitmapImage.SetSourceAsync(stream);

                                        phoneContact.Photo = bitmapImage;
                                    }
                                }
                                intermediateContacts.Add(phoneContact);
                            }
                        }
                    }
                }

                // check if we've annotated a contact as a Signal contact already, if we have we don't need to ask Signal about them
                for (int i = 0; i < intermediateContacts.Count; i++)
                {
                    var annotatedContact = await contactAnnotationList.FindAnnotationsByRemoteIdAsync(intermediateContacts[i].PhoneNumber);

                    if (annotatedContact.Count > 0)
                    {
                        intermediateContacts[i].OnSignal = true;
                        signalContacts.Add(intermediateContacts[i]);
                        intermediateContacts.RemoveAt(i);
                        i--;
                    }
                }

                List <string> intermediateContactPhoneNumbers = intermediateContacts.Select(c => c.PhoneNumber).ToList();
                var           registeredUsers = await accountManager.GetRegisteredUsersAsync(intermediateContactPhoneNumbers, LibUtils.SignalSettings.ContactDiscoveryServiceEnclaveId, cancelSource.Token);

                foreach (var contact in intermediateContacts)
                {
                    var foundContact = registeredUsers.FirstOrDefault(c => c.Key == contact.PhoneNumber);
                    if (!string.IsNullOrEmpty(foundContact.Key))
                    {
                        contact.OnSignal   = true;
                        contact.SignalGuid = foundContact.Value;
                        ContactAnnotation contactAnnotation = new ContactAnnotation
                        {
                            ContactId           = contact.Id,
                            RemoteId            = contact.PhoneNumber,
                            SupportedOperations = ContactAnnotationOperations.Message | ContactAnnotationOperations.ContactProfile
                        };
                        contactAnnotation.ProviderProperties.Add(nameof(contact.SignalGuid), foundContact.Value);
                        await contactAnnotationList.TrySaveAnnotationAsync(contactAnnotation);

                        signalContacts.Add(contact);
                    }
                }
                Contacts.AddRange(signalContacts);
            }
            else
            {
                ContactsVisible = false;
            }
            RefreshingContacts = false;
        }
Esempio n. 36
0
        private async Task <StoredContact> ToStoredContact(StoredContact contact)
        {
            if (contact == null)
            {
                ContactStore contactStore = await ContactStore.CreateOrOpenAsync(
                    ContactStoreSystemAccessMode.ReadWrite,
                    ContactStoreApplicationAccessMode.ReadOnly);

                contact = new StoredContact(contactStore);
            }

            IDictionary <string, object> properties = await contact.GetPropertiesAsync();

            // Address
            if (Addresses != null && Addresses.Count > 0)
            {
                Addresses.ForEach(address => address.AsStoredContactProperties(ref properties));
            }

            // Birthday
            if (W3ContactBirthday != null)
            {
                W3ContactBirthday.AsStoredContactProperties(ref properties);
            }

            // Emails
            if (Emails != null && Emails.Count > 0)
            {
                Emails.ForEach(email => email.AsStoredContactProperties(ref properties));
            }

            // Name
            if (Name != null)
            {
                Name.AsStoredContactProperties(ref properties);
            }

            // NickName
            if (W3ContactNickName != null)
            {
                W3ContactNickName.AsStoredContactProperties(ref properties);
            }

            // Note
            if (W3ContactNotes != null)
            {
                W3ContactNotes.AsStoredContactProperties(ref properties);
            }

            // Organization
            if (Organization != null)
            {
                Organization.AsStoredContactProperties(ref properties);
            }

            // Phones
            if (Phones != null && Phones.Count > 0)
            {
                Phones.ForEach(phone => phone.AsStoredContactProperties(ref properties));
            }

            // Photos
            if (Photos != null && Photos.Count > 0)
            {
                W3ContactPhoto firstPhoto = Photos.FirstOrDefault();
                if (firstPhoto != null)
                {
                    await firstPhoto.SetPictureOnStoredContactAsync(contact);
                }
            }

            // Urls
            if (Urls != null && Urls.Count > 0)
            {
                Urls.ForEach(url => url.AsStoredContactProperties(ref properties));
            }

            return(contact);
        }
Esempio n. 37
0
        private async Task <ContactList> GetContactListAsync(UserDataAccount userDataAccount, ContactStore store)
        {
            try
            {
                var user        = _cacheService.GetUser(_cacheService.Options.MyId);
                var displayName = user?.GetFullName() ?? "Unigram";

                ContactList contactList = null;
                if (_cacheService.Options.TryGetValue("x_contact_list", out string id))
                {
                    contactList = await store.GetContactListAsync(id);
                }

                if (contactList == null)
                {
                    contactList = await store.CreateContactListAsync(displayName, userDataAccount.Id);

                    await _protoService.SendAsync(new Telegram.Td.Api.SetOption("x_contact_list", new Telegram.Td.Api.OptionValueString(contactList.Id)));
                }

                contactList.DisplayName         = displayName;
                contactList.OtherAppWriteAccess = ContactListOtherAppWriteAccess.None;
                await contactList.SaveAsync();

                return(contactList);
            }
            catch
            {
                return(null);
            }
        }
        async private void selectContact_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ContactPicker contactPicker = new ContactPicker();
                contactPicker.CommitButtonText = "Select";
                contactPicker.SelectionMode    = ContactSelectionMode.Contacts;
                Contact tmp = await contactPicker.PickContactAsync();

                if (tmp == null)
                {
                    status.Log(LocalizableStrings.CONTACTS_NO_CONTACT_SELECTED);
                    return;
                }
                status.Log(LocalizableStrings.CONTACTS_CONTACT_SELECTED);

                ContactStore store = await ContactManager.RequestStoreAsync();

                // BUG on Desktop tmp.Id is an empty string.
                Debug.WriteLine(tmp.Id);
                if (string.IsNullOrEmpty(tmp.Id))
                {
                    status.Log(LocalizableStrings.CONTACTS_NO_CONTACT_DETAILS);
                    return;
                }

                Contact contact = await store.GetContactAsync(tmp.Id);

                if (contact == null)
                {
                    status.Log(LocalizableStrings.CONTACTS_NO_CONTACT_DETAILS);
                    return;
                }
                status.Log(LocalizableStrings.CONTACTS_CONTACT_DETAILS_FOUND);

                BitmapImage bitmap = null;
                if (contact.Thumbnail != null)
                {
                    IRandomAccessStreamWithContentType stream = await contact.Thumbnail.OpenReadAsync();

                    if (stream != null && stream.Size > 0)
                    {
                        bitmap = new BitmapImage();
                        bitmap.SetSource(stream);
                    }
                }
                thumbnail.Source = bitmap;

                string name = contact.DisplayName;
                if (!string.IsNullOrEmpty(name))
                {
                    contactName.Text = name;
                }

                ContactEmail email = contact.Emails.FirstOrDefault();
                if (email != null)
                {
                    contactEmail.Text = email.Address;
                }

                ContactPhone phone = contact.Phones.FirstOrDefault();
                if (phone != null)
                {
                    contactPhone.Text = phone.Number;
                }

                ContactAddress address = contact.Addresses.FirstOrDefault();
                if (address != null)
                {
                    contactAddress.Text = address.StreetAddress;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                status.Log(ex.Message);
            }
        }
Esempio n. 39
0
        public static async void SyncContacts()
        {
            ContactList contactList;

            //CleanUp
            {
                ContactStore store = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite);

                IReadOnlyList <ContactList> contactLists = await store.FindContactListsAsync();

                if (contactLists.Count > 0)
                {
                    await contactLists[0].DeleteAsync();
                }

                contactList = await store.CreateContactListAsync("Lite Messenger");
            }

            ContactAnnotationList annotationList;

            {
                ContactAnnotationStore annotationStore = await
                                                         ContactManager.RequestAnnotationStoreAsync(ContactAnnotationStoreAccessType.AppAnnotationsReadWrite);


                IReadOnlyList <ContactAnnotationList> annotationLists = await annotationStore.FindAnnotationListsAsync();

                if (annotationLists.Count > 0)
                {
                    await annotationLists[0].DeleteAsync();
                }

                annotationList = await annotationStore.CreateAnnotationListAsync();
            }


            String appId = "4a6ce7f5-f418-4ba8-8836-c06d77ab735d_g91sr9nghxvmm!App";

            foreach (var chatHeader in Names)
            {
                //if (chatHeader.IsGroup)
                //    continue;
                Contact contact = new Contact
                {
                    FirstName = chatHeader.Name,
                    RemoteId  = chatHeader.Href
                };
                await contactList.SaveContactAsync(contact);

                ContactAnnotation annotation = new ContactAnnotation
                {
                    ContactId           = contact.Id,
                    RemoteId            = chatHeader.Href,
                    SupportedOperations = ContactAnnotationOperations.Message
                };


                if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 5))
                {
                    annotation.ProviderProperties.Add("ContactPanelAppID", appId);
                    annotation.SupportedOperations = ContactAnnotationOperations.Message | ContactAnnotationOperations.ContactProfile;
                }
                await annotationList.TrySaveAnnotationAsync(annotation);
            }
        }
Esempio n. 40
0
        public async void AddContact(string remoteId, string givenName, string familyName, string username, String avatar, String url)
        {
            ContactStore store = await ContactStore.CreateOrOpenAsync();

            try
            {
                if (await store.FindContactByRemoteIdAsync(remoteId) == null)
                {
                    StoredContact contact = new StoredContact(store);

                    contact.RemoteId = remoteId;


                    contact.GivenName  = givenName;
                    contact.FamilyName = familyName;

                    contact.DisplayName = remoteId;


                    HttpWebRequest  request     = (HttpWebRequest)WebRequest.Create(new Uri(avatar));
                    HttpWebResponse webResponse = await request.GetResponseAsync() as HttpWebResponse;

                    MemoryStream memoryStream = new MemoryStream();
                    webResponse.GetResponseStream().CopyTo(memoryStream);
                    IRandomAccessStream stream = await ConvertToRandomAccessStream(memoryStream);

                    IDictionary <string, object> props = await contact.GetPropertiesAsync();

                    props.Add(KnownContactProperties.Nickname, username);
                    props.Add(KnownContactProperties.Url, url);



                    IDictionary <string, object> extprops = await contact.GetExtendedPropertiesAsync();

                    extprops.Add("Codename", username);
                    extprops.Add("ProfilePic", avatar);


                    await contact.SetDisplayPictureAsync(stream);

                    await contact.SaveAsync();
                }
                else
                {
                    StoredContact contact = await store.FindContactByRemoteIdAsync(remoteId);

                    IDictionary <string, object> extprops = await contact.GetExtendedPropertiesAsync();

                    if (!extprops.Values.Contains(avatar))
                    {
                        HttpWebRequest  request     = (HttpWebRequest)WebRequest.Create(new Uri(avatar));
                        HttpWebResponse webResponse = await request.GetResponseAsync() as HttpWebResponse;

                        MemoryStream memoryStream = new MemoryStream();
                        webResponse.GetResponseStream().CopyTo(memoryStream);
                        IRandomAccessStream stream = await ConvertToRandomAccessStream(memoryStream);

                        await contact.SetDisplayPictureAsync(stream);

                        extprops.Remove("ProfilePic");
                        extprops.Add("ProfilePic", avatar);

                        await contact.SaveAsync();
                    }
                }
            }
            catch (WebException) { }
        }
Esempio n. 41
0
        public async Task SyncContactsAsync(List <User> friendsList)
        {
            if (!this._synching && !this._deleting)
            {
                this._synching = true;
                friendsList    = Enumerable.ToList <User>(Enumerable.Take <User>(friendsList, ContactsManager.MAX_FRIENDS_TO_SYNC));
                long loggedInUserId = AppGlobalStateManager.Current.LoggedInUserId;
                try
                {
                    SavedContacts savedContacts = await this.GetSavedList();

                    SavedContacts       savedContacts2 = savedContacts;
                    List <User>         list           = savedContacts2.SavedUsers;
                    List <User>         arg_1E7_0      = list;
                    List <User>         arg_1E7_1      = friendsList;
                    Func <User, string> arg_1E7_2      = new Func <User, string>((u) => { return(u.uid.ToString()); });

                    Func <User, User, bool> arg_1E7_3 = new Func <User, User, bool>((u1, u2) =>
                    {
                        return(ContactsManager.AreStringsEqualOrNullEmpty(u1.first_name, u2.first_name) && ContactsManager.AreStringsEqualOrNullEmpty(u1.last_name, u2.last_name) && ContactsManager.AreStringsEqualOrNullEmpty(u1.mobile_phone, u2.mobile_phone) && ContactsManager.AreStringsEqualOrNullEmpty(u1.home_phone, u2.home_phone) && ContactsManager.AreStringsEqualOrNullEmpty(u1.site, u2.site) && ContactsManager.AreStringsEqualOrNullEmpty(u1.bdate, u2.bdate) && ContactsManager.AreStringsEqualOrNullEmpty(u1.photo_max, u2.photo_max));
                    });

                    List <Tuple <User, User> > list2;
                    List <User> list3;
                    List <User> list4;
                    ListUtils.GetListChanges <User>(arg_1E7_0, arg_1E7_1, arg_1E7_2, arg_1E7_3, out list2, out list3, out list4);
                    Logger.Instance.Info("ContactsManager got {0} updated users, {1} new users, {2} deleted users", new object[]
                    {
                        list2.Count,
                        list3.Count,
                        list4.Count
                    });
                    int count = list3.Count;
                    int num   = 0;
                    if (loggedInUserId != AppGlobalStateManager.Current.LoggedInUserId || !AppGlobalStateManager.Current.GlobalState.SyncContacts)
                    {
                        await this.DoDeleteAllContactsAsync();
                    }
                    else
                    {
                        ContactStore contactStore = await ContactStore.CreateOrOpenAsync();

                        await this.EnsureProvisioned(contactStore);

                        StoredContact storedContact = await contactStore.FindContactByRemoteIdAsync(ContactsManager.GetRemoteId(AppGlobalStateManager.Current.GlobalState.LoggedInUser));

                        if (storedContact != null)
                        {
                            await this.SetContactProperties(storedContact, AppGlobalStateManager.Current.GlobalState.LoggedInUser, null);

                            await storedContact.SaveAsync();
                        }
                        contactStore.CreateContactQuery();
                        List <Tuple <User, User> > .Enumerator enumerator = list2.GetEnumerator();
                        //int num2;
                        try
                        {
                            while (enumerator.MoveNext())
                            {
                                Tuple <User, User> var_8_57F = enumerator.Current;
                                User user         = var_8_57F.Item2;
                                User originalUser = var_8_57F.Item1;
                                if (loggedInUserId != AppGlobalStateManager.Current.LoggedInUserId || !AppGlobalStateManager.Current.GlobalState.SyncContacts)
                                {
                                    await this.DoDeleteAllContactsAsync();

                                    return;
                                }
                                try
                                {
                                    StoredContact storedContact2 = await contactStore.FindContactByRemoteIdAsync(ContactsManager.GetRemoteId(user));

                                    await this.SetContactProperties(storedContact2, user, originalUser);

                                    if (storedContact2 != null)
                                    {
                                        await storedContact2.SaveAsync();
                                    }
                                    storedContact2 = null;
                                }
                                catch (Exception var_9_7B5)
                                {
                                    Logger.Instance.Error("Failed to update contact for user " + user.Name, var_9_7B5);
                                }
                                user         = null;
                                originalUser = null;
                            }
                        }
                        finally
                        {
                            //if (num2 < 0)
                            //{
                            enumerator.Dispose();
                            //}
                        }
                        enumerator = default(List <Tuple <User, User> > .Enumerator);
                        List <User> .Enumerator enumerator2 = list3.GetEnumerator();
                        try
                        {
                            while (enumerator2.MoveNext())
                            {
                                User user2 = enumerator2.Current;
                                num++;
                                if (loggedInUserId != AppGlobalStateManager.Current.LoggedInUserId || !AppGlobalStateManager.Current.GlobalState.SyncContacts)
                                {
                                    await this.DoDeleteAllContactsAsync();

                                    return;
                                }
                                try
                                {
                                    if (await contactStore.FindContactByRemoteIdAsync(ContactsManager.GetRemoteId(user2)) == null)//todo:bug?
                                    {
                                        Stopwatch stopwatch = Stopwatch.StartNew();
                                        this.FireSyncStatusChanged(num, count);
                                        Logger.Instance.Info("ContactsManager begin creating user", new object[0]);
                                        StoredContact storedContact3 = new StoredContact(contactStore);
                                        await this.SetContactProperties(storedContact3, user2, null);

                                        await storedContact3.SaveAsync();

                                        Logger.Instance.Info("ContactsManager end creating user", new object[0]);
                                        stopwatch.Stop();
                                        long var_11_AF3 = 500L - stopwatch.ElapsedMilliseconds;
                                        if (var_11_AF3 > 0L)
                                        {
                                            await Task.Delay((int)var_11_AF3);
                                        }
                                        stopwatch      = null;
                                        storedContact3 = null;
                                    }
                                    list.Add(user2);
                                }
                                catch (Exception var_12_B82)
                                {
                                    Logger.Instance.Error("Failed to create contact for user " + user2.Name, var_12_B82);
                                }
                                user2 = null;
                            }
                        }
                        finally
                        {
                            //if (num2 < 0)
                            //{
                            enumerator2.Dispose();
                            //}
                        }
                        enumerator2 = default(List <User> .Enumerator);
                        enumerator2 = list4.GetEnumerator();
                        try
                        {
                            while (enumerator2.MoveNext())
                            {
                                User user3 = enumerator2.Current;
                                if (loggedInUserId != AppGlobalStateManager.Current.LoggedInUserId || !AppGlobalStateManager.Current.GlobalState.SyncContacts)
                                {
                                    await this.DoDeleteAllContactsAsync();

                                    return;
                                }
                                try
                                {
                                    StoredContact var_13_D35 = await contactStore.FindContactByRemoteIdAsync(ContactsManager.GetRemoteId(user3));

                                    if (var_13_D35 != null)
                                    {
                                        await contactStore.DeleteContactAsync(var_13_D35.Id);
                                    }
                                    list.Remove(user3);
                                }
                                catch (Exception var_14_DBF)
                                {
                                    Logger.Instance.Error("Failed to delete contact for user " + user3.Name, var_14_DBF);
                                }
                                user3 = null;
                            }
                        }
                        finally
                        {
                            //if (num2 < 0)
                            //{
                            enumerator2.Dispose();
                            //}
                        }
                        enumerator2 = default(List <User> .Enumerator);
                        savedContacts2.SyncedDate = DateTime.UtcNow;
                        await this.EnsurePersistSavedContactsAsync();

                        savedContacts2 = null;
                        list           = null;
                        list4          = null;
                        list3          = null;
                        list2          = null;
                        contactStore   = null;
                        storedContact  = null;
                    }
                }
                catch (Exception var_15_ECB)
                {
                    Logger.Instance.Error("Failed to sync contacts. ", var_15_ECB);
                }
                finally
                {
                    //int num2;
                    //if (num2 < 0)
                    //{
                    this._synching = false;
                    this.FireSyncStatusChanged(0, 0);
                    //}
                }
            }
        }
Esempio n. 42
0
 /// <summary>
 /// Handle if contact changed.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private void Store_ContactChanged(ContactStore sender, ContactChangedEventArgs args)
 {
     // throw new NotImplementedException();
 }
 public ContactStoreEvents(ContactStore This)
 {
     this.This = This;
 }
Esempio n. 44
0
    public async Task CheckForContactStore()
    {
      if (ContactStore != null)
        return;

      ContactStore = await ContactStore.CreateOrOpenAsync(
                              ContactStoreSystemAccessMode.ReadWrite, 
                              ContactStoreApplicationAccessMode.ReadOnly);

      // Unique Id für Contact-Save setzen
      await _remoteIdHelper.TrySetRemoteIdGuid(ContactStore);
    }
Esempio n. 45
0
 void ProcessGroupChat()
 {
     this.Text = "Group chat " + ContactStore.GetContactByJid(this.target).ToString();
     WappSocket.Instance.SendGetGroupInfo(this.target);
 }
Esempio n. 46
0
        /// <summary>
        /// Invoke the method specified by the
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </summary>
        /// <param name="message">
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </param>
        internal async override void InvokeAsync(JSMessage message)
        {
            string        callbackId = message.CallbackId;
            List <string> properties = null;

            try
            {
                switch (message.Method)
                {
                case "callContact":

                    Logger.Info("Calling contact...");

                    // Get the phone number
                    string phonenumber = message.Args[0] as string;

                    // Create and show the PhoneCall task
                    PhoneCallTask phoneCallTask = new PhoneCallTask();
                    phoneCallTask.PhoneNumber = phonenumber;
                    UiDispatcher.BeginInvoke(() =>
                    {
                        phoneCallTask.Show();
                    });

                    // Set app navigated to external page
                    Mowbly.AppNavigatedToExternalPage = true;
                    break;

                case "deleteContact":

                    Logger.Info("Deleting contact...");

                    string contactId = message.Args[0] as string;

                    try
                    {
                        ContactStore contactStore = await ContactStore.CreateOrOpenAsync(
                            ContactStoreSystemAccessMode.ReadWrite,
                            ContactStoreApplicationAccessMode.ReadOnly);

                        await contactStore.DeleteContactAsync(contactId);

                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        string error = String.Concat(
                            Mowbly.GetString(Constants.STRING_CONTACT_DELETE_ERROR),
                            e.Message);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code  = MethodResult.FAILURE_CODE,
                            Error = new MethodError
                            {
                                Message = error
                            }
                        });
                    }
                    break;

                case "findContact":

                    // Read args
                    string filter  = message.Args[0] as string;
                    JToken options = message.Args[1] as JToken;
                    properties = options["properties"].ToObject <List <string> >();
                    double limit = (double)options["limit"];

                    Logger.Info("Searching contacts for " + filter);

                    // Contacts search results handler
                    EventHandler <MowblyContactsSearchEventArgs> OnContactsSearchCompleted = null;
                    OnContactsSearchCompleted = (sender, e) =>
                    {
                        if (e.Status)
                        {
                            // Notify result to JS
                            InvokeCallbackJavascript(message.CallbackId, new MethodResult {
                                Result = e.W3Contacts
                            });
                        }
                        else
                        {
                            InvokeCallbackJavascript(message.CallbackId, new MethodResult {
                                Result = null
                            });
                        }
                    };

                    if (Regex.IsMatch(filter, @"^[0-9()-]+$"))
                    {
                        // Only numbers, search by phone number
                        SearchContactInUserDataAsync(filter, OnContactsSearchCompleted, true, FilterKind.PhoneNumber, limit, properties);
                    }
                    else
                    {
                        // Search by display name
                        SearchContactInUserDataAsync(filter, OnContactsSearchCompleted, true, FilterKind.DisplayName, limit, properties);
                    }
                    break;

                case "pickContact":


                    properties = ((JToken)message.Args[0]).ToObject <List <string> >();
                    ContactChooserTask contactChooserTask = new ContactChooserTask(callbackId);
                    EventHandler <ContactChooserTaskEventArgs> OnContactChooserTaskCompleted = null;
                    OnContactChooserTaskCompleted = (sender, e) =>
                    {
                        // Unsubscribe
                        contactChooserTask.OnCompleted -= OnContactChooserTaskCompleted;

                        // Notify result to JS
                        if (e.Contact != null)
                        {
                            W3Contact contact = new W3Contact(e.Contact, properties);
                            InvokeCallbackJavascript(e.CallbackId, new MethodResult {
                                Result = contact
                            });
                        }
                        else
                        {
                            InvokeCallbackJavascript(e.CallbackId, new MethodResult
                            {
                                Code  = MethodResult.FAILURE_CODE,
                                Error = new MethodError
                                {
                                    Message = Mowbly.GetString(Constants.STRING_ACTIVITY_CANCELLED)
                                }
                            });
                        }
                    };

                    // Subscribe to OnCompleted event
                    contactChooserTask.OnCompleted += OnContactChooserTaskCompleted;

                    // Show contact chooser task
                    UiDispatcher.BeginInvoke(() =>
                    {
                        try
                        {
                            contactChooserTask.Show();
                        }
                        catch (Exception e)
                        {
                            // Might fail at times since navigation is not allowed when task is not in foreground
                            string error = String.Concat(Mowbly.GetString(Constants.STRING_CONTACT_CHOOSE_FAILED), e.Message);
                            Logger.Error(error);
                            InvokeCallbackJavascript(callbackId, new MethodResult
                            {
                                Code  = MethodResult.FAILURE_CODE,
                                Error = new MethodError
                                {
                                    Message = error
                                }
                            });
                        }
                    });
                    break;

                case "saveContact":

                    try
                    {
                        // Create W3Contact object from JS contact
                        W3Contact w3Contact       = JsonConvert.DeserializeObject <W3Contact>(message.Args[0].ToString());
                        string    storedContactId = await w3Contact.SaveToNativeContactStore();

                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Result = storedContactId
                        });
                    }
                    catch (Exception e)
                    {
                        string error = String.Concat(Mowbly.GetString(Constants.STRING_CONTACT_SAVE_FAILED), e.Message);
                        Logger.Error(error);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code  = MethodResult.FAILURE_CODE,
                            Error = new MethodError
                            {
                                Message = error
                            }
                        });
                    }

                    break;

                case "viewContact":

                    // Get the param and type
                    string id = message.Args[0] as string;
                    Tuple <string, string> paramAndType = await GetSearchParamAndType(id);

                    if (paramAndType != null)
                    {
                        string            param             = paramAndType.Item1;
                        string            type              = paramAndType.Item2;
                        ContactViewerTask contactViewerTask = new ContactViewerTask(param, type);

                        // Show contact viewer task
                        UiDispatcher.BeginInvoke(() =>
                        {
                            try
                            {
                                contactViewerTask.Show();
                            }
                            catch (Exception e)
                            {
                                // Might fail at times since navigation is not allowed when task is not in foreground
                                string error = String.Concat(Mowbly.GetString(Constants.STRING_CONTACT_VIEW_FAILED), e.Message);
                                Logger.Error(error);
                                InvokeCallbackJavascript(callbackId, new MethodResult
                                {
                                    Code  = MethodResult.FAILURE_CODE,
                                    Error = new MethodError
                                    {
                                        Message = error
                                    }
                                });
                            }
                        });
                    }
                    else
                    {
                        string error = String.Concat(Mowbly.GetString(Constants.STRING_CONTACT_VIEW_FAILED),
                                                     Mowbly.GetString(Constants.STRING_CONTACT_NOT_FOUND));
                        Logger.Error(error);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code  = MethodResult.FAILURE_CODE,
                            Error = new MethodError
                            {
                                Message = error
                            }
                        });
                    }

                    break;

                default:
                    Logger.Error("Feature " + Name + " does not support method " + message.Method);
                    break;
                }
            }
            catch (Exception e)
            {
                Logger.Error("Exception occured. Reason - " + e.Message);
            }
        }
Esempio n. 47
0
 public async Task StartService()
 {
     _store = await ContactStore.CreateOrOpenAsync();
 }