FLEXNetworkTransactionDetailTableViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 *responseHeadersSection = [[self class] responseHeadersSectionForTransaction:self.transaction];
  78. if ([responseHeadersSection.rows count] > 0) {
  79. [sections addObject:responseHeadersSection];
  80. }
  81. self.sections = sections;
  82. }
  83. - (void)handleTransactionUpdatedNotification:(NSNotification *)notification
  84. {
  85. FLEXNetworkTransaction *transaction = [[notification userInfo] objectForKey:kFLEXNetworkRecorderUserInfoTransactionKey];
  86. if (transaction == self.transaction) {
  87. [self rebuildTableSections];
  88. }
  89. }
  90. #pragma mark - Table view data source
  91. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  92. {
  93. return [self.sections count];
  94. }
  95. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  96. {
  97. FLEXNetworkDetailSection *sectionModel = [self.sections objectAtIndex:section];
  98. return [sectionModel.rows count];
  99. }
  100. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  101. {
  102. FLEXNetworkDetailSection *sectionModel = [self.sections objectAtIndex:section];
  103. return sectionModel.title;
  104. }
  105. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  106. {
  107. FLEXMultilineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXMultilineTableViewCellIdentifier forIndexPath:indexPath];
  108. FLEXNetworkDetailRow *rowModel = [self rowModelAtIndexPath:indexPath];
  109. cell.textLabel.attributedText = [[self class] attributedTextForRow:rowModel];
  110. cell.accessoryType = rowModel.selectionFuture ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
  111. cell.selectionStyle = rowModel.selectionFuture ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone;
  112. return cell;
  113. }
  114. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  115. {
  116. FLEXNetworkDetailRow *rowModel = [self rowModelAtIndexPath:indexPath];
  117. UIViewController *viewControllerToPush = nil;
  118. if (rowModel.selectionFuture) {
  119. viewControllerToPush = rowModel.selectionFuture();
  120. }
  121. if (viewControllerToPush) {
  122. [self.navigationController pushViewController:viewControllerToPush animated:YES];
  123. }
  124. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  125. }
  126. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  127. {
  128. FLEXNetworkDetailRow *row = [self rowModelAtIndexPath:indexPath];
  129. NSAttributedString *attributedText = [[self class] attributedTextForRow:row];
  130. BOOL showsAccessory = row.selectionFuture != nil;
  131. return [FLEXMultilineTableViewCell preferredHeightWithAttributedText:attributedText inTableViewWidth:self.tableView.bounds.size.width style:UITableViewStyleGrouped showsAccessory:showsAccessory];
  132. }
  133. - (FLEXNetworkDetailRow *)rowModelAtIndexPath:(NSIndexPath *)indexPath
  134. {
  135. FLEXNetworkDetailSection *sectionModel = [self.sections objectAtIndex:indexPath.section];
  136. return [sectionModel.rows objectAtIndex:indexPath.row];
  137. }
  138. #pragma mark - View Configuration
  139. + (NSAttributedString *)attributedTextForRow:(FLEXNetworkDetailRow *)row
  140. {
  141. NSDictionary *titleAttributes = @{ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Medium" size:12.0],
  142. NSForegroundColorAttributeName : [UIColor colorWithWhite:0.5 alpha:1.0] };
  143. NSDictionary *detailAttributes = @{ NSFontAttributeName : [FLEXUtility defaultTableViewCellLabelFont],
  144. NSForegroundColorAttributeName : [UIColor blackColor] };
  145. NSString *title = [NSString stringWithFormat:@"%@: ", row.title];
  146. NSString *detailText = row.detailText ?: @"";
  147. NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
  148. [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:title attributes:titleAttributes]];
  149. [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:detailText attributes:detailAttributes]];
  150. return attributedText;
  151. }
  152. #pragma mark - Table Data Generation
  153. + (FLEXNetworkDetailSection *)generalSectionForTransaction:(FLEXNetworkTransaction *)transaction
  154. {
  155. NSMutableArray *rows = [NSMutableArray array];
  156. FLEXNetworkDetailRow *requestURLRow = [[FLEXNetworkDetailRow alloc] init];
  157. requestURLRow.title = @"Request URL";
  158. NSURL *url = transaction.request.URL;
  159. requestURLRow.detailText = url.absoluteString;
  160. requestURLRow.selectionFuture = ^{
  161. UIViewController *urlWebViewController = [[FLEXWebViewController alloc] initWithURL:url];
  162. urlWebViewController.title = url.absoluteString;
  163. return urlWebViewController;
  164. };
  165. [rows addObject:requestURLRow];
  166. FLEXNetworkDetailRow *responseBodyRow = [[FLEXNetworkDetailRow alloc] init];
  167. responseBodyRow.title = @"Response Body";
  168. NSData *responseData = [[FLEXNetworkRecorder defaultRecorder] cachedResponseBodyForTransaction:transaction];
  169. if ([responseData length] > 0) {
  170. responseBodyRow.detailText = @"tap to view";
  171. // Avoid a long lived strong reference to the response data in case we need to purge it from the cache.
  172. __weak NSData *weakResponseData = responseData;
  173. responseBodyRow.selectionFuture = ^{
  174. UIViewController *responseBodyDetailViewController = nil;
  175. NSData *strongResponseData = weakResponseData;
  176. if (strongResponseData) {
  177. responseBodyDetailViewController = [self detailViewControllerForMIMEType:transaction.response.MIMEType data:strongResponseData];
  178. } else {
  179. // FIXME (RKO): Show an alert explaining that the data was purged?
  180. }
  181. return responseBodyDetailViewController;
  182. };
  183. } else {
  184. BOOL emptyResponse = transaction.receivedDataLength == 0;
  185. responseBodyRow.detailText = emptyResponse ? @"empty" : @"purged from cache";
  186. }
  187. [rows addObject:responseBodyRow];
  188. FLEXNetworkDetailRow *requestMethodRow = [[FLEXNetworkDetailRow alloc] init];
  189. requestMethodRow.title = @"Request Method";
  190. requestMethodRow.detailText = transaction.request.HTTPMethod;
  191. [rows addObject:requestMethodRow];
  192. NSString *statusCodeString = [FLEXUtility statusCodeStringFromURLResponse:transaction.response];
  193. if ([statusCodeString length] > 0) {
  194. FLEXNetworkDetailRow *statusCodeRow = [[FLEXNetworkDetailRow alloc] init];
  195. statusCodeRow.title = @"Status Code";
  196. statusCodeRow.detailText = statusCodeString;
  197. [rows addObject:statusCodeRow];
  198. }
  199. FLEXNetworkDetailRow *mimeTypeRow = [[FLEXNetworkDetailRow alloc] init];
  200. mimeTypeRow.title = @"MIME Type";
  201. mimeTypeRow.detailText = transaction.response.MIMEType;
  202. [rows addObject:mimeTypeRow];
  203. FLEXNetworkDetailRow *responseSizeRow = [[FLEXNetworkDetailRow alloc] init];
  204. responseSizeRow.title = @"Response Size";
  205. responseSizeRow.detailText = [NSByteCountFormatter stringFromByteCount:transaction.receivedDataLength countStyle:NSByteCountFormatterCountStyleBinary];
  206. [rows addObject:responseSizeRow];
  207. NSDateFormatter *startTimeFormatter = [[NSDateFormatter alloc] init];
  208. startTimeFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
  209. FLEXNetworkDetailRow *localStartTimeRow = [[FLEXNetworkDetailRow alloc] init];
  210. localStartTimeRow.title = [NSString stringWithFormat:@"Start Time (%@)", [[NSTimeZone localTimeZone] abbreviationForDate:transaction.startTime]];
  211. localStartTimeRow.detailText = [startTimeFormatter stringFromDate:transaction.startTime];
  212. [rows addObject:localStartTimeRow];
  213. startTimeFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  214. FLEXNetworkDetailRow *utcStartTimeRow = [[FLEXNetworkDetailRow alloc] init];
  215. utcStartTimeRow.title = @"Start Time (UTC)";
  216. utcStartTimeRow.detailText = [startTimeFormatter stringFromDate:transaction.startTime];
  217. [rows addObject:utcStartTimeRow];
  218. FLEXNetworkDetailRow *unixStartTime = [[FLEXNetworkDetailRow alloc] init];
  219. unixStartTime.title = @"Unix Start Time";
  220. unixStartTime.detailText = [NSString stringWithFormat:@"%f", [transaction.startTime timeIntervalSince1970]];
  221. [rows addObject:unixStartTime];
  222. FLEXNetworkDetailRow *durationRow = [[FLEXNetworkDetailRow alloc] init];
  223. durationRow.title = @"Total Duration";
  224. durationRow.detailText = [FLEXUtility stringFromRequestDuration:transaction.duration];
  225. [rows addObject:durationRow];
  226. FLEXNetworkDetailRow *latencyRow = [[FLEXNetworkDetailRow alloc] init];
  227. latencyRow.title = @"Latency";
  228. latencyRow.detailText = [FLEXUtility stringFromRequestDuration:transaction.latency];
  229. [rows addObject:latencyRow];
  230. FLEXNetworkDetailSection *generalSection = [[FLEXNetworkDetailSection alloc] init];
  231. generalSection.title = @"General";
  232. generalSection.rows = rows;
  233. return generalSection;
  234. }
  235. + (FLEXNetworkDetailSection *)requestHeadersSectionForTransaction:(FLEXNetworkTransaction *)transaction
  236. {
  237. FLEXNetworkDetailSection *requestHeadersSection = [[FLEXNetworkDetailSection alloc] init];
  238. requestHeadersSection.title = @"Request Headers";
  239. requestHeadersSection.rows = [self networkDetailRowsFromDictionary:transaction.request.allHTTPHeaderFields];
  240. return requestHeadersSection;
  241. }
  242. + (FLEXNetworkDetailSection *)queryParametersSectionForTransaction:(FLEXNetworkTransaction *)transaction
  243. {
  244. NSDictionary *queryDictionary = [FLEXUtility queryDictionaryFromURL:transaction.request.URL];
  245. FLEXNetworkDetailSection *querySection = [[FLEXNetworkDetailSection alloc] init];
  246. querySection.title = @"Query Parameters";
  247. querySection.rows = [self networkDetailRowsFromDictionary:queryDictionary];
  248. return querySection;
  249. }
  250. + (FLEXNetworkDetailSection *)responseHeadersSectionForTransaction:(FLEXNetworkTransaction *)transaction
  251. {
  252. FLEXNetworkDetailSection *responseHeadersSection = [[FLEXNetworkDetailSection alloc] init];
  253. responseHeadersSection.title = @"Response Headers";
  254. if ([transaction.response isKindOfClass:[NSHTTPURLResponse class]]) {
  255. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)transaction.response;
  256. responseHeadersSection.rows = [self networkDetailRowsFromDictionary:httpResponse.allHeaderFields];
  257. }
  258. return responseHeadersSection;
  259. }
  260. + (NSArray *)networkDetailRowsFromDictionary:(NSDictionary *)dictionary
  261. {
  262. NSMutableArray *rows = [NSMutableArray arrayWithCapacity:[dictionary count]];
  263. NSArray *sortedKeys = [[dictionary allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
  264. for (NSString *key in sortedKeys) {
  265. NSString *value = [dictionary objectForKey:key];
  266. FLEXNetworkDetailRow *row = [[FLEXNetworkDetailRow alloc] init];
  267. row.title = key;
  268. row.detailText = value;
  269. [rows addObject:row];
  270. }
  271. return [rows copy];
  272. }
  273. + (UIViewController *)detailViewControllerForMIMEType:(NSString *)mimeType data:(NSData *)data
  274. {
  275. // FIXME (RKO): Don't rely on UTF8 string encoding
  276. UIViewController *detailViewController = nil;
  277. if ([mimeType isEqual:@"application/json"]) {
  278. NSString *prettyJSON = [FLEXUtility prettyJSONStringFromData:data];
  279. detailViewController = [[FLEXWebViewController alloc] initWithText:prettyJSON];
  280. } else if ([mimeType hasPrefix:@"image/"]) {
  281. UIImage *image = [UIImage imageWithData:data];
  282. detailViewController = [[FLEXImagePreviewViewController alloc] initWithImage:image];
  283. } else if ([mimeType hasPrefix:@"text/"]) {
  284. NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  285. detailViewController = [[FLEXWebViewController alloc] initWithText:text];
  286. }
  287. detailViewController.title = @"Response";
  288. return detailViewController;
  289. }
  290. @end