FLEXNetworkMITMViewController.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. //
  2. // FLEXNetworkMITMViewController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 2/8/15.
  6. // Copyright (c) 2020 FLEX Team. All rights reserved.
  7. //
  8. #import "FLEXColor.h"
  9. #import "FLEXUtility.h"
  10. #import "FLEXNetworkMITMViewController.h"
  11. #import "FLEXNetworkTransaction.h"
  12. #import "FLEXNetworkRecorder.h"
  13. #import "FLEXNetworkObserver.h"
  14. #import "FLEXNetworkTransactionCell.h"
  15. #import "FLEXNetworkTransactionDetailController.h"
  16. #import "FLEXNetworkSettingsController.h"
  17. #import "FLEXGlobalsViewController.h"
  18. #import "UIBarButtonItem+FLEX.h"
  19. #import "FLEXResources.h"
  20. @interface FLEXNetworkMITMViewController ()
  21. /// Backing model
  22. @property (nonatomic, copy) NSArray<FLEXNetworkTransaction *> *networkTransactions;
  23. @property (nonatomic) long long bytesReceived;
  24. @property (nonatomic, copy) NSArray<FLEXNetworkTransaction *> *filteredNetworkTransactions;
  25. @property (nonatomic) long long filteredBytesReceived;
  26. @property (nonatomic) BOOL rowInsertInProgress;
  27. @property (nonatomic) BOOL isPresentingSearch;
  28. @property (nonatomic) BOOL pendingReload;
  29. @end
  30. @implementation FLEXNetworkMITMViewController
  31. #pragma mark - Lifecycle
  32. - (id)init {
  33. return [self initWithStyle:UITableViewStylePlain];
  34. }
  35. - (void)viewDidLoad {
  36. [super viewDidLoad];
  37. self.showsSearchBar = YES;
  38. self.showSearchBarInitially = NO;
  39. [self addToolbarItems:@[
  40. [UIBarButtonItem
  41. flex_itemWithImage:FLEXResources.gearIcon
  42. target:self
  43. action:@selector(settingsButtonTapped:)
  44. ],
  45. [[UIBarButtonItem
  46. flex_systemItem:UIBarButtonSystemItemTrash
  47. target:self
  48. action:@selector(trashButtonTapped:)
  49. ] flex_withTintColor:UIColor.redColor]
  50. ]];
  51. [self.tableView
  52. registerClass:[FLEXNetworkTransactionCell class]
  53. forCellReuseIdentifier:kFLEXNetworkTransactionCellIdentifier
  54. ];
  55. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  56. self.tableView.rowHeight = FLEXNetworkTransactionCell.preferredCellHeight;
  57. [self registerForNotifications];
  58. [self updateTransactions];
  59. }
  60. - (void)viewWillAppear:(BOOL)animated {
  61. [super viewWillAppear:animated];
  62. // Reload the table if we received updates while not on-screen
  63. if (self.pendingReload) {
  64. [self.tableView reloadData];
  65. self.pendingReload = NO;
  66. }
  67. }
  68. - (void)dealloc {
  69. [NSNotificationCenter.defaultCenter removeObserver:self];
  70. }
  71. - (void)registerForNotifications {
  72. NSDictionary *notifications = @{
  73. kFLEXNetworkRecorderNewTransactionNotification:
  74. NSStringFromSelector(@selector(handleNewTransactionRecordedNotification:)),
  75. kFLEXNetworkRecorderTransactionUpdatedNotification:
  76. NSStringFromSelector(@selector(handleTransactionUpdatedNotification:)),
  77. kFLEXNetworkRecorderTransactionsClearedNotification:
  78. NSStringFromSelector(@selector(handleTransactionsClearedNotification:)),
  79. kFLEXNetworkObserverEnabledStateChangedNotification:
  80. NSStringFromSelector(@selector(handleNetworkObserverEnabledStateChangedNotification:)),
  81. };
  82. for (NSString *name in notifications.allKeys) {
  83. [NSNotificationCenter.defaultCenter addObserver:self
  84. selector:NSSelectorFromString(notifications[name]) name:name object:nil
  85. ];
  86. }
  87. }
  88. #pragma mark - Private
  89. #pragma mark Button Actions
  90. - (void)settingsButtonTapped:(UIBarButtonItem *)sender {
  91. UIViewController *settings = [FLEXNetworkSettingsController new];
  92. settings.navigationItem.rightBarButtonItem = FLEXBarButtonItemSystem(
  93. Done, self, @selector(settingsViewControllerDoneTapped:)
  94. );
  95. settings.title = @"Network Debugging Settings";
  96. // This is not a FLEXNavigationController because it is not intended as a new tab
  97. UIViewController *nav = [[UINavigationController alloc] initWithRootViewController:settings];
  98. [self presentViewController:nav animated:YES completion:nil];
  99. }
  100. - (void)trashButtonTapped:(UIBarButtonItem *)sender {
  101. [FLEXAlert makeSheet:^(FLEXAlert *make) {
  102. make.title(@"Clear All Recorded Requests?");
  103. make.message(@"This cannot be undone.");
  104. make.button(@"Cancel").cancelStyle();
  105. make.button(@"Clear All").destructiveStyle().handler(^(NSArray *strings) {
  106. [FLEXNetworkRecorder.defaultRecorder clearRecordedActivity];
  107. });
  108. } showFrom:self source:sender];
  109. }
  110. - (void)settingsViewControllerDoneTapped:(id)sender {
  111. [self dismissViewControllerAnimated:YES completion:nil];
  112. }
  113. #pragma mark Transactions
  114. - (void)updateTransactions {
  115. self.networkTransactions = [FLEXNetworkRecorder.defaultRecorder networkTransactions];
  116. }
  117. - (void)setNetworkTransactions:(NSArray<FLEXNetworkTransaction *> *)networkTransactions {
  118. if (![_networkTransactions isEqual:networkTransactions]) {
  119. _networkTransactions = networkTransactions;
  120. [self updateBytesReceived];
  121. [self updateFilteredBytesReceived];
  122. }
  123. }
  124. - (void)updateBytesReceived {
  125. long long bytesReceived = 0;
  126. for (FLEXNetworkTransaction *transaction in self.networkTransactions) {
  127. bytesReceived += transaction.receivedDataLength;
  128. }
  129. self.bytesReceived = bytesReceived;
  130. [self updateFirstSectionHeader];
  131. }
  132. - (void)setFilteredNetworkTransactions:(NSArray<FLEXNetworkTransaction *> *)networkTransactions {
  133. if (![_filteredNetworkTransactions isEqual:networkTransactions]) {
  134. _filteredNetworkTransactions = networkTransactions;
  135. [self updateFilteredBytesReceived];
  136. }
  137. }
  138. - (void)updateFilteredBytesReceived {
  139. long long filteredBytesReceived = 0;
  140. for (FLEXNetworkTransaction *transaction in self.filteredNetworkTransactions) {
  141. filteredBytesReceived += transaction.receivedDataLength;
  142. }
  143. self.filteredBytesReceived = filteredBytesReceived;
  144. [self updateFirstSectionHeader];
  145. }
  146. #pragma mark Header
  147. - (void)updateFirstSectionHeader {
  148. UIView *view = [self.tableView headerViewForSection:0];
  149. if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  150. UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
  151. headerView.textLabel.text = [self headerText];
  152. [headerView setNeedsLayout];
  153. }
  154. }
  155. - (NSString *)headerText {
  156. long long bytesReceived = 0;
  157. NSInteger totalRequests = 0;
  158. if (self.searchController.isActive) {
  159. bytesReceived = self.filteredBytesReceived;
  160. totalRequests = self.filteredNetworkTransactions.count;
  161. } else {
  162. bytesReceived = self.bytesReceived;
  163. totalRequests = self.networkTransactions.count;
  164. }
  165. NSString *byteCountText = [NSByteCountFormatter
  166. stringFromByteCount:bytesReceived countStyle:NSByteCountFormatterCountStyleBinary
  167. ];
  168. NSString *requestsText = totalRequests == 1 ? @"Request" : @"Requests";
  169. return [NSString stringWithFormat:@"%@ %@ (%@ received)",
  170. @(totalRequests), requestsText, byteCountText
  171. ];
  172. }
  173. #pragma mark - FLEXGlobalsEntry
  174. + (NSString *)globalsEntryTitle:(FLEXGlobalsRow)row {
  175. return @"📡 Network History";
  176. }
  177. + (FLEXGlobalsEntryRowAction)globalsEntryRowAction:(FLEXGlobalsRow)row {
  178. return ^(UITableViewController *host) {
  179. if (FLEXNetworkObserver.isEnabled) {
  180. [host.navigationController pushViewController:[
  181. self globalsEntryViewController:row
  182. ] animated:YES];
  183. } else {
  184. [FLEXAlert makeAlert:^(FLEXAlert *make) {
  185. make.title(@"Network Monitor Disabled");
  186. make.message(@"You must enable network monitoring to proceed.");
  187. make.button(@"Turn On").handler(^(NSArray<NSString *> *strings) {
  188. FLEXNetworkObserver.enabled = YES;
  189. [host.navigationController pushViewController:[
  190. self globalsEntryViewController:row
  191. ] animated:YES];
  192. }).cancelStyle();
  193. make.button(@"Dismiss");
  194. } showFrom:host];
  195. }
  196. };
  197. }
  198. + (UIViewController *)globalsEntryViewController:(FLEXGlobalsRow)row {
  199. UIViewController *controller = [self new];
  200. controller.title = [self globalsEntryTitle:row];
  201. return controller;
  202. }
  203. #pragma mark - Notification Handlers
  204. - (void)handleNewTransactionRecordedNotification:(NSNotification *)notification {
  205. [self tryUpdateTransactions];
  206. }
  207. - (void)tryUpdateTransactions {
  208. // Don't do any view updating if we aren't in the view hierarchy
  209. if (!self.viewIfLoaded.window) {
  210. [self updateTransactions];
  211. self.pendingReload = YES;
  212. return;
  213. }
  214. // Let the previous row insert animation finish before starting a new one to avoid stomping.
  215. // We'll try calling the method again when the insertion completes,
  216. // and we properly no-op if there haven't been changes.
  217. if (self.rowInsertInProgress) {
  218. return;
  219. }
  220. if (self.searchController.isActive) {
  221. [self updateTransactions];
  222. [self updateSearchResults:self.searchText];
  223. return;
  224. }
  225. NSInteger existingRowCount = self.networkTransactions.count;
  226. [self updateTransactions];
  227. NSInteger newRowCount = self.networkTransactions.count;
  228. NSInteger addedRowCount = newRowCount - existingRowCount;
  229. if (addedRowCount != 0 && !self.isPresentingSearch) {
  230. // Insert animation if we're at the top.
  231. if (self.tableView.contentOffset.y <= 0.0 && addedRowCount > 0) {
  232. [CATransaction begin];
  233. self.rowInsertInProgress = YES;
  234. [CATransaction setCompletionBlock:^{
  235. self.rowInsertInProgress = NO;
  236. [self tryUpdateTransactions];
  237. }];
  238. NSMutableArray<NSIndexPath *> *indexPathsToReload = [NSMutableArray new];
  239. for (NSInteger row = 0; row < addedRowCount; row++) {
  240. [indexPathsToReload addObject:[NSIndexPath indexPathForRow:row inSection:0]];
  241. }
  242. [self.tableView insertRowsAtIndexPaths:indexPathsToReload withRowAnimation:UITableViewRowAnimationAutomatic];
  243. [CATransaction commit];
  244. } else {
  245. // Maintain the user's position if they've scrolled down.
  246. CGSize existingContentSize = self.tableView.contentSize;
  247. [self.tableView reloadData];
  248. CGFloat contentHeightChange = self.tableView.contentSize.height - existingContentSize.height;
  249. self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, self.tableView.contentOffset.y + contentHeightChange);
  250. }
  251. }
  252. }
  253. - (void)handleTransactionUpdatedNotification:(NSNotification *)notification {
  254. [self updateBytesReceived];
  255. [self updateFilteredBytesReceived];
  256. FLEXNetworkTransaction *transaction = notification.userInfo[kFLEXNetworkRecorderUserInfoTransactionKey];
  257. // Update both the main table view and search table view if needed.
  258. for (FLEXNetworkTransactionCell *cell in [self.tableView visibleCells]) {
  259. if ([cell.transaction isEqual:transaction]) {
  260. // Using -[UITableView reloadRowsAtIndexPaths:withRowAnimation:] is overkill here and kicks off a lot of
  261. // work that can make the table view somewhat unresponsive when lots of updates are streaming in.
  262. // We just need to tell the cell that it needs to re-layout.
  263. [cell setNeedsLayout];
  264. break;
  265. }
  266. }
  267. [self updateFirstSectionHeader];
  268. }
  269. - (void)handleTransactionsClearedNotification:(NSNotification *)notification {
  270. [self updateTransactions];
  271. [self.tableView reloadData];
  272. }
  273. - (void)handleNetworkObserverEnabledStateChangedNotification:(NSNotification *)notification {
  274. // Update the header, which displays a warning when network debugging is disabled
  275. [self updateFirstSectionHeader];
  276. }
  277. #pragma mark - Table view data source
  278. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  279. return self.searchController.isActive ? self.filteredNetworkTransactions.count : self.networkTransactions.count;
  280. }
  281. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  282. return [self headerText];
  283. }
  284. - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
  285. if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  286. UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
  287. headerView.textLabel.font = [UIFont systemFontOfSize:14.0 weight:UIFontWeightSemibold];
  288. }
  289. }
  290. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  291. FLEXNetworkTransactionCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXNetworkTransactionCellIdentifier forIndexPath:indexPath];
  292. cell.transaction = [self transactionAtIndexPath:indexPath];
  293. // Since we insert from the top, assign background colors bottom up to keep them consistent for each transaction.
  294. NSInteger totalRows = [tableView numberOfRowsInSection:indexPath.section];
  295. if ((totalRows - indexPath.row) % 2 == 0) {
  296. cell.backgroundColor = FLEXColor.secondaryBackgroundColor;
  297. } else {
  298. cell.backgroundColor = FLEXColor.primaryBackgroundColor;
  299. }
  300. return cell;
  301. }
  302. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  303. FLEXNetworkTransactionDetailController *detailViewController = [FLEXNetworkTransactionDetailController new];
  304. detailViewController.transaction = [self transactionAtIndexPath:indexPath];
  305. [self.navigationController pushViewController:detailViewController animated:YES];
  306. }
  307. #pragma mark - Menu Actions
  308. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
  309. return YES;
  310. }
  311. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
  312. return action == @selector(copy:);
  313. }
  314. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
  315. if (action == @selector(copy:)) {
  316. NSURLRequest *request = [self transactionAtIndexPath:indexPath].request;
  317. UIPasteboard.generalPasteboard.string = request.URL.absoluteString ?: @"";
  318. }
  319. }
  320. #if FLEX_AT_LEAST_IOS13_SDK
  321. - (UIContextMenuConfiguration *)tableView:(UITableView *)tableView contextMenuConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath point:(CGPoint)point __IOS_AVAILABLE(13.0) {
  322. NSURLRequest *request = [self transactionAtIndexPath:indexPath].request;
  323. return [UIContextMenuConfiguration
  324. configurationWithIdentifier:nil
  325. previewProvider:nil
  326. actionProvider:^UIMenu *(NSArray<UIMenuElement *> *suggestedActions) {
  327. UIAction *copy = [UIAction
  328. actionWithTitle:@"Copy"
  329. image:nil
  330. identifier:nil
  331. handler:^(__kindof UIAction *action) {
  332. UIPasteboard.generalPasteboard.string = request.URL.absoluteString ?: @"";
  333. }
  334. ];
  335. UIAction *blacklist = [UIAction
  336. actionWithTitle:[NSString stringWithFormat:@"Blacklist '%@'", request.URL.host]
  337. image:nil
  338. identifier:nil
  339. handler:^(__kindof UIAction *action) {
  340. NSMutableArray *blacklist = FLEXNetworkRecorder.defaultRecorder.hostBlacklist;
  341. [blacklist addObject:request.URL.host];
  342. [FLEXNetworkRecorder.defaultRecorder clearBlacklistedTransactions];
  343. [FLEXNetworkRecorder.defaultRecorder synchronizeBlacklist];
  344. [self tryUpdateTransactions];
  345. }
  346. ];
  347. return [UIMenu
  348. menuWithTitle:@"" image:nil identifier:nil
  349. options:UIMenuOptionsDisplayInline
  350. children:@[copy, blacklist]
  351. ];
  352. }
  353. ];
  354. }
  355. #endif
  356. - (FLEXNetworkTransaction *)transactionAtIndexPath:(NSIndexPath *)indexPath {
  357. return self.searchController.isActive ? self.filteredNetworkTransactions[indexPath.row] : self.networkTransactions[indexPath.row];
  358. }
  359. #pragma mark - Search Bar
  360. - (void)updateSearchResults:(NSString *)searchString {
  361. if (!searchString.length) {
  362. self.filteredNetworkTransactions = self.networkTransactions;
  363. [self.tableView reloadData];
  364. } else {
  365. [self onBackgroundQueue:^NSArray *{
  366. return [self.networkTransactions flex_filtered:^BOOL(FLEXNetworkTransaction *entry, NSUInteger idx) {
  367. return [entry.request.URL.absoluteString localizedCaseInsensitiveContainsString:searchString];
  368. }];
  369. } thenOnMainQueue:^(NSArray *filteredNetworkTransactions) {
  370. if ([self.searchText isEqual:searchString]) {
  371. self.filteredNetworkTransactions = filteredNetworkTransactions;
  372. [self.tableView reloadData];
  373. }
  374. }];
  375. }
  376. }
  377. #pragma mark UISearchControllerDelegate
  378. - (void)willPresentSearchController:(UISearchController *)searchController {
  379. self.isPresentingSearch = YES;
  380. }
  381. - (void)didPresentSearchController:(UISearchController *)searchController {
  382. self.isPresentingSearch = NO;
  383. }
  384. - (void)willDismissSearchController:(UISearchController *)searchController {
  385. [self.tableView reloadData];
  386. }
  387. @end