Ejemplo n.º 1
0
        public override void OnReceive(Context context, Intent intent)
        {
            File currentSummary       = new File(context.FilesDir, CurrentSummaryFile);
            File sentSummary          = new File(context.FilesDir, SentSummaryFile);
            NotificationSender sender = new NotificationSender(context, SummaryCategory);

            if (currentSummary.Exists())
            {
                try
                {
                    string text;
                    using (StreamReader reader = new StreamReader(context.OpenFileInput(CurrentSummaryFile)))
                    {
                        text = reader.ReadToEnd();
                    }
                    Log.Debug(nameof(AlarmReceiver), text);
                    sender.PutNormalizeExtra(ExtraSummaryText, text);
                    sender.Send(NotificationType.SummaryNotification, text);
                    if (sentSummary.Exists())
                    {
                        sentSummary.Delete();
                    }
                    currentSummary.RenameTo(sentSummary);
                }
                catch (Exception e)
                {
                    Log.Error(nameof(AlarmReceiver), e.StackTrace);
                }
            }
            else
            {
                Log.Debug(nameof(AlarmReceiver), $"File {currentSummary.AbsolutePath} not exist");
            }
        }
        private void WriteAndSend(NotificationSender sender, string path, FileObserverEvents events)
        {
            string message     = string.Format(GetString(Resource.String.category_system_notif_modification_detected), events, path);
            string fullMessage = $"{new Date().GetFormattedDateTime()} : {message}";

            using (StreamWriter writer = new StreamWriter(OpenFileOutput(LogFile, FileCreationMode.Append)))
            {
                writer.WriteLine(fullMessage);
            }

            using (StreamWriter writer = new StreamWriter(OpenFileOutput(AlarmReceiver.CurrentSummaryFile, FileCreationMode.Append)))
            {
                writer.WriteLine(fullMessage);
            }

            sender.PutNormalizeExtra(ExtraFilePath, path);
            sender.PutNormalizeExtra(ExtraFileEvent, events.ToString());
            sender.Send(NotificationType.WarningNotification, message);
        }
Ejemplo n.º 3
0
        private void OnOutgoingCall(Context context, string phoneNumber)
        {
            var telephonyManager = TelephonyManager.FromContext(context);

            if (phoneNumber == null)
            {
                Log.Error(Tag, "Can't proceed outgoing call, caller phone number is null!");
                return;
            }

            var myPhoneNumber = new string(telephonyManager.Line1Number.Where(char.IsDigit).ToArray());

            if (myPhoneNumber.Length == 0)
            {
                Log.Error(Tag, "Can't proceed outgoing call, your phone number is null!");
                return;
            }

            var         phoneNumberUtils = PhoneNumberUtil.GetInstance();
            PhoneNumber callerPhoneNumber;

            try
            {
                callerPhoneNumber =
                    phoneNumberUtils.Parse(phoneNumber, context.Resources.Configuration.Locale.Country);
            }
            catch (Exception e)
            {
                Log.Error(nameof(PhoneCallReceiver), e.Message);
                return;
            }
            var thisPhoneNumber =
                phoneNumberUtils.Parse(myPhoneNumber, context.Resources.Configuration.Locale.Country);

            if (callerPhoneNumber.CountryCode == thisPhoneNumber.CountryCode)
            {
                Log.Debug(Tag,
                          $"Same for {phoneNumberUtils.Format(callerPhoneNumber, PhoneNumberFormat.INTERNATIONAL)}," +
                          $" {phoneNumberUtils.Format(thisPhoneNumber, PhoneNumberFormat.INTERNATIONAL)}");
                return;
            }

            if (new File(context.FilesDir, PhoneUtils.ExcludedOutCountryCodesFile).Exists())
            {
                string text;
                using (var reader =
                           new StreamReader(context.OpenFileInput(PhoneUtils.ExcludedOutCountryCodesFile)))
                {
                    text = reader.ReadToEnd();
                }

                foreach (var line in text.Split())
                {
                    if (int.TryParse(line, out var lineCode) && callerPhoneNumber.CountryCode == lineCode)
                    {
                        Log.Debug(Tag, $"Found {lineCode} in excluded outgoing country codes");
                        return;
                    }
                }
            }

            var warningMessage = string.Format(
                context.GetString(Resource.String.category_phone_notification_suspicious_call_to),
                callerPhoneNumber.GetInternationalNumber());

            using (var writer =
                       new StreamWriter(context.OpenFileOutput(PhoneUtils.SuspiciousCallsFile, FileCreationMode.Append)))
            {
                writer.WriteLine(warningMessage);
            }

            using (var writer =
                       new StreamWriter(context.OpenFileOutput(AlarmReceiver.CurrentSummaryFile, FileCreationMode.Append)))
            {
                writer.WriteLine(warningMessage);
            }

            var sender = new NotificationSender(context, DataHolder.PhoneCategory);

            sender.PutNormalizeExtra(PhoneUtils.CountryCodeKey, callerPhoneNumber.CountryCode);
            sender.PutNormalizeExtra(PhoneUtils.IsOutgoingKey, true);
            sender.Send(NotificationType.WarningNotification, warningMessage);
            MainActivity.Adapter?.Refresh();
        }
