QNHosts.m 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // QNHosts.m
  3. // HappyDNS
  4. //
  5. // Created by bailong on 15/6/23.
  6. // Copyright (c) 2015年 Qiniu Cloud Storage. All rights reserved.
  7. //
  8. #import "QNHosts.h"
  9. #import "QNDomain.h"
  10. //#import "QNIP.h"
  11. #import "QNNetworkInfo.h"
  12. @interface QNHosts ()
  13. @property (nonatomic) NSMutableDictionary *dict;
  14. @end
  15. @interface QNHostsValue : NSObject
  16. @property (nonatomic, copy, readonly) NSString *ip;
  17. @property (readonly) int provider;
  18. @end
  19. @implementation QNHostsValue
  20. - (instancetype)init:(NSString *)ip provider:(int)provider {
  21. if (self = [super init]) {
  22. _ip = ip;
  23. _provider = provider;
  24. }
  25. return self;
  26. }
  27. @end
  28. static NSArray *filter(NSArray *input, int provider) {
  29. NSMutableArray *normal = [[NSMutableArray alloc] initWithCapacity:input.count];
  30. NSMutableArray *special = [[NSMutableArray alloc] init];
  31. for (QNHostsValue *v in input) {
  32. NSString *ip = v.ip;
  33. if (v.provider == kQNISP_GENERAL) {
  34. [normal addObject:ip];
  35. }
  36. if (provider == v.provider && provider != kQNISP_GENERAL) {
  37. [special addObject:ip];
  38. }
  39. }
  40. if (special.count != 0) {
  41. return special;
  42. }
  43. return normal;
  44. }
  45. @implementation QNHosts
  46. - (NSArray *)query:(QNDomain *)domain networkInfo:(QNNetworkInfo *)netInfo {
  47. NSMutableArray *x;
  48. @synchronized(_dict) {
  49. x = [_dict objectForKey:domain.domain];
  50. }
  51. if (x == nil || x.count == 0) {
  52. return nil;
  53. }
  54. if (x.count >= 2) {
  55. QNHostsValue *first = [x firstObject];
  56. [x removeObjectAtIndex:0];
  57. [x addObject:first];
  58. }
  59. return filter(x, netInfo.provider);
  60. }
  61. - (void)put:(NSString *)domain ip:(NSString *)ip {
  62. [self put:domain ip:ip provider:kQNISP_GENERAL];
  63. }
  64. - (void)put:(NSString *)domain ip:(NSString *)ip provider:(int)provider {
  65. QNHostsValue *v = [[QNHostsValue alloc] init:ip provider:provider];
  66. @synchronized(_dict) {
  67. NSMutableArray *x = [_dict objectForKey:domain];
  68. if (x == nil) {
  69. x = [[NSMutableArray alloc] init];
  70. }
  71. [x addObject:v];
  72. [_dict setObject:x forKey:domain];
  73. }
  74. }
  75. - (instancetype)init {
  76. if (self = [super init]) {
  77. _dict = [[NSMutableDictionary alloc] init];
  78. }
  79. return self;
  80. }
  81. @end