FLEXNetworkMITMViewController.m 17 KB

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