FLEXNetworkMITMViewController.m 15 KB

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