FLEXNetworkMITMViewController.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. //
  2. // FLEXNetworkMITMViewController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 2/8/15.
  6. // Copyright (c) 2020 Flipboard. 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 "FLEXNetworkTransactionTableViewCell.h"
  15. #import "FLEXNetworkTransactionDetailTableViewController.h"
  16. #import "FLEXNetworkSettingsTableViewController.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. itemWithImage:FLEXResources.gearIcon
  42. target:self
  43. action:@selector(settingsButtonTapped:)
  44. ],
  45. [[UIBarButtonItem
  46. systemItem:UIBarButtonSystemItemTrash
  47. target:self
  48. action:@selector(trashButtonTapped:)
  49. ] withTintColor:UIColor.redColor]
  50. ]];
  51. [self.tableView
  52. registerClass:[FLEXNetworkTransactionTableViewCell class]
  53. forCellReuseIdentifier:kFLEXNetworkTransactionCellIdentifier
  54. ];
  55. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  56. self.tableView.rowHeight = FLEXNetworkTransactionTableViewCell.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:(id)sender {
  91. UIViewController *settings = [FLEXNetworkSettingsTableViewController 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:(id)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];
  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 updating if we aren't in the view hierarchy
  209. if (!self.viewIfLoaded.window) {
  210. self.pendingReload = YES;
  211. return;
  212. }
  213. // Let the previous row insert animation finish before starting a new one to avoid stomping.
  214. // We'll try calling the method again when the insertion completes, and we properly no-op if there haven't been changes.
  215. if (self.rowInsertInProgress) {
  216. return;
  217. }
  218. if (self.searchController.isActive) {
  219. [self updateTransactions];
  220. [self updateSearchResults:nil];
  221. return;
  222. }
  223. NSInteger existingRowCount = self.networkTransactions.count;
  224. [self updateTransactions];
  225. NSInteger newRowCount = self.networkTransactions.count;
  226. NSInteger addedRowCount = newRowCount - existingRowCount;
  227. if (addedRowCount != 0 && !self.isPresentingSearch) {
  228. // Insert animation if we're at the top.
  229. if (self.tableView.contentOffset.y <= 0.0 && addedRowCount > 0) {
  230. [CATransaction begin];
  231. self.rowInsertInProgress = YES;
  232. [CATransaction setCompletionBlock:^{
  233. self.rowInsertInProgress = NO;
  234. [self tryUpdateTransactions];
  235. }];
  236. NSMutableArray<NSIndexPath *> *indexPathsToReload = [NSMutableArray new];
  237. for (NSInteger row = 0; row < addedRowCount; row++) {
  238. [indexPathsToReload addObject:[NSIndexPath indexPathForRow:row inSection:0]];
  239. }
  240. [self.tableView insertRowsAtIndexPaths:indexPathsToReload withRowAnimation:UITableViewRowAnimationAutomatic];
  241. [CATransaction commit];
  242. } else {
  243. // Maintain the user's position if they've scrolled down.
  244. CGSize existingContentSize = self.tableView.contentSize;
  245. [self.tableView reloadData];
  246. CGFloat contentHeightChange = self.tableView.contentSize.height - existingContentSize.height;
  247. self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, self.tableView.contentOffset.y + contentHeightChange);
  248. }
  249. }
  250. }
  251. - (void)handleTransactionUpdatedNotification:(NSNotification *)notification {
  252. [self updateBytesReceived];
  253. [self updateFilteredBytesReceived];
  254. FLEXNetworkTransaction *transaction = notification.userInfo[kFLEXNetworkRecorderUserInfoTransactionKey];
  255. // Update both the main table view and search table view if needed.
  256. for (FLEXNetworkTransactionTableViewCell *cell in [self.tableView visibleCells]) {
  257. if ([cell.transaction isEqual:transaction]) {
  258. // Using -[UITableView reloadRowsAtIndexPaths:withRowAnimation:] is overkill here and kicks off a lot of
  259. // work that can make the table view somewhat unresponsive when lots of updates are streaming in.
  260. // We just need to tell the cell that it needs to re-layout.
  261. [cell setNeedsLayout];
  262. break;
  263. }
  264. }
  265. [self updateFirstSectionHeader];
  266. }
  267. - (void)handleTransactionsClearedNotification:(NSNotification *)notification {
  268. [self updateTransactions];
  269. [self.tableView reloadData];
  270. }
  271. - (void)handleNetworkObserverEnabledStateChangedNotification:(NSNotification *)notification {
  272. // Update the header, which displays a warning when network debugging is disabled
  273. [self updateFirstSectionHeader];
  274. }
  275. #pragma mark - Table view data source
  276. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  277. return self.searchController.isActive ? self.filteredNetworkTransactions.count : self.networkTransactions.count;
  278. }
  279. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  280. return [self headerText];
  281. }
  282. - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
  283. if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  284. UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
  285. headerView.textLabel.font = [UIFont systemFontOfSize:14.0 weight:UIFontWeightSemibold];
  286. }
  287. }
  288. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  289. FLEXNetworkTransactionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXNetworkTransactionCellIdentifier forIndexPath:indexPath];
  290. cell.transaction = [self transactionAtIndexPath:indexPath];
  291. // Since we insert from the top, assign background colors bottom up to keep them consistent for each transaction.
  292. NSInteger totalRows = [tableView numberOfRowsInSection:indexPath.section];
  293. if ((totalRows - indexPath.row) % 2 == 0) {
  294. cell.backgroundColor = FLEXColor.secondaryBackgroundColor;
  295. } else {
  296. cell.backgroundColor = FLEXColor.primaryBackgroundColor;
  297. }
  298. return cell;
  299. }
  300. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  301. FLEXNetworkTransactionDetailTableViewController *detailViewController = [FLEXNetworkTransactionDetailTableViewController new];
  302. detailViewController.transaction = [self transactionAtIndexPath:indexPath];
  303. [self.navigationController pushViewController:detailViewController animated:YES];
  304. }
  305. #pragma mark - Menu Actions
  306. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
  307. return YES;
  308. }
  309. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
  310. return action == @selector(copy:);
  311. }
  312. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
  313. if (action == @selector(copy:)) {
  314. NSURLRequest *request = [self transactionAtIndexPath:indexPath].request;
  315. UIPasteboard.generalPasteboard.string = request.URL.absoluteString ?: @"";
  316. }
  317. }
  318. #if FLEX_AT_LEAST_IOS13_SDK
  319. - (UIContextMenuConfiguration *)tableView:(UITableView *)tableView contextMenuConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath point:(CGPoint)point __IOS_AVAILABLE(13.0) {
  320. return [UIContextMenuConfiguration
  321. configurationWithIdentifier:nil
  322. previewProvider:nil
  323. actionProvider:^UIMenu *(NSArray<UIMenuElement *> *suggestedActions) {
  324. UIAction *copy = [UIAction
  325. actionWithTitle:@"Copy"
  326. image:nil
  327. identifier:nil
  328. handler:^(__kindof UIAction *action) {
  329. NSURLRequest *request = [self transactionAtIndexPath:indexPath].request;
  330. UIPasteboard.generalPasteboard.string = request.URL.absoluteString ?: @"";
  331. }
  332. ];
  333. return [UIMenu
  334. menuWithTitle:@"" image:nil identifier:nil
  335. options:UIMenuOptionsDisplayInline
  336. children:@[copy]
  337. ];
  338. }
  339. ];
  340. }
  341. #endif
  342. - (FLEXNetworkTransaction *)transactionAtIndexPath:(NSIndexPath *)indexPath {
  343. return self.searchController.isActive ? self.filteredNetworkTransactions[indexPath.row] : self.networkTransactions[indexPath.row];
  344. }
  345. #pragma mark - Search Bar
  346. - (void)updateSearchResults:(NSString *)searchString {
  347. if (!searchString) {
  348. self.filteredNetworkTransactions = self.networkTransactions;
  349. [self.tableView reloadData];
  350. } else {
  351. [self onBackgroundQueue:^NSArray *{
  352. return [self.networkTransactions flex_filtered:^BOOL(FLEXNetworkTransaction *entry, NSUInteger idx) {
  353. return [entry.request.URL.absoluteString localizedCaseInsensitiveContainsString:searchString];
  354. }];
  355. } thenOnMainQueue:^(NSArray *filteredNetworkTransactions) {
  356. if ([self.searchText isEqual:searchString]) {
  357. self.filteredNetworkTransactions = filteredNetworkTransactions;
  358. [self.tableView reloadData];
  359. }
  360. }];
  361. }
  362. }
  363. #pragma mark UISearchControllerDelegate
  364. - (void)willPresentSearchController:(UISearchController *)searchController {
  365. self.isPresentingSearch = YES;
  366. }
  367. - (void)didPresentSearchController:(UISearchController *)searchController {
  368. self.isPresentingSearch = NO;
  369. }
  370. - (void)willDismissSearchController:(UISearchController *)searchController {
  371. [self.tableView reloadData];
  372. }
  373. @end