FLEXNetworkMITMViewController.m 15 KB

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