Ejemplo n.º 4
0
        public override void OnReceive(Context context, Intent intent)
        {
            Log.Debug(nameof(ScreenUnlockReceiver), intent.Action);

            var notificationSender = new NotificationSender(context, DataHolder.ScreenLocksCategory);

            if (_mPreferences == null)
            {
                _mPreferences = PreferenceManager.GetDefaultSharedPreferences(context);
            }

            var now = new Date();

            long monitoringStartTime;

            if ((monitoringStartTime = _mPreferences.GetLong(ScreenUtils.MonitoringLastStartTime, -1)) == -1)
            {
                monitoringStartTime = ScreenUtils.GetMonitoringStartTime(now);
                _mPreferences.Edit().PutLong(ScreenUtils.MonitoringLastStartTime, monitoringStartTime).Apply();
                using (var writer = new StreamWriter(
                           context.OpenFileOutput(DebugFile, FileCreationMode.Append)))
                {
                    writer.WriteLine($"----Monitoring u start Time: {now.GetFormattedDateTime()}----");
                }
            }
            else
            {
                monitoringStartTime = ScreenUtils.GetMonitoringStartTime(new Date(monitoringStartTime));
            }

            if (_lastDayUnlocked == -1)
            {
                int tmpDay;
                if ((tmpDay = _mPreferences.GetInt(ScreenUtils.LastUnlockDay, -1)) != -1)
                {
                    _lastDayUnlocked = tmpDay;
                    UnlockedTimes    = _mPreferences.GetInt(ScreenUtils.UnlocksToday, 0);
                }
                else
                {
                    _lastDayUnlocked = Calendar.Instance.Get(CalendarField.DayOfWeek);
                    _mPreferences.Edit().PutInt(ScreenUtils.LastUnlockDay, _lastDayUnlocked).Apply();
                }
            }

            if (_unlockMillis == null)
            {
                var thisDay = _mPreferences.GetInt($"{ScreenUtils.UnlocksDayNumber}{_lastDayUnlocked}", 0);
                _todayNormalSpeedValue = Math.Max(
                    _abnormalUnlockMinCount,
                    (int)(thisDay * _abnormalUnlockPercentage / 100d));
                _unlockMillis = new List <long>();
            }

            if (TimeUnit.Milliseconds.ToDays(now.Time - monitoringStartTime) >= 1)
            {
                var unlocksToPut = UnlockedTimes;
                int u;

                if ((u = _mPreferences.GetInt($"{ScreenUtils.UnlocksDayNumber}{_lastDayUnlocked}", -1)) != -1)
                {
                    unlocksToPut = (int)Math.Ceiling((u + unlocksToPut) / 2d);
                }

                var tmpDay = _lastDayUnlocked;
                _lastDayUnlocked = Calendar.Instance.Get(CalendarField.DayOfWeek);
                UnlockedTimes    = 1;

                var thisDay = _mPreferences.GetInt($"{ScreenUtils.UnlocksDayNumber}{_lastDayUnlocked}", 0);
                _todayNormalSpeedValue = Math.Max(
                    _abnormalUnlockMinCount,
                    (int)(thisDay * _abnormalUnlockPercentage / 100d));
                _unlockMillis = new List <long>();

                _mPreferences.Edit()
                .PutInt($"{ScreenUtils.UnlocksDayNumber}{tmpDay}", unlocksToPut)
                .PutInt(ScreenUtils.LastUnlockDay, _lastDayUnlocked)
                .PutLong(ScreenUtils.MonitoringLastStartTime, ScreenUtils.GetMonitoringStartTime(now))
                .PutInt(ScreenUtils.UnlocksToday, UnlockedTimes)
                .PutInt(ScreenUtils.UnlocksNewNormalCount, -1)
                .Apply();

                MainActivity.Adapter?.Refresh();
                return;
            }

            Log.Debug("AbScreenReceiver",
                      $"Not new day. Was {new Date(monitoringStartTime).GetFormattedDateTime()}, now {now.GetFormattedDateTime()}");

            _mPreferences.Edit().PutInt(ScreenUtils.UnlocksToday, ++UnlockedTimes).Apply();

            var mode = 0;

            if (UnlockedTimes > GetNormalUnlocksCount(_mPreferences) * 1.1)
            {
                mode = 1;
            }

            _abnormalUnlockInterval = _mPreferences.GetInt(AbnormalUnlocksTimeInterval, _abnormalUnlockInterval);

            if (_unlockMillis.Count > _todayNormalSpeedValue)
            {
                var s = TimeUnit.Milliseconds.ToSeconds(now.Time - _unlockMillis[0]);

                if (s <= _abnormalUnlockInterval && s > 0)
                {
                    mode = 2;
                    using (var writer = new StreamWriter(
                               context.OpenFileOutput(DebugFile, FileCreationMode.Append)))
                    {
                        writer.WriteLine($"----Time: {new Date().GetFormattedDateTime()}----");
                        foreach (var unlock in _unlockMillis)
                        {
                            writer.WriteLine($"Unlock at {new Date(unlock).GetFormattedDateTime()}, val = {unlock}");
                        }

                        writer.WriteLine("-----End1-----");
                    }
                }
                else
                {
                    var  tmpList = new List <long>();
                    long sec;
                    foreach (var time in _unlockMillis)
                    {
                        sec = TimeUnit.Milliseconds.ToSeconds(now.Time - time);
                        if (sec <= _abnormalUnlockInterval && sec > 0)
                        {
                            tmpList.Add(time);
                        }
                    }

                    _unlockMillis = tmpList;
                    sec           = TimeUnit.Milliseconds.ToSeconds(now.Time - _unlockMillis[0]);
                    if (_unlockMillis.Count > _todayNormalSpeedValue && sec <= _abnormalUnlockInterval && sec > 0)
                    {
                        mode = 2;
                        using (var writer = new StreamWriter(
                                   context.OpenFileOutput(DebugFile, FileCreationMode.Append)))
                        {
                            writer.WriteLine($"----Time: {new Date().GetFormattedDateTime()}----");
                            foreach (var unlock in _unlockMillis)
                            {
                                writer.WriteLine(
                                    $"Unlock at {new Date(unlock).GetFormattedDateTime()}, val = {unlock}");
                            }

                            writer.WriteLine("-----End2-----");
                        }
                    }
                }
            }

            _unlockMillis.Add(now.Time);

            string notificationText;

            switch (mode)
            {
            case 1:
                Status           = ScreenStatus.Many;
                notificationText =
                    string.Format(context.GetString(Resource.String.category_screen_notif_daily_overflow),
                                  UnlockedTimes, NormalCount);
                notificationSender.PutNormalizeExtra(ScreenUtils.UnlocksNewNormalCount,
                                                     (int)(UnlockedTimes * 1.2));

                CategoriesAdapter.Refresh(DataHolder.ScreenCategory);
                break;

            case 2:
                var tmpInterval = (int)(.9 * _abnormalUnlockInterval);
                if (tmpInterval >= _abnormalUnlockInterval)
                {
                    if (tmpInterval > 1)
                    {
                        tmpInterval--;
                    }
                }

                Status           = ScreenStatus.Speed;
                notificationText =
                    string.Format(context.GetString(Resource.String.category_screen_notif_west_fast_hand),
                                  _unlockMillis.Count,
                                  TimeUnit.Milliseconds.ToSeconds(_unlockMillis.Last() - _unlockMillis.First()));

                notificationSender.PutNormalizeExtra(AbnormalUnlocksTimeInterval, tmpInterval);
                CategoriesAdapter.Refresh(DataHolder.ScreenCategory);
                break;

            default:
                Status = ScreenStatus.OK;
                CategoriesAdapter.Refresh(DataHolder.ScreenCategory);
                return;
            }

            using (var writer =
                       new StreamWriter(context.OpenFileOutput(AlarmReceiver.CurrentSummaryFile, FileCreationMode.Append)))
            {
                writer.WriteLine(notificationText);
            }

            notificationSender.Send(NotificationType.WarningNotification, notificationText);
        }
Ejemplo n.º 5
0
        public static async void GetLastLocationFromDevice()
        {
            if (_fusedLocationProviderClient == null)
            {
                Log.Debug("LastAbLocation", "fu is null!");
                return;
            }

            var location = await _fusedLocationProviderClient.GetLastLocationAsync();

            if (location == null)
            {
                return;
            }
            var res            = new float[2];
            var bigDestination = true;
            var entered        = false;

            if (new File(mContext.FilesDir, LocationCoordinatesFile).Exists())
            {
                using (var reader =
                           new StreamReader(mContext.OpenFileInput(LocationCoordinatesFile)))
                {
                    foreach (var line in reader.ReadToEnd().Split("\n"))
                    {
                        if (!line.Contains("Latitude"))
                        {
                            continue;
                        }

                        var latString = line.Substring(line.AfterIndex("Latitude = "),
                                                       line.IndexOf(", Long") - line.AfterIndex("Latitude = "));
                        var    longString = line.Substring(line.AfterIndex("Longitude = "));
                        double latDouble;
                        double longDouble;
                        try
                        {
                            latDouble  = double.Parse(latString);
                            longDouble = double.Parse(longString);
                        }
                        catch (Exception)
                        {
                            continue;
                        }

                        Location.DistanceBetween(latDouble,
                                                 longDouble, location.Latitude, location.Longitude, res);
                        entered = true;
                        if (res[0] < 10 * 1000)
                        {
                            bigDestination = false;
                            break;
                        }
                    }
                }
            }

            if (entered && bigDestination)
            {
                var notPrevious = true;
                if (PreviousLocation != null)
                {
                    var prevRes = new float[2];
                    Location.DistanceBetween(PreviousLocation.Latitude,
                                             PreviousLocation.Longitude, location.Latitude, location.Longitude, prevRes);
                    if (prevRes[0] < 500)
                    {
                        notPrevious = false;
                    }
                }
                if (notPrevious)
                {
                    var sender = new NotificationSender(mContext, DataHolder.LocationCategory);
                    sender.PutNormalizeExtra(LocationLatitude, location.Latitude);
                    sender.PutNormalizeExtra(LocationLongitude, location.Longitude);

                    var distance =
                        string.Format(mContext.GetString(Resource.String.category_location_notif_big_distance),
                                      res[0] / 1000);

                    sender.Send(NotificationType.WarningNotification, distance);
                    using (StreamWriter writer = new StreamWriter(mContext.OpenFileOutput(AlarmReceiver.CurrentSummaryFile, FileCreationMode.Append)))
                    {
                        writer.WriteLine(distance);
                    }

                    PreviousLocation = location;
                    DataHolder.CategoriesDictionary[DataHolder.LocationCategory].Level = DataHolder.CheckStatus.Dangerous;
                }
            }
            else
            {
                if (DataHolder.CategoriesDictionary[DataHolder.LocationCategory].Level == DataHolder.CheckStatus.Dangerous)
                {
                    DataHolder.CategoriesDictionary[DataHolder.LocationCategory].Level = DataHolder.CheckStatus.Warning;
                }
            }

            if (!new File(mContext.FilesDir, LocationCoordinatesFile).Exists())
            {
                using (var writer =
                           new StreamWriter(mContext.OpenFileOutput(LocationCoordinatesFile,
                                                                    FileCreationMode.Private)))
                {
                    writer.WriteLine("Known locations:");
                    writer.WriteLine($"Latitude = {location.Latitude}, Longitude = {location.Longitude}");
                }
            }

            DataHolder.CategoriesDictionary[DataHolder.LocationCategory].Data = FormatLocation(mContext, location);
            if (MainActivity.Adapter != null)
            {
                int pos = MainActivity.Adapter.categories.FindIndex(s => s == DataHolder.LocationCategory);
                MainActivity.Adapter.Refresh(pos);
            }
        }