FLEXNetworkTransactionDetailTableViewController.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. //
  2. // FLEXNetworkTransactionDetailTableViewController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 2/10/15.
  6. // Copyright (c) 2015 Flipboard. All rights reserved.
  7. //
  8. #import "FLEXNetworkTransactionDetailTableViewController.h"
  9. #import "FLEXNetworkRecorder.h"
  10. #import "FLEXNetworkTransaction.h"
  11. #import "FLEXWebViewController.h"
  12. #import "FLEXImagePreviewViewController.h"
  13. #import "FLEXMultilineTableViewCell.h"
  14. #import "FLEXUtility.h"
  15. @interface FLEXNetworkDetailSection : NSObject
  16. @property (nonatomic, copy) NSString *title;
  17. @property (nonatomic, copy) NSArray *rows;
  18. @end
  19. @implementation FLEXNetworkDetailSection
  20. @end
  21. typedef UIViewController *(^FLEXNetworkDetailRowSelectionFuture)(void);
  22. @interface FLEXNetworkDetailRow : NSObject
  23. @property (nonatomic, copy) NSString *title;
  24. @property (nonatomic, copy) NSString *detailText;
  25. @property (nonatomic, copy) FLEXNetworkDetailRowSelectionFuture selectionFuture;
  26. @end
  27. @implementation FLEXNetworkDetailRow
  28. @end
  29. @interface FLEXNetworkTransactionDetailTableViewController ()
  30. @property (nonatomic, copy) NSArray *sections;
  31. @end
  32. @implementation FLEXNetworkTransactionDetailTableViewController
  33. - (instancetype)initWithStyle:(UITableViewStyle)style
  34. {
  35. // Force grouped style
  36. self = [super initWithStyle:UITableViewStyleGrouped];
  37. if (self) {
  38. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTransactionUpdatedNotification:) name:kFLEXNetworkRecorderTransactionUpdatedNotification object:nil];
  39. }
  40. return self;
  41. }
  42. - (void)viewDidLoad
  43. {
  44. [super viewDidLoad];
  45. [self.tableView registerClass:[FLEXMultilineTableViewCell class] forCellReuseIdentifier:kFLEXMultilineTableViewCellIdentifier];
  46. }
  47. - (void)setTransaction:(FLEXNetworkTransaction *)transaction
  48. {
  49. if (![_transaction isEqual:transaction]) {
  50. _transaction = transaction;
  51. self.title = [transaction.request.URL lastPathComponent];
  52. [self rebuildTableSections];
  53. }
  54. }
  55. - (void)setSections:(NSArray *)sections
  56. {
  57. if (![_sections isEqual:sections]) {
  58. _sections = [sections copy];
  59. [self.tableView reloadData];
  60. }
  61. }
  62. - (void)rebuildTableSections
  63. {
  64. NSMutableArray *sections = [NSMutableArray array];
  65. FLEXNetworkDetailSection *generalSection = [[self class] generalSectionForTransaction:self.transaction];
  66. if ([generalSection.rows count] > 0) {
  67. [sections addObject:generalSection];
  68. }
  69. FLEXNetworkDetailSection *requestHeadersSection = [[self class] requestHeadersSectionForTransaction:self.transaction];
  70. if ([requestHeadersSection.rows count] > 0) {
  71. [sections addObject:requestHeadersSection];
  72. }
  73. FLEXNetworkDetailSection *queryParametersSection = [[self class] queryParametersSectionForTransaction:self.transaction];
  74. if ([queryParametersSection.rows count] > 0) {
  75. [sections addObject:queryParametersSection];
  76. }
  77. FLEXNetworkDetailSection *postBodySection = [[self class] postBodySectionForTransaction:self.transaction];
  78. if ([postBodySection.rows count] > 0) {
  79. [sections addObject:postBodySection];
  80. }
  81. FLEXNetworkDetailSection *responseHeadersSection = [[self class] responseHeadersSectionForTransaction:self.transaction];
  82. if ([responseHeadersSection.rows count] > 0) {
  83. [sections addObject:responseHeadersSection];
  84. }
  85. self.sections = sections;
  86. }
  87. - (void)handleTransactionUpdatedNotification:(NSNotification *)notification
  88. {
  89. FLEXNetworkTransaction *transaction = [[notification userInfo] objectForKey:kFLEXNetworkRecorderUserInfoTransactionKey];
  90. if (transaction == self.transaction) {
  91. [self rebuildTableSections];
  92. }
  93. }
  94. #pragma mark - Table view data source
  95. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  96. {
  97. return [self.sections count];
  98. }
  99. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  100. {
  101. FLEXNetworkDetailSection *sectionModel = [self.sections objectAtIndex:section];
  102. return [sectionModel.rows count];
  103. }
  104. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  105. {
  106. FLEXNetworkDetailSection *sectionModel = [self.sections objectAtIndex:section];
  107. return sectionModel.title;
  108. }
  109. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  110. {
  111. FLEXMultilineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXMultilineTableViewCellIdentifier forIndexPath:indexPath];
  112. FLEXNetworkDetailRow *rowModel = [self rowModelAtIndexPath:indexPath];
  113. cell.textLabel.attributedText = [[self class] attributedTextForRow:rowModel];
  114. cell.accessoryType = rowModel.selectionFuture ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
  115. cell.selectionStyle = rowModel.selectionFuture ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone;
  116. return cell;
  117. }
  118. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  119. {
  120. FLEXNetworkDetailRow *rowModel = [self rowModelAtIndexPath:indexPath];
  121. UIViewController *viewControllerToPush = nil;
  122. if (rowModel.selectionFuture) {
  123. viewControllerToPush = rowModel.selectionFuture();
  124. }
  125. if (viewControllerToPush) {
  126. [self.navigationController pushViewController:viewControllerToPush animated:YES];
  127. }
  128. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  129. }
  130. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  131. {
  132. FLEXNetworkDetailRow *row = [self rowModelAtIndexPath:indexPath];
  133. NSAttributedString *attributedText = [[self class] attributedTextForRow:row];
  134. BOOL showsAccessory = row.selectionFuture != nil;
  135. return [FLEXMultilineTableViewCell preferredHeightWithAttributedText:attributedText inTableViewWidth:self.tableView.bounds.size.width style:UITableViewStyleGrouped showsAccessory:showsAccessory];
  136. }
  137. - (FLEXNetworkDetailRow *)rowModelAtIndexPath:(NSIndexPath *)indexPath
  138. {
  139. FLEXNetworkDetailSection *sectionModel = [self.sections objectAtIndex:indexPath.section];
  140. return [sectionModel.rows objectAtIndex:indexPath.row];
  141. }
  142. #pragma mark - Cell Copying
  143. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
  144. {
  145. return YES;
  146. }
  147. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  148. {
  149. return action == @selector(copy:);
  150. }
  151. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  152. {
  153. if (action == @selector(copy:)) {
  154. FLEXNetworkDetailRow *row = [self rowModelAtIndexPath:indexPath];
  155. [[UIPasteboard generalPasteboard] setString:row.detailText];
  156. }
  157. }
  158. #pragma mark - View Configuration
  159. + (NSAttributedString *)attributedTextForRow:(FLEXNetworkDetailRow *)row
  160. {
  161. NSDictionary *titleAttributes = @{ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Medium" size:12.0],
  162. NSForegroundColorAttributeName : [UIColor colorWithWhite:0.5 alpha:1.0] };
  163. NSDictionary *detailAttributes = @{ NSFontAttributeName : [FLEXUtility defaultTableViewCellLabelFont],
  164. NSForegroundColorAttributeName : [UIColor blackColor] };
  165. NSString *title = [NSString stringWithFormat:@"%@: ", row.title];
  166. NSString *detailText = row.detailText ?: @"";
  167. NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
  168. [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:title attributes:titleAttributes]];
  169. [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:detailText attributes:detailAttributes]];
  170. return attributedText;
  171. }
  172. #pragma mark - Table Data Generation
  173. + (FLEXNetworkDetailSection *)generalSectionForTransaction:(FLEXNetworkTransaction *)transaction
  174. {
  175. NSMutableArray *rows = [NSMutableArray array];
  176. FLEXNetworkDetailRow *requestURLRow = [[FLEXNetworkDetailRow alloc] init];
  177. requestURLRow.title = @"Request URL";
  178. NSURL *url = transaction.request.URL;
  179. requestURLRow.detailText = url.absoluteString;
  180. requestURLRow.selectionFuture = ^{
  181. UIViewController *urlWebViewController = [[FLEXWebViewController alloc] initWithURL:url];
  182. urlWebViewController.title = url.absoluteString;
  183. return urlWebViewController;
  184. };
  185. [rows addObject:requestURLRow];
  186. FLEXNetworkDetailRow *requestMethodRow = [[FLEXNetworkDetailRow alloc] init];
  187. requestMethodRow.title = @"Request Method";
  188. requestMethodRow.detailText = transaction.request.HTTPMethod;
  189. [rows addObject:requestMethodRow];
  190. if ([transaction.request.HTTPBody length] > 0) {
  191. FLEXNetworkDetailRow *postBodySizeRow = [[FLEXNetworkDetailRow alloc] init];
  192. postBodySizeRow.title = @"Request Body Size";
  193. postBodySizeRow.detailText = [NSByteCountFormatter stringFromByteCount:[transaction.request.HTTPBody length] countStyle:NSByteCountFormatterCountStyleBinary];
  194. [rows addObject:postBodySizeRow];
  195. FLEXNetworkDetailRow *postBodyRow = [[FLEXNetworkDetailRow alloc] init];
  196. postBodyRow.title = @"Request Body";
  197. postBodyRow.detailText = @"tap to view";
  198. postBodyRow.selectionFuture = ^{
  199. NSString *contentType = [transaction.request valueForHTTPHeaderField:@"Content-Type"];
  200. UIViewController *detailViewController = [self detailViewControllerForMIMEType:contentType data:[self postBodyDataForTransaction:transaction]];
  201. if (detailViewController) {
  202. detailViewController.title = @"Request Body";
  203. } else {
  204. NSString *alertMessage = [NSString stringWithFormat:@"FLEX does not have a viewer for request body data with MIME type: %@", [transaction.request valueForHTTPHeaderField:@"Content-Type"]];
  205. [[[UIAlertView alloc] initWithTitle:@"Can't View Body Data" message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
  206. }
  207. return detailViewController;
  208. };
  209. [rows addObject:postBodyRow];
  210. }
  211. NSString *statusCodeString = [FLEXUtility statusCodeStringFromURLResponse:transaction.response];
  212. if ([statusCodeString length] > 0) {
  213. FLEXNetworkDetailRow *statusCodeRow = [[FLEXNetworkDetailRow alloc] init];
  214. statusCodeRow.title = @"Status Code";
  215. statusCodeRow.detailText = statusCodeString;
  216. [rows addObject:statusCodeRow];
  217. }
  218. if (transaction.error) {
  219. FLEXNetworkDetailRow *errorRow = [[FLEXNetworkDetailRow alloc] init];
  220. errorRow.title = @"Error";
  221. errorRow.detailText = transaction.error.localizedDescription;
  222. [rows addObject:errorRow];
  223. }
  224. FLEXNetworkDetailRow *responseBodyRow = [[FLEXNetworkDetailRow alloc] init];
  225. responseBodyRow.title = @"Response Body";
  226. NSData *responseData = [[FLEXNetworkRecorder defaultRecorder] cachedResponseBodyForTransaction:transaction];
  227. if ([responseData length] > 0) {
  228. responseBodyRow.detailText = @"tap to view";
  229. // Avoid a long lived strong reference to the response data in case we need to purge it from the cache.
  230. __weak NSData *weakResponseData = responseData;
  231. responseBodyRow.selectionFuture = ^{
  232. UIViewController *responseBodyDetailViewController = nil;
  233. NSData *strongResponseData = weakResponseData;
  234. if (strongResponseData) {
  235. responseBodyDetailViewController = [self detailViewControllerForMIMEType:transaction.response.MIMEType data:strongResponseData];
  236. if (!responseBodyDetailViewController) {
  237. NSString *alertMessage = [NSString stringWithFormat:@"FLEX does not have a viewer for responses with MIME type: %@", transaction.response.MIMEType];
  238. [[[UIAlertView alloc] initWithTitle:@"Can't View Response" message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
  239. }
  240. responseBodyDetailViewController.title = @"Response";
  241. } else {
  242. NSString *alertMessage = @"The response has been purged from the cache";
  243. [[[UIAlertView alloc] initWithTitle:@"Can't View Response" message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
  244. }
  245. return responseBodyDetailViewController;
  246. };
  247. } else {
  248. BOOL emptyResponse = transaction.receivedDataLength == 0;
  249. responseBodyRow.detailText = emptyResponse ? @"empty" : @"not in cache";
  250. }
  251. [rows addObject:responseBodyRow];
  252. FLEXNetworkDetailRow *responseSizeRow = [[FLEXNetworkDetailRow alloc] init];
  253. responseSizeRow.title = @"Response Size";
  254. responseSizeRow.detailText = [NSByteCountFormatter stringFromByteCount:transaction.receivedDataLength countStyle:NSByteCountFormatterCountStyleBinary];
  255. [rows addObject:responseSizeRow];
  256. FLEXNetworkDetailRow *mimeTypeRow = [[FLEXNetworkDetailRow alloc] init];
  257. mimeTypeRow.title = @"MIME Type";
  258. mimeTypeRow.detailText = transaction.response.MIMEType;
  259. [rows addObject:mimeTypeRow];
  260. FLEXNetworkDetailRow *mechanismRow = [[FLEXNetworkDetailRow alloc] init];
  261. mechanismRow.title = @"Mechanism";
  262. mechanismRow.detailText = transaction.requestMechanism;
  263. [rows addObject:mechanismRow];
  264. NSDateFormatter *startTimeFormatter = [[NSDateFormatter alloc] init];
  265. startTimeFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
  266. FLEXNetworkDetailRow *localStartTimeRow = [[FLEXNetworkDetailRow alloc] init];
  267. localStartTimeRow.title = [NSString stringWithFormat:@"Start Time (%@)", [[NSTimeZone localTimeZone] abbreviationForDate:transaction.startTime]];
  268. localStartTimeRow.detailText = [startTimeFormatter stringFromDate:transaction.startTime];
  269. [rows addObject:localStartTimeRow];
  270. startTimeFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  271. FLEXNetworkDetailRow *utcStartTimeRow = [[FLEXNetworkDetailRow alloc] init];
  272. utcStartTimeRow.title = @"Start Time (UTC)";
  273. utcStartTimeRow.detailText = [startTimeFormatter stringFromDate:transaction.startTime];
  274. [rows addObject:utcStartTimeRow];
  275. FLEXNetworkDetailRow *unixStartTime = [[FLEXNetworkDetailRow alloc] init];
  276. unixStartTime.title = @"Unix Start Time";
  277. unixStartTime.detailText = [NSString stringWithFormat:@"%f", [transaction.startTime timeIntervalSince1970]];
  278. [rows addObject:unixStartTime];
  279. FLEXNetworkDetailRow *durationRow = [[FLEXNetworkDetailRow alloc] init];
  280. durationRow.title = @"Total Duration";
  281. durationRow.detailText = [FLEXUtility stringFromRequestDuration:transaction.duration];
  282. [rows addObject:durationRow];
  283. FLEXNetworkDetailRow *latencyRow = [[FLEXNetworkDetailRow alloc] init];
  284. latencyRow.title = @"Latency";
  285. latencyRow.detailText = [FLEXUtility stringFromRequestDuration:transaction.latency];
  286. [rows addObject:latencyRow];
  287. FLEXNetworkDetailSection *generalSection = [[FLEXNetworkDetailSection alloc] init];
  288. generalSection.title = @"General";
  289. generalSection.rows = rows;
  290. return generalSection;
  291. }
  292. + (FLEXNetworkDetailSection *)requestHeadersSectionForTransaction:(FLEXNetworkTransaction *)transaction
  293. {
  294. FLEXNetworkDetailSection *requestHeadersSection = [[FLEXNetworkDetailSection alloc] init];
  295. requestHeadersSection.title = @"Request Headers";
  296. requestHeadersSection.rows = [self networkDetailRowsFromDictionary:transaction.request.allHTTPHeaderFields];
  297. return requestHeadersSection;
  298. }
  299. + (FLEXNetworkDetailSection *)postBodySectionForTransaction:(FLEXNetworkTransaction *)transaction
  300. {
  301. FLEXNetworkDetailSection *postBodySection = [[FLEXNetworkDetailSection alloc] init];
  302. postBodySection.title = @"Request Body Parameters";
  303. if ([transaction.request.HTTPBody length] > 0) {
  304. NSString *contentType = [transaction.request valueForHTTPHeaderField:@"Content-Type"];
  305. if ([contentType hasPrefix:@"application/x-www-form-urlencoded"]) {
  306. NSString *bodyString = [[NSString alloc] initWithData:[self postBodyDataForTransaction:transaction] encoding:NSUTF8StringEncoding];
  307. postBodySection.rows = [self networkDetailRowsFromDictionary:[FLEXUtility dictionaryFromQuery:bodyString]];
  308. }
  309. }
  310. return postBodySection;
  311. }
  312. + (FLEXNetworkDetailSection *)queryParametersSectionForTransaction:(FLEXNetworkTransaction *)transaction
  313. {
  314. NSDictionary *queryDictionary = [FLEXUtility dictionaryFromQuery:transaction.request.URL.query];
  315. FLEXNetworkDetailSection *querySection = [[FLEXNetworkDetailSection alloc] init];
  316. querySection.title = @"Query Parameters";
  317. querySection.rows = [self networkDetailRowsFromDictionary:queryDictionary];
  318. return querySection;
  319. }
  320. + (FLEXNetworkDetailSection *)responseHeadersSectionForTransaction:(FLEXNetworkTransaction *)transaction
  321. {
  322. FLEXNetworkDetailSection *responseHeadersSection = [[FLEXNetworkDetailSection alloc] init];
  323. responseHeadersSection.title = @"Response Headers";
  324. if ([transaction.response isKindOfClass:[NSHTTPURLResponse class]]) {
  325. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)transaction.response;
  326. responseHeadersSection.rows = [self networkDetailRowsFromDictionary:httpResponse.allHeaderFields];
  327. }
  328. return responseHeadersSection;
  329. }
  330. + (NSArray *)networkDetailRowsFromDictionary:(NSDictionary *)dictionary
  331. {
  332. NSMutableArray *rows = [NSMutableArray arrayWithCapacity:[dictionary count]];
  333. NSArray *sortedKeys = [[dictionary allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
  334. for (NSString *key in sortedKeys) {
  335. NSString *value = [dictionary objectForKey:key];
  336. FLEXNetworkDetailRow *row = [[FLEXNetworkDetailRow alloc] init];
  337. row.title = key;
  338. row.detailText = [value description];
  339. [rows addObject:row];
  340. }
  341. return [rows copy];
  342. }
  343. + (UIViewController *)detailViewControllerForMIMEType:(NSString *)mimeType data:(NSData *)data
  344. {
  345. // FIXME (RKO): Don't rely on UTF8 string encoding
  346. UIViewController *detailViewController = nil;
  347. if ([mimeType isEqual:@"application/json"] || [mimeType isEqual:@"application/javascript"] || [mimeType isEqual:@"text/javascript"]) {
  348. NSString *prettyJSON = [FLEXUtility prettyJSONStringFromData:data];
  349. if ([prettyJSON length] > 0) {
  350. detailViewController = [[FLEXWebViewController alloc] initWithText:prettyJSON];
  351. }
  352. } else if ([mimeType hasPrefix:@"image/"]) {
  353. UIImage *image = [UIImage imageWithData:data];
  354. detailViewController = [[FLEXImagePreviewViewController alloc] initWithImage:image];
  355. } else if ([mimeType isEqual:@"application/x-plist"]) {
  356. id propertyList = [NSPropertyListSerialization propertyListWithData:data options:0 format:NULL error:NULL];
  357. detailViewController = [[FLEXWebViewController alloc] initWithText:[propertyList description]];
  358. }
  359. // Fall back to trying to show the response as text
  360. if (!detailViewController) {
  361. NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  362. if ([text length] > 0) {
  363. detailViewController = [[FLEXWebViewController alloc] initWithText:text];
  364. }
  365. }
  366. return detailViewController;
  367. }
  368. + (NSData *)postBodyDataForTransaction:(FLEXNetworkTransaction *)transaction
  369. {
  370. NSData *bodyData = transaction.request.HTTPBody;
  371. if ([bodyData length] > 0) {
  372. NSString *contentEncoding = [transaction.request valueForHTTPHeaderField:@"Content-Encoding"];
  373. if ([contentEncoding rangeOfString:@"deflate" options:NSCaseInsensitiveSearch].length > 0 || [contentEncoding rangeOfString:@"gzip" options:NSCaseInsensitiveSearch].length > 0) {
  374. bodyData = [FLEXUtility inflatedDataFromCompressedData:bodyData];
  375. }
  376. }
  377. return bodyData;
  378. }
  379. @end