static public async Task <ChadderSQLMainDB> GetDatabase(int instanceId)
        {
            if (Instances.ContainsKey(instanceId))
            {
                return(Instances[instanceId]);
            }
            var db = new ChadderSQLMainDB(instanceId);

            Instances[instanceId] = db;

            try
            {
                await db.CreateTableAsync <ChadderLocalDeviceInfo>();

                await db.CreateTableAsync <ChadderLocalUserRecord>();

                await db.SetVersion(1);

                return(db);
            }
            catch (Exception ex)
            {
                Insight.Report(ex);
                db.Close();
                throw;
            }
        }
        protected async Task SendPendingMessages()
        {
            ChadderMessage msg = null;

            try
            {
                var backoff = new ExponentialBackoff(1000, 5000);
                while (PendingMessages.Count > 0)
                {
                    if (PendingMessages.TryPeek(out msg) && msg.Status != ChadderMessage.MESSAGE_STATUS.SENT)
                    {
                        var conversation = db.GetConversation(msg.ConversationId);
                        if (await SendMessageToServer(msg, conversation) == ChadderError.OK)
                        {
                            while (PendingMessages.TryDequeue(out msg))
                            {
                                ;
                            }
                            backoff.Reset();
                        }
                        else
                        {
                            await backoff.Failed();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Insight.Track("SendPendingMessages safe try-catch");
                Insight.Report(ex);
            }
            SendPendingMessagesTask = null;
        }
        /// <summary>
        /// Connects the SignalR Hub
        /// </summary>
        /// <returns></returns>
        public async Task <bool> Connect()
        {
            try
            {
                ShouldBeConnected = true;
                var holder = Insight.StartTimer("Connection timer");
                if (Token != null)
                {
                    HubConnection.Headers["Authorization"] = "Bearer " + Token;
                }
                await HubConnection.Start();

                Insight.StopTimer(holder);
                Insight.Track("HUB - Connected using " + HubConnection.Transport.Name);
                ConnectTimer.Reset();
                return(true);
            }
            catch (HttpClientException ex)
            {
                Insight.Report(ex);
                ex.Response.Content.ReadAsStringAsync().ContinueWith((r) =>
                {
                    Insight.Track(r.Result);
                });
            }
            catch
            {
            }
            return(false);
        }
Exemple #4
0
        static public async Task <ChadderSQLUserDB> GetUserDatabase(string userId, byte[] password, int instanceId)
        {
            var db = new ChadderSQLUserDB(GetFilePath(userId, instanceId), password);

            try
            {
                await db.CreateTableAsync <ChadderLocalUserInfo>();

                await db.CreateTableAsync <ChadderContact>();

                await db.CreateTableAsync <ChadderConversation>();

                await db.CreateTableAsync <ChadderMessage>();

                await db.CreateTableAsync <ChadderSQLPicture>();

                await db.CreateTableAsync <ChadderUserDevice>();

                var oldVersion = await db.GetVersion();

                await db.Migrate(oldVersion);

                return(db);
            }
            catch (Exception ex)
            {
                Insight.Report(ex);
                db.Close();
                throw;
            }
        }
        protected override void InvalidateData()
        {
            base.InvalidateData();
            if (Profile == null)
            {
                return;
            }
            try
            {
                username.Text       = Profile.Username;
                profileName.Text    = Profile.Name;
                keyFingerprint.Text = Profile.PublicKeyBook.GetMaster().FingerprintEncodedClipped;
                imgProfile.SetImageDrawable(new CircleDrawable(Profile.Picture.Image));

                if (Profile.KeyStatus == Data.PublicKeyStatus.VERIFIED)
                {
                    txtFingerprintStatus.Text = "Verified";
                }
                else if (Profile.KeyStatus == Data.PublicKeyStatus.NOT_VERIFIED)
                {
                    txtFingerprintStatus.Text = "Not Verified";
                }
                else
                {
                    txtFingerprintStatus.TextFormatted = Html.FromHtml("<b>Wrong</b>");
                }


                Activity.InvalidateOptionsMenu();
            }
            catch (Exception ex)
            {
                Insight.Report(ex);
            }
        }
 //++public static void ShareFacebook(Activity Activity, UiLifecycleHelper uiHelper)
 public static void ShareFacebook(Activity Activity)
 {
     try
     {
         //if (FacebookDialog.CanPresentShareDialog(Activity.ApplicationContext, FacebookDialog.ShareDialogFeature.ShareDialog))
         //{
         //    FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(Activity)
         //    .SetLink(Activity.GetString(Resource.String.ProfileFacebookShareLink))
         //    .SetName(Activity.GetString(Resource.String.ProfileFacebookShareName))
         //    .Build();
         //    uiHelper.TrackPendingDialogCall(shareDialog.Present());
         //}
         //else
         //{
         //    var param = new Bundle();
         //    param.PutString("name", Activity.GetString(Resource.String.ProfileFacebookShareName));
         //    param.PutString("link", Activity.GetString(Resource.String.ProfileFacebookShareLink));
         //    var feedDialog = new WebDialog.FeedDialogBuilder(Activity, Activity.GetString(Resource.String.app_id), param).Build(); ;
         //    feedDialog.Complete += delegate
         //    {
         //        feedDialog.Dismiss();
         //    };
         //    feedDialog.Show();
         //}
     }
     catch (Exception ex)
     {
         Insight.Report(ex);
         Toast.MakeText(Activity, "Unable to share on facebook", ToastLength.Long).Show();
     }
 }
Exemple #7
0
        public async Task <ChadderError> PairDevice(ChadderUserDevice device)
        {
            try
            {
                var package = new PairDeviceContent()
                {
                    Book = db.LocalUser.PrivateKeyBook
                };
                var content = await EncryptForDevice(package, device);

                var request = new PairDeviceParameters()
                {
                    DeviceId = device.DeviceId,
                    Data     = content.Serialize()
                };
                var result = await AuthorizedRequest <BasicResponse <string> >(Connection.AccountHub, "PairDevice", request);

                if (result.Error == ChadderError.OK)
                {
                    device.HasUserKey = true;
                    await sqlDB.UpdateAsync(device);
                }
                return(result.Error);
            }
            catch (Exception ex)
            {
                Insight.Report(ex);
                return(ChadderError.GENERAL_EXCEPTION);
            }
        }
Exemple #8
0
        public async Task <ChadderError> GetPackages()
        {
            var result = await AuthorizedRequest <BasicArrayResponse <Package> >(Connection.AccountHub, "GetPackages", db.LocalUser.LastPackage);

            if (result.Error == ChadderError.OK)
            {
                bool noException = true; // if there is only 1 package and it crashes it will end up on infinite loop.
                foreach (var p in result.List)
                {
                    try
                    {
                        if (await ProcessPackage(p))
                        {
                            db.LocalUser.LastPackage = p.Id;
                        }
                        else
                        {
                            noException = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        noException = false;
                        Insight.Report(ex);
                    }
                }
                if (result.List.Count > 0 && noException)
                {
                    await sqlDB.UpdateAsync(db.LocalUser);

                    return(await GetPackages());
                }
            }
            return(result.Error);
        }
 public async Task SetHidden(ChadderConversation conversation)
 {
     try
     {
         conversation.Hidden = true;
         await sqlDB.UpdateAsync(conversation);
     }
     catch (Exception ex)
     {
         Insight.Report(ex);
     }
 }
Exemple #10
0
        public override async void OnReceive(Context context, Intent intent)
        {
            bool noConnection = intent.GetBooleanExtra(Android.Net.ConnectivityManager.ExtraNoConnectivity, false);

            try
            {
                ChadderApp.UIHelper.OnConnectionStateChanged(noConnection == false);
            }
            catch (Exception ex)
            {
                Insight.Report(ex);
            }
        }
        public async Task <bool> LoadPictureAsync(bool thumbnail, ChadderSQLPicture picture = null)
        {
            try
            {
                if (thumbnail && IsThumbnailLoaded || thumbnail == false && IsLoaded)
                {
                    return(true); // Already Loaded
                }
                if (Id == null)
                {
                    return(true); // Invalid Picture
                }
                if (_loading == true)
                {
                    return(true); // Already Loading
                }
                _loading = true;
                if (picture == null && RecordId != 0)
                {
                    picture = await Source.sqlDB.GetPicture(RecordId);
                }
                if (picture == null)
                {
                    if (await Source.DownloadPicture(this) == ChadderError.OK)
                    {
                        picture = await Source.sqlDB.GetPicture(RecordId);
                    }
                }
                if (picture != null)
                {
                    LoadMetaDataFromRecord(picture);

                    var bmp = await LoadPictureFromData(picture.Bin, thumbnail);

                    Update(bmp, thumbnail);
                    _loading = false;
                    return(true);
                }
                return(false);
            }
            catch (Exception ex)
            {
                _loading = false;
                Insight.Report(ex);
                return(false);
            }
        }
Exemple #12
0
        public async Task <ChadderContact> ProcessScannedId(string str)
        {
            try
            {
                var data = str.Split(',');
                if (int.Parse(data[0]) == 1)
                {
                    var contact = db.GetContact(data[1]);
                    if (contact == null)
                    {
                        var response = await GetUserInfo(data[1]);

                        if (response.Error == ChadderError.OK)
                        {
                            contact = response.Extra;
                        }
                        else
                        {
                            Insight.Track("ProcessScannedId GetUserInfo=", response.Error);
                            return(null);
                        }
                    }
                    var compressed = Convert.FromBase64String(data[2]);
                    if (compressed.SequenceEqual(contact.PublicKeyBook.GetMaster().Compressed))
                    {
                        contact.KeyStatus = PublicKeyStatus.VERIFIED;
                    }
                    else
                    {
                        contact.KeyStatus = PublicKeyStatus.CHANGED;
                    }
                    if (contact.IsTemporary == false)
                    {
                        await sqlDB.UpdateAsync(contact);
                    }
                    return(contact);
                }
            }
            catch (Exception ex)
            {
                Insight.Track("ProcessScannedId");
                Insight.Report(ex);
            }
            return(null);
        }
Exemple #13
0
        protected async Task FinishLoading()
        {
            try
            {
                var timer   = Insight.StartTimer("FinishLoading");
                var backoff = new ExponentialBackoff(1000, 5000);
                while (await CreateToken() != ChadderError.OK)
                {
                    await backoff.Failed();
                }
                backoff.Reset();
                await Connection.Connect();

                while (await GetPackages() != ChadderError.OK)
                {
                    await backoff.Failed();
                }
                backoff.Reset();

                while (await GetMyDevices() != ChadderError.OK)
                {
                    await backoff.Failed();
                }
                backoff.Reset();

                while (await UpdateContacts() != ChadderError.OK)
                {
                    await backoff.Failed();
                }
                Insight.StopTimer(timer);
                backoff.Reset();
                while (await GetMyInfo() != ChadderError.OK)
                {
                    await backoff.Failed();
                }

                StartSendPendingMessages();
            }
            catch (Exception ex)
            {
                Insight.Report(ex);
            }
        }
 private void collection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
 {
     try
     {
         if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
         {
             foreach (var item in e.NewItems)
             {
                 AddItem((T)item);
             }
         }
         else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
         {
             foreach (var item in e.OldItems)
             {
                 Remove((T)item);
             }
         }
         else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Move && e.NewItems.Count == 1)
         {
             var item       = (T)e.NewItems[0];
             var wholeIndex = e.NewStartingIndex;
             var current    = IndexOf(item);
             for (int i = 0; i < current; ++i)
             {
                 if (whole.IndexOf(this[i]) > wholeIndex)
                 {
                     Move(current, i);
                     break;
                 }
             }
         }
         else
         {
             reset();
         }
     }
     catch (Exception ex)
     {
         Insight.Track("FilteredCollection_CollectionChanged " + e.Action.ToString());
         Insight.Report(ex);
     }
 }
Exemple #15
0
        public async Task <ChadderError> LoadUser(ChadderLocalUserRecord record)
        {
            try
            {
                var keyPackage = Chadder.Data.Base.Content.Deserialize <PlainBinary>(record.DatabaseKey);
                sqlDB = await ChadderSQLUserDB.GetUserDatabase(record.UserId, keyPackage.BinData, InstanceId);
            }
            catch (Exception ex)
            {
                Insight.Report(ex);
                return(ChadderError.DB_FAILED_OPEN);
            }
            await db.Load();

            IsOnline = true;

            await FinishLoading();

            return(ChadderError.OK);
        }
Exemple #16
0
        public override void OnActivityResult(int requestCode, int resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            try
            {
                var image = ChadderImagePicker.OnPickImageResult(requestCode, resultCode, data, Activity);
                if (image != null)
                {
                    image.DefaultResize();
                    ChadderUI.SendPicture(image.CompressToJPEG(), _conversation);
                }
            }
            catch (Exception e)
            {
                Toast.MakeText(Activity, e.Message, ToastLength.Long).Show();
                Insight.Report(e);
                Console.WriteLine(e);
            }
        }
        public async Task <T> Invoke <T>(IHubProxy proxy, string method, int retries, int nextRetry, params object[] data) where T : BasicResponse, new()
        {
            Exception Inner = null;

            do
            {
                try
                {
                    if (HubConnection != null && proxy != null && HubConnection.State == ConnectionState.Connected)
                    {
                        return(await proxy.Invoke <T>(method, data));
                    }
                }
                catch (Exception ex)
                {
                    Inner = ex;
                    Insight.Track(string.Format("Invoke {0} Failed: {1}", method, HubConnection.State.ToString()));
                    if (HubConnection.State == ConnectionState.Connected)
                    {
                        Insight.Report(ex);
                    }
                }
                if (retries > 0)
                {
                    await Task.Delay(nextRetry);

                    nextRetry *= 2;
                    retries--;
                }
                else
                {
                    break;
                }
            } while (true);
            var response = new T();

            response.InnerException = Inner;
            response.Error          = ChadderError.CONNECTION_ERROR;
            return(response);
        }
        protected void GCMInit()
        {
            try
            {
                PackageInfo pInfo   = this.Activity.PackageManager.GetPackageInfo(this.Activity.PackageName, 0);
                var         shared  = this.Activity.GetSharedPreferences();
                var         version = shared.GetInt(GetString(Resource.String.shared_preferences_version), 0);
                var         temp    = shared.GetString(GetString(Resource.String.shared_preferences_gcm_handle), null);
                if (temp != null)
                {
                    GcmClient.UnRegister(Activity);
                }
                // If already registered for GCM, or if not connected to the internet proceed to login
                if (isNetworkAvailable())
                {
                    // Check for Google GCM
                    int errorCode = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this.Activity);
                    if (errorCode == ConnectionResult.Success)
                    {
                        GcmClient.Register(this.Activity, GcmBroadcastReceiver.SENDER_IDS);
                        Insight.Track("GcmClient.Register");
                    }
                    else
                    {
                        const int          PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
                        Android.App.Dialog dialog = GooglePlayServicesUtil.GetErrorDialog(errorCode, this.Activity, PLAY_SERVICES_RESOLUTION_REQUEST);
                        dialog.DismissEvent += delegate
                        {
                            this.Activity.Finish();
                        };

                        dialog.Show();
                    }
                }
            }
            catch (Exception e)
            {
                Insight.Report(e);
            }
        }
        public static async Task DeleteFile(string filename)
        {
            try
            {
#if WINDOWS_PHONE_APP || WINDOWS_PHONE
                Windows.Storage.StorageFolder folder = DatabaseFolder;
                var mainFile = await folder.GetFileAsync(filename);

                await mainFile.DeleteAsync();
#elif __ANDROID__ || __IOS__ || WINDOWS_DESKTOP
                bool exists = System.IO.File.Exists(filename);
                if (exists)
                {
                    System.IO.File.Delete(filename);
                }
#endif
            }
            catch (Exception ex)
            {
                Insight.Track("DeleteFile: " + filename);
                Insight.Report(ex);
            }
        }
        protected override void InvalidateData()
        {
            base.InvalidateData();
            try
            {
                var profile = ChadderUI.Source.db.LocalUser;
                _tvName.Text  = profile.Name;
                _tvEmail.Text = profile.Email;
                _tvPhone.Text = profile.Phone;
                //++_tvContactBook.Text = ChadderUI.DisplayContactBook();

                _btnPicture.SetImageDrawable(new CircleDrawable(profile.Picture.Image));

                if (profile.IsNamePublic)
                {
                    _tvShareName.Text = "ProfilePublicNameMessageOn".t();
                }
                else
                {
                    _tvShareName.Text = "ProfilePublicNameMessageOff".t();
                }

                if (profile.HasUserKey == false)
                {
                    _btnFingerprint.Visibility = ViewStates.Gone;
                }
                else
                {
                    _btnFingerprint.Visibility = ViewStates.Visible;
                }
            }
            catch (Exception ex)
            {
                Insight.Report(ex);
            }
        }
        public override View GetView(int position, View view, ViewGroup parent)
        {
            var  shouldBeType  = GetItemViewType(position);
            bool createNewView = view == null;

            if (createNewView == false)
            {
                if (initializedViews.ContainsKey(view) == true)
                {
                    var tuple = initializedViews[view];
                    if (tuple.Item1 != shouldBeType)
                    {
                        createNewView = true;
                    }
                }
                else
                {
                    createNewView = true;
                }
            }
            if (createNewView)
            {
                var layoutResource = GetResourceByItemType(shouldBeType);
                view = this.Context.LayoutInflater.Inflate(layoutResource, null);
                this.InitializeNewView(view, shouldBeType);
            }

            T item = this[position];

            if (initializedViews.ContainsKey(view) == false || item == null || item.Equals(initializedViews[view].Item2) == false)
            {
                this.initializedViews[view] = new Tuple <int, T>(shouldBeType, item);
                try
                {
                    this.PrepareView(item, view, position);
                }
                catch (Exception ex)
                {
                    Insight.Track("Exception thrown PrepareView - " + this.GetType().Name);
                    Insight.Report(ex);
                }
            }
            if (item != null)
            {
                PropertyChangedEventHandler Changed = (a, e) =>
                {
                    try
                    {
                        PrepareView(item, view, position);
                    }
                    catch (Exception ex)
                    {
                        Insight.Track("Exception thrown PrepareView - " + this.GetType().Name);
                        Insight.Report(ex);
                    }
                };
                if (ChangedEvents.ContainsKey(item) == true)
                {
                    item.PropertyChanged -= ChangedEvents[item];
                }

                ChangedEvents[item] = Changed;

                item.PropertyChanged += Changed;
            }
            return(view);
        }
 private void AndroidEnvironment_UnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
 {
     Insight.Report(e.Exception);
 }
Exemple #23
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            var view = inflater.Inflate(Resource.Layout.fragment_contact_list, container, false);

            try
            {
                _contactListView = view.FindViewById <Android.Widget.ListView>(Resource.Id.contact_list);

                searchText = view.FindViewById <EditText>(Resource.Id.contact_list_searchview);

                _noEntryText = view.FindViewById <TextView>(Resource.Id.no_friends_textview);
                _noEntryText.TextFormatted = Html.FromHtml("To add friends you can type their name in the search bar and if they have enabled </br>\"Public Name\" they will appear here");

                searchText.TextChanged += (s, e) =>
                {
                    _adapter.Collection.SetSearch(searchText.Text);
                };

                _adapter = new FindFriendAdapter(this.Activity, _noEntryText, new UIHelper.FindContactObservableCollection(ChadderApp.UIHelper.Source));
                _contactListView.Adapter    = _adapter;
                _contactListView.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) =>
                {
                    var contact = _adapter[e.Position];
                    if (contact == null)
                    {
                        return;
                    }
                    if (contact.IsTemporary)
                    {
                        SupportFragmentManager.BeginTransaction()
                        .Replace(Resource.Id.content_frame, ViewProfileFragment.ViewProfile(contact))
                        .AddToBackStack(null)
                        .Commit();
                    }
                    else
                    {
                        SupportFragmentManager.PopBackStack();
                        SupportFragmentManager.BeginTransaction()
                        .Replace(Resource.Id.content_frame, ChatFragment.OpenChat(contact))
                        .AddToBackStack(null)
                        .Commit();
                    }
                };

                _menuManager = new ContextMenuManager <ChadderContact>(this, _contactListView);

                _menuManager.InsertItem("View profile", (ChadderContact contact) =>
                {
                    Android.Support.V4.App.FragmentTransaction transaction = this.Activity.SupportFragmentManager.BeginTransaction();
                    transaction.Replace(Resource.Id.content_frame, ViewProfileFragment.ViewProfile(contact));
                    transaction.AddToBackStack(null);
                    transaction.Commit();
                });

                _menuManager.InsertItem(c => c.Type == Chadder.Data.RelationshipType.BLOCKED ? "Unblock" : "Block",
                                        (ChadderContact contact) => ChadderUI.ToggleBlock(contact));

                _menuManager.InsertItem("Report",
                                        (ChadderContact contact) => ChadderUI.ReportContact(contact));
            }
            catch (Exception e)
            {
                Insight.Report(e);
            }

            return(view);
        }
        protected async Task <ChadderError> SendMessageToServer(ChadderMessage msg, ChadderConversation conversation)
        {
            try
            {
                BasicMessage package = null;
                if (msg.Type == ChadderMessage.MESSAGE_TYPE.TEXT)
                {
                    package = new TextMessage()
                    {
                        Body = msg.Body
                    };
                }
                else if (msg.Type == ChadderMessage.MESSAGE_TYPE.PICTURE)
                {
                    if (msg.Picture.ToBeUploaded)
                    {
                        var record = await sqlDB.GetPicture(msg.Picture.RecordId);

                        var presult = await UploadPicture(record);

                        if (presult.Error == ChadderError.OK)
                        {
                            msg.PictureId = record.PictureId;
                            await sqlDB.UpdateAsync(msg);
                        }
                        else
                        {
                            return(presult.Error);
                        }
                    }
                    package = new ImageMessage()
                    {
                        PictureId = msg.PictureId
                    };
                }
                else
                {
                    Insight.Track("Invalid Message Type in SendMessageToServer");
                    return(ChadderError.INVALID_INPUT);
                }
                package.Id         = msg.MessageId;
                package.Group      = null;
                package.TimeSent   = msg.TimeSent.Value;
                package.Expiration = msg.Expiration.Value;

                var content = await EncryptForUser(package, conversation.Contact);

                var request = new SendPackageParameter()
                {
                    UserId = conversation.ContactUserId,
                    Data   = content.Serialize()
                };
                var result = await AuthorizedRequest <BasicResponse <string> >(Connection.ChatHub, "SendPackageToUser", request);

                if (result.Error == ChadderError.OK)
                {
                    msg.Status      = ChadderMessage.MESSAGE_STATUS.SENT;
                    msg.TimeServer  = result.Time;
                    msg.ReferenceId = result.Extra;
                    await sqlDB.UpdateAsync(msg);
                }
                return(result.Error);
            }
            catch (Exception ex)
            {
                Insight.Report(ex);
                return(ChadderError.GENERAL_EXCEPTION);
            }
        }