Welcome to mirror list, hosted at ThFree Co, Russian Federation.

LocalNotificationManager.mm « Notifications « Core « Maps « iphone - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d74f8cda3750b02847d58e4486108e024bd77718 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#import "LocalNotificationManager.h"
#import "CLLocation+Mercator.h"
#import "MWMStorage.h"
#import "MapViewController.h"
#import "Statistics.h"
#import "3party/Alohalytics/src/alohalytics_objc.h"

#include "Framework.h"

#include "storage/country_info_getter.hpp"
#include "storage/storage_helpers.hpp"

#include "map/framework_light.hpp"

#include "platform/network_policy_ios.h"

namespace
{
NSString * const kLocalNotificationNameKey = @"LocalNotificationName";
NSString * const kUGCNotificationValue = @"UGC";
NSString * const kDownloadMapActionKey = @"DownloadMapActionKey";
NSString * const kDownloadMapActionName = @"DownloadMapActionName";
NSString * const kDownloadMapCountryId = @"DownloadMapCountryId";

NSString * const kFlagsKey = @"DownloadMapNotificationFlags";

NSTimeInterval constexpr kRepeatedNotificationIntervalInSeconds =
    3 * 30 * 24 * 60 * 60;  // three months
NSString * const kLastUGCNotificationDate = @"LastUGCNotificationDate";
}  // namespace

using namespace storage;

@interface LocalNotificationManager ()<CLLocationManagerDelegate, UIAlertViewDelegate>

@property(nonatomic) CLLocationManager * locationManager;
@property(copy, nonatomic) CompletionHandler downloadMapCompletionHandler;
@property(weak, nonatomic) NSTimer * timer;
@property(copy, nonatomic) MWMVoidBlock onTap;

@end

@implementation LocalNotificationManager

+ (instancetype)sharedManager
{
  static LocalNotificationManager * manager = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    manager = [[self alloc] init];
  });
  return manager;
}

+ (BOOL)shouldShowUGCNotification
{
  if (!network_policy::CanUseNetwork())
    return NO;


  auto ud = [NSUserDefaults standardUserDefaults];
  if (NSDate * date = [ud objectForKey:kLastUGCNotificationDate])
  {
    auto calendar = [NSCalendar currentCalendar];
    auto components = [calendar components:NSCalendarUnitDay fromDate:date
                                    toDate:[NSDate date] options:NSCalendarWrapComponents];

    auto constexpr minDaysSinceLast = 5u;
    if (components.day <= minDaysSinceLast)
      return NO;
  }

  using namespace lightweight;
  lightweight::Framework f(REQUEST_TYPE_NUMBER_OF_UNSENT_UGC | REQUEST_TYPE_USER_AUTH_STATUS);
  if (f.Get<REQUEST_TYPE_USER_AUTH_STATUS>() || f.Get<REQUEST_TYPE_NUMBER_OF_UNSENT_UGC>() < 2)
    return NO;

  return YES;
}

+ (void)UGCNotificationWasShown
{
  auto ud = [NSUserDefaults standardUserDefaults];
  [ud setObject:[NSDate date] forKey:kLastUGCNotificationDate];
  [ud synchronize];
  [Statistics logEvent:@"UGC_UnsentNotification_shown"];
}

- (void)dealloc { _locationManager.delegate = nil; }
- (void)processNotification:(NSDictionary *)userInfo onLaunch:(BOOL)onLaunch
{
  if ([userInfo[kDownloadMapActionKey] isEqualToString:kDownloadMapActionName])
  {
    [Statistics logEvent:@"'Download Map' Notification Clicked"];
    MapViewController * mapViewController = [MapViewController sharedController];
    [mapViewController.navigationController popToRootViewControllerAnimated:NO];

    NSString * notificationCountryId = userInfo[kDownloadMapCountryId];
    TCountryId const countryId = notificationCountryId.UTF8String;
    [Statistics logEvent:kStatDownloaderMapAction
          withParameters:@{
            kStatAction : kStatDownload,
            kStatIsAuto : kStatNo,
            kStatFrom : kStatMap,
            kStatScenario : kStatDownload
          }];
    [MWMStorage downloadNode:countryId
                   onSuccess:^{
                     GetFramework().ShowNode(countryId);
                   }];
  }
  else if ([userInfo[kLocalNotificationNameKey] isEqualToString:kUGCNotificationValue])
  {
    if (self.onTap)
      self.onTap();

   [Statistics logEvent:@"UGC_UnsentNotification_clicked"];
  }
}

#pragma mark - Location Notifications

- (BOOL)showUGCNotificationIfNeeded:(MWMVoidBlock)onTap
{
  auto application = UIApplication.sharedApplication;
  auto identifier = UIBackgroundTaskInvalid;
  auto handler = [&identifier] {
    [[UIApplication sharedApplication] endBackgroundTask:identifier];
  };

  identifier = [application beginBackgroundTaskWithExpirationHandler:^{
    handler();
  }];

  if (![LocalNotificationManager shouldShowUGCNotification]) {
    handler();
    return NO;
  }

  self.onTap = onTap;
  UILocalNotification * notification = [[UILocalNotification alloc] init];
  notification.alertTitle = L(@"notification_unsent_reviews_title");
  notification.alertBody = L(@"notification_unsent_reviews_message");
  notification.alertAction = L(@"authorization_button_sign_in");
  notification.soundName = UILocalNotificationDefaultSoundName;
  notification.userInfo = @{kLocalNotificationNameKey : kUGCNotificationValue};

  [application presentLocalNotificationNow:notification];
  [LocalNotificationManager UGCNotificationWasShown];
  handler();
  return YES;
}

- (void)showDownloadMapNotificationIfNeeded:(CompletionHandler)completionHandler
{
  NSTimeInterval const completionTimeIndent = 2.0;
  NSTimeInterval const backgroundTimeRemaining =
      UIApplication.sharedApplication.backgroundTimeRemaining - completionTimeIndent;
  if ([CLLocationManager locationServicesEnabled] && backgroundTimeRemaining > 0.0)
  {
    self.downloadMapCompletionHandler = completionHandler;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:backgroundTimeRemaining
                                                  target:self
                                                selector:@selector(timerSelector:)
                                                userInfo:nil
                                                 repeats:NO];
    LOG(LINFO, ("startUpdatingLocation"));
    [self.locationManager startUpdatingLocation];
  }
  else
  {
    LOG(LINFO, ("stopUpdatingLocation"));
    [self.locationManager stopUpdatingLocation];
    completionHandler(UIBackgroundFetchResultFailed);
  }
}

- (BOOL)shouldShowNotificationForCountryId:(NSString *)countryId
{
  if (!countryId || countryId.length == 0)
    return NO;
  NSUserDefaults * ud = NSUserDefaults.standardUserDefaults;
  NSDictionary<NSString *, NSDate *> * flags = [ud objectForKey:kFlagsKey];
  NSDate * lastShowDate = flags[countryId];
  return !lastShowDate ||
         [[NSDate date] timeIntervalSinceDate:lastShowDate] >
             kRepeatedNotificationIntervalInSeconds;
}

- (void)markNotificationShownForCountryId:(NSString *)countryId
{
  NSUserDefaults * ud = NSUserDefaults.standardUserDefaults;
  NSMutableDictionary<NSString *, NSDate *> * flags = [[ud objectForKey:kFlagsKey] mutableCopy];
  if (!flags)
    flags = [NSMutableDictionary dictionary];
  flags[countryId] = [NSDate date];
  [ud setObject:flags forKey:kFlagsKey];
  [ud synchronize];
}

- (void)timerSelector:(id)sender
{
  // Location still was not received but it's time to finish up so system will not kill us.
  LOG(LINFO, ("stopUpdatingLocation"));
  [self.locationManager stopUpdatingLocation];
  [self performCompletionHandler:UIBackgroundFetchResultFailed];
}

- (void)performCompletionHandler:(UIBackgroundFetchResult)result
{
  if (!self.downloadMapCompletionHandler)
    return;
  self.downloadMapCompletionHandler(result);
  self.downloadMapCompletionHandler = nil;
}

#pragma mark - Location Manager

- (CLLocationManager *)locationManager
{
  if (!_locationManager)
  {
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.distanceFilter = kCLLocationAccuracyThreeKilometers;
  }
  return _locationManager;
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations
{
  [self.timer invalidate];
  LOG(LINFO, ("stopUpdatingLocation"));
  [self.locationManager stopUpdatingLocation];
  NSString * flurryEventName = @"'Download Map' Notification Didn't Schedule";
  UIBackgroundFetchResult result = UIBackgroundFetchResultNoData;

  BOOL const inBackground =
      UIApplication.sharedApplication.applicationState == UIApplicationStateBackground;
  BOOL const onWiFi = (Platform::ConnectionStatus() == Platform::EConnectionType::CONNECTION_WIFI);
  if (inBackground && onWiFi)
  {
    CLLocation * lastLocation = locations.lastObject;
    auto const & mercator = lastLocation.mercator;
    auto & f = GetFramework();
    auto const & countryInfoGetter = f.GetCountryInfoGetter();
    if (!IsPointCoveredByDownloadedMaps(mercator, f.GetStorage(), countryInfoGetter))
    {
      NSString * countryId = @(countryInfoGetter.GetRegionCountryId(mercator).c_str());
      if ([self shouldShowNotificationForCountryId:countryId])
      {
        [self markNotificationShownForCountryId:countryId];

        UILocalNotification * notification = [[UILocalNotification alloc] init];
        notification.alertAction = L(@"download");
        notification.alertBody = L(@"download_map_notification");
        notification.soundName = UILocalNotificationDefaultSoundName;
        notification.userInfo =
            @{kDownloadMapActionKey : kDownloadMapActionName, kDownloadMapCountryId : countryId};

        UIApplication * application = UIApplication.sharedApplication;
        [application presentLocalNotificationNow:notification];

        [Alohalytics logEvent:@"suggestedToDownloadMissingMapForCurrentLocation"
                   atLocation:lastLocation];
        flurryEventName = @"'Download Map' Notification Scheduled";
        result = UIBackgroundFetchResultNewData;
      }
    }
  }
  [Statistics logEvent:flurryEventName withParameters:@{ @"WiFi" : @(onWiFi) }];
  [self performCompletionHandler:result];
}

@end