OSSModel.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. //
  2. // OSSModel.m
  3. // oss_ios_sdk
  4. //
  5. // Created by zhouzhuo on 8/16/15.
  6. // Copyright (c) 2015 aliyun.com. All rights reserved.
  7. //
  8. #import "OSSDefine.h"
  9. #import "OSSModel.h"
  10. #import "OSSBolts.h"
  11. #import "OSSUtil.h"
  12. #import "OSSNetworking.h"
  13. #import "OSSLog.h"
  14. #import "OSSXMLDictionary.h"
  15. #if TARGET_OS_IOS
  16. #import <UIKit/UIDevice.h>
  17. #endif
  18. #import "OSSAllRequestNeededMessage.h"
  19. @implementation NSDictionary (OSS)
  20. - (NSString *)base64JsonString {
  21. NSError * error;
  22. NSData * jsonData = [NSJSONSerialization dataWithJSONObject:self
  23. options:0
  24. error:&error];
  25. if (!jsonData) {
  26. return @"e30="; // base64("{}");
  27. } else {
  28. NSString * jsonStr = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
  29. NSLog(@"callback json - %@", jsonStr);
  30. return [[jsonStr dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
  31. }
  32. }
  33. @end
  34. @implementation OSSSyncMutableDictionary
  35. - (instancetype)init {
  36. if (self = [super init]) {
  37. _dictionary = [NSMutableDictionary dictionary];
  38. _dispatchQueue = dispatch_queue_create("com.aliyun.aliyunsycmutabledictionary", DISPATCH_QUEUE_SERIAL);
  39. }
  40. return self;
  41. }
  42. - (NSArray *)allKeys {
  43. __block NSArray *allKeys = nil;
  44. dispatch_sync(self.dispatchQueue, ^{
  45. allKeys = [self.dictionary allKeys];
  46. });
  47. return allKeys;
  48. }
  49. - (id)objectForKey:(id)aKey {
  50. __block id returnObject = nil;
  51. dispatch_sync(self.dispatchQueue, ^{
  52. returnObject = [self.dictionary objectForKey:aKey];
  53. });
  54. return returnObject;
  55. }
  56. - (void)setObject:(id)anObject forKey:(id <NSCopying>)aKey {
  57. dispatch_sync(self.dispatchQueue, ^{
  58. [self.dictionary oss_setObject:anObject forKey:aKey];
  59. });
  60. }
  61. - (void)removeObjectForKey:(id)aKey {
  62. dispatch_sync(self.dispatchQueue, ^{
  63. [self.dictionary removeObjectForKey:aKey];
  64. });
  65. }
  66. @end
  67. @implementation OSSFederationToken
  68. - (NSString *)description
  69. {
  70. return [NSString stringWithFormat:@"OSSFederationToken<%p>:{AccessKeyId: %@\nAccessKeySecret: %@\nSecurityToken: %@\nExpiration: %@}", self, _tAccessKey, _tSecretKey, _tToken, _expirationTimeInGMTFormat];
  71. }
  72. @end
  73. @implementation OSSPlainTextAKSKPairCredentialProvider
  74. - (instancetype)initWithPlainTextAccessKey:(nonnull NSString *)accessKey secretKey:(nonnull NSString *)secretKey {
  75. if (self = [super init]) {
  76. self.accessKey = [accessKey oss_trim];
  77. self.secretKey = [secretKey oss_trim];
  78. }
  79. return self;
  80. }
  81. - (nullable NSString *)sign:(NSString *)content error:(NSError **)error {
  82. if (![self.accessKey oss_isNotEmpty] || ![self.secretKey oss_isNotEmpty])
  83. {
  84. if (error != nil)
  85. {
  86. *error = [NSError errorWithDomain:OSSClientErrorDomain
  87. code:OSSClientErrorCodeSignFailed
  88. userInfo:@{OSSErrorMessageTOKEN: @"accessKey or secretKey can't be null"}];
  89. }
  90. return nil;
  91. }
  92. NSString * sign = [OSSUtil calBase64Sha1WithData:content withSecret:self.secretKey];
  93. return [NSString stringWithFormat:@"OSS %@:%@", self.accessKey, sign];
  94. }
  95. @end
  96. @implementation OSSCustomSignerCredentialProvider
  97. - (instancetype)initWithImplementedSigner:(OSSCustomSignContentBlock)signContent
  98. {
  99. NSParameterAssert(signContent);
  100. if (self = [super init])
  101. {
  102. _signContent = signContent;
  103. }
  104. return self;
  105. }
  106. - (NSString *)sign:(NSString *)content error:(NSError **)error
  107. {
  108. NSString * signature = @"";
  109. @synchronized(self) {
  110. signature = self.signContent(content, error);
  111. }
  112. if (*error) {
  113. *error = [NSError errorWithDomain:OSSClientErrorDomain
  114. code:OSSClientErrorCodeSignFailed
  115. userInfo:[[NSDictionary alloc] initWithDictionary:[*error userInfo]]];
  116. return nil;
  117. }
  118. return signature;
  119. }
  120. @end
  121. @implementation OSSFederationCredentialProvider
  122. - (instancetype)initWithFederationTokenGetter:(OSSGetFederationTokenBlock)federationTokenGetter {
  123. if (self = [super init]) {
  124. self.federationTokenGetter = federationTokenGetter;
  125. }
  126. return self;
  127. }
  128. - (nullable OSSFederationToken *)getToken:(NSError **)error {
  129. OSSFederationToken * validToken = nil;
  130. @synchronized(self) {
  131. if (self.cachedToken == nil) {
  132. self.cachedToken = self.federationTokenGetter();
  133. } else {
  134. if (self.cachedToken.expirationTimeInGMTFormat) {
  135. NSDateFormatter * fm = [NSDateFormatter new];
  136. fm.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  137. [fm setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
  138. self.cachedToken.expirationTimeInMilliSecond = [[fm dateFromString:self.cachedToken.expirationTimeInGMTFormat] timeIntervalSince1970] * 1000;
  139. self.cachedToken.expirationTimeInGMTFormat = nil;
  140. OSSLogVerbose(@"Transform GMT date to expirationTimeInMilliSecond: %lld", self.cachedToken.expirationTimeInMilliSecond);
  141. }
  142. NSDate * expirationDate = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)(self.cachedToken.expirationTimeInMilliSecond / 1000)];
  143. NSTimeInterval interval = [expirationDate timeIntervalSinceDate:[NSDate oss_clockSkewFixedDate]];
  144. /* if this token will be expired after less than 2min, we abort it in case of when request arrived oss server,
  145. it's expired already. */
  146. if (interval < 5 * 60) {
  147. OSSLogDebug(@"get federation token, but after %lf second it would be expired", interval);
  148. self.cachedToken = self.federationTokenGetter();
  149. }
  150. }
  151. validToken = self.cachedToken;
  152. }
  153. if (!validToken)
  154. {
  155. if (error != nil)
  156. {
  157. *error = [NSError errorWithDomain:OSSClientErrorDomain
  158. code:OSSClientErrorCodeSignFailed
  159. userInfo:@{OSSErrorMessageTOKEN: @"Can't get a federation token"}];
  160. }
  161. return nil;
  162. }
  163. return validToken;
  164. }
  165. @end
  166. @implementation OSSStsTokenCredentialProvider
  167. - (OSSFederationToken *)getToken {
  168. OSSFederationToken * token = [OSSFederationToken new];
  169. token.tAccessKey = self.accessKeyId;
  170. token.tSecretKey = self.secretKeyId;
  171. token.tToken = self.securityToken;
  172. token.expirationTimeInMilliSecond = NSIntegerMax;
  173. return token;
  174. }
  175. - (instancetype)initWithAccessKeyId:(NSString *)accessKeyId secretKeyId:(NSString *)secretKeyId securityToken:(NSString *)securityToken {
  176. if (self = [super init]) {
  177. self.accessKeyId = [accessKeyId oss_trim];
  178. self.secretKeyId = [secretKeyId oss_trim];
  179. self.securityToken = [securityToken oss_trim];
  180. }
  181. return self;
  182. }
  183. - (NSString *)sign:(NSString *)content error:(NSError **)error {
  184. NSString * sign = [OSSUtil calBase64Sha1WithData:content withSecret:self.secretKeyId];
  185. return [NSString stringWithFormat:@"OSS %@:%@", self.accessKeyId, sign];
  186. }
  187. @end
  188. @implementation OSSAuthCredentialProvider
  189. - (instancetype)initWithAuthServerUrl:(NSString *)authServerUrl
  190. {
  191. return [self initWithAuthServerUrl:authServerUrl responseDecoder:nil];
  192. }
  193. - (instancetype)initWithAuthServerUrl:(NSString *)authServerUrl responseDecoder:(nullable OSSResponseDecoderBlock)decoder
  194. {
  195. self = [super initWithFederationTokenGetter:^OSSFederationToken * {
  196. NSURL * url = [NSURL URLWithString:self.authServerUrl];
  197. NSURLRequest * request = [NSURLRequest requestWithURL:url];
  198. OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
  199. NSURLSession * session = [NSURLSession sharedSession];
  200. NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
  201. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  202. if (error) {
  203. [tcs setError:error];
  204. return;
  205. }
  206. [tcs setResult:data];
  207. }];
  208. [sessionTask resume];
  209. [tcs.task waitUntilFinished];
  210. if (tcs.task.error) {
  211. return nil;
  212. } else {
  213. NSData* data = tcs.task.result;
  214. if(decoder){
  215. data = decoder(data);
  216. }
  217. NSDictionary * object = [NSJSONSerialization JSONObjectWithData:data
  218. options:kNilOptions
  219. error:nil];
  220. int statusCode = [[object objectForKey:@"StatusCode"] intValue];
  221. if (statusCode == 200) {
  222. OSSFederationToken * token = [OSSFederationToken new];
  223. // All the entries below are mandatory.
  224. token.tAccessKey = [object objectForKey:@"AccessKeyId"];
  225. token.tSecretKey = [object objectForKey:@"AccessKeySecret"];
  226. token.tToken = [object objectForKey:@"SecurityToken"];
  227. token.expirationTimeInGMTFormat = [object objectForKey:@"Expiration"];
  228. OSSLogDebug(@"token: %@ %@ %@ %@", token.tAccessKey, token.tSecretKey, token.tToken, [object objectForKey:@"Expiration"]);
  229. return token;
  230. }else{
  231. return nil;
  232. }
  233. }
  234. }];
  235. if(self){
  236. self.authServerUrl = authServerUrl;
  237. }
  238. return self;
  239. }
  240. @end
  241. NSString * const BACKGROUND_SESSION_IDENTIFIER = @"com.aliyun.oss.backgroundsession";
  242. @implementation OSSClientConfiguration
  243. - (instancetype)init {
  244. if (self = [super init]) {
  245. self.maxRetryCount = OSSDefaultRetryCount;
  246. self.maxConcurrentRequestCount = OSSDefaultMaxConcurrentNum;
  247. self.enableBackgroundTransmitService = NO;
  248. self.isHttpdnsEnable = NO;
  249. self.backgroundSesseionIdentifier = BACKGROUND_SESSION_IDENTIFIER;
  250. self.timeoutIntervalForRequest = OSSDefaultTimeoutForRequestInSecond;
  251. self.timeoutIntervalForResource = OSSDefaultTimeoutForResourceInSecond;
  252. self.isPathStyleAccessEnable = NO;
  253. self.isCustomPathPrefixEnable = NO;
  254. self.cnameExcludeList = @[];
  255. self.isAllowUACarrySystemInfo = YES;
  256. self.isFollowRedirectsEnable = YES;
  257. // When the value <= 0, do not set HTTPMaximumConnectionsPerHost and use the default value of NSURLSessionConfiguration
  258. self.HTTPMaximumConnectionsPerHost = 0;
  259. }
  260. return self;
  261. }
  262. - (void)setCnameExcludeList:(NSArray *)cnameExcludeList {
  263. NSMutableArray * array = [NSMutableArray new];
  264. [cnameExcludeList enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  265. NSString * host = [(NSString *)obj lowercaseString];
  266. if ([host containsString:@"://"]) {
  267. NSString * trimHost = [host substringFromIndex:[host rangeOfString:@"://"].location + 3];
  268. [array addObject:trimHost];
  269. } else {
  270. [array addObject:host];
  271. }
  272. }];
  273. _cnameExcludeList = array.copy;
  274. }
  275. @end
  276. @implementation OSSSignerInterceptor
  277. - (instancetype)initWithCredentialProvider:(id<OSSCredentialProvider>)credentialProvider {
  278. if (self = [super init]) {
  279. self.credentialProvider = credentialProvider;
  280. }
  281. return self;
  282. }
  283. - (OSSTask *)interceptRequestMessage:(OSSAllRequestNeededMessage *)requestMessage {
  284. OSSLogVerbose(@"signing intercepting - ");
  285. NSError * error = nil;
  286. /****************************************************************
  287. * define a constant array to contain all specified subresource */
  288. static NSArray * OSSSubResourceARRAY = nil;
  289. static dispatch_once_t onceToken;
  290. dispatch_once(&onceToken, ^{
  291. OSSSubResourceARRAY = @[@"acl", @"uploadId", @"partNumber", @"uploads", @"logging", @"website", @"location",
  292. @"lifecycle", @"referer", @"cors", @"delete", @"append", @"position", @"security-token", @"x-oss-process", @"sequential",@"bucketInfo",@"symlink", @"restore", @"tagging"];
  293. });
  294. /****************************************************************/
  295. /* initial each part of content to sign */
  296. NSString * method = requestMessage.httpMethod;
  297. NSString * contentType = @"";
  298. NSString * contentMd5 = @"";
  299. NSString * date = requestMessage.date;
  300. NSString * xossHeader = @"";
  301. NSString * resource = @"";
  302. OSSFederationToken * federationToken = nil;
  303. if (requestMessage.contentType) {
  304. contentType = requestMessage.contentType;
  305. }
  306. if (requestMessage.contentMd5) {
  307. contentMd5 = requestMessage.contentMd5;
  308. }
  309. /* if credential provider is a federation token provider, it need to specially handle */
  310. if ([self.credentialProvider isKindOfClass:[OSSFederationCredentialProvider class]]) {
  311. federationToken = [(OSSFederationCredentialProvider *)self.credentialProvider getToken:&error];
  312. if (error) {
  313. return [OSSTask taskWithError:error];
  314. }
  315. [requestMessage.headerParams oss_setObject:federationToken.tToken forKey:@"x-oss-security-token"];
  316. } else if ([self.credentialProvider isKindOfClass:[OSSStsTokenCredentialProvider class]]) {
  317. federationToken = [(OSSStsTokenCredentialProvider *)self.credentialProvider getToken];
  318. [requestMessage.headerParams oss_setObject:federationToken.tToken forKey:@"x-oss-security-token"];
  319. }
  320. [requestMessage.headerParams oss_setObject:requestMessage.contentSHA1 forKey:OSSHttpHeaderHashSHA1];
  321. /* construct CanonicalizedOSSHeaders */
  322. if (requestMessage.headerParams) {
  323. NSMutableArray * params = [[NSMutableArray alloc] init];
  324. NSArray * sortedKey = [[requestMessage.headerParams allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  325. return [obj1 compare:obj2];
  326. }];
  327. for (NSString * key in sortedKey) {
  328. if ([key hasPrefix:@"x-oss-"]) {
  329. [params addObject:[NSString stringWithFormat:@"%@:%@", key, [requestMessage.headerParams objectForKey:key]]];
  330. }
  331. }
  332. if ([params count]) {
  333. xossHeader = [NSString stringWithFormat:@"%@\n", [params componentsJoinedByString:@"\n"]];
  334. }
  335. }
  336. /* construct CanonicalizedResource */
  337. resource = @"/";
  338. if (requestMessage.bucketName) {
  339. resource = [NSString stringWithFormat:@"/%@/", requestMessage.bucketName];
  340. }
  341. if (requestMessage.objectKey) {
  342. resource = [resource oss_stringByAppendingPathComponentForURL:requestMessage.objectKey];
  343. }
  344. if (requestMessage.params) {
  345. NSMutableArray * querys = [[NSMutableArray alloc] init];
  346. NSArray * sortedKey = [[requestMessage.params allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  347. return [obj1 compare:obj2];
  348. }];
  349. for (NSString * key in sortedKey) {
  350. NSString * value = [requestMessage.params objectForKey:key];
  351. if (![OSSSubResourceARRAY containsObject:key]) { // notice it's based on content compare
  352. continue;
  353. }
  354. if ([value isEqualToString:@""]) {
  355. [querys addObject:[NSString stringWithFormat:@"%@", key]];
  356. } else {
  357. [querys addObject:[NSString stringWithFormat:@"%@=%@", key, value]];
  358. }
  359. }
  360. if ([querys count]) {
  361. resource = [resource stringByAppendingString:[NSString stringWithFormat:@"?%@",[querys componentsJoinedByString:@"&"]]];
  362. }
  363. }
  364. /* now, join every part of content and sign */
  365. NSString * stringToSign = [NSString stringWithFormat:@"%@\n%@\n%@\n%@\n%@%@", method, contentMd5, contentType, date, xossHeader, resource];
  366. OSSLogDebug(@"string to sign: %@", stringToSign);
  367. if ([self.credentialProvider isKindOfClass:[OSSFederationCredentialProvider class]]
  368. || [self.credentialProvider isKindOfClass:[OSSStsTokenCredentialProvider class]])
  369. {
  370. NSString * signature = [OSSUtil sign:stringToSign withToken:federationToken];
  371. [requestMessage.headerParams oss_setObject:signature forKey:@"Authorization"];
  372. }else if ([self.credentialProvider isKindOfClass:[OSSCustomSignerCredentialProvider class]])
  373. {
  374. OSSCustomSignerCredentialProvider *provider = (OSSCustomSignerCredentialProvider *)self.credentialProvider;
  375. NSError *customSignError;
  376. NSString * signature = [provider sign:stringToSign error:&customSignError];
  377. if (customSignError) {
  378. OSSLogError(@"OSSCustomSignerError: %@", customSignError)
  379. return [OSSTask taskWithError: customSignError];
  380. }
  381. [requestMessage.headerParams oss_setObject:signature forKey:@"Authorization"];
  382. }else
  383. {
  384. NSString * signature = [self.credentialProvider sign:stringToSign error:&error];
  385. if (error) {
  386. return [OSSTask taskWithError:error];
  387. }
  388. [requestMessage.headerParams oss_setObject:signature forKey:@"Authorization"];
  389. }
  390. return [OSSTask taskWithResult:nil];
  391. }
  392. @end
  393. @implementation OSSUASettingInterceptor
  394. - (instancetype)initWithClientConfiguration:(OSSClientConfiguration *)clientConfiguration{
  395. if (self = [super init]) {
  396. self.clientConfiguration = clientConfiguration;
  397. }
  398. return self;
  399. }
  400. - (OSSTask *)interceptRequestMessage:(OSSAllRequestNeededMessage *)request {
  401. NSString * userAgent = [self getUserAgent:self.clientConfiguration.userAgentMark];
  402. [request.headerParams oss_setObject:userAgent forKey:@"User-Agent"];
  403. return [OSSTask taskWithResult:nil];
  404. }
  405. - (NSString *)getUserAgent:(NSString *)customUserAgent {
  406. static NSString * userAgent = nil;
  407. static dispatch_once_t once;
  408. NSString * tempUserAgent = nil;
  409. dispatch_once(&once, ^{
  410. NSString *localeIdentifier = [[NSLocale currentLocale] localeIdentifier];
  411. #if TARGET_OS_IOS
  412. if (self.clientConfiguration.isAllowUACarrySystemInfo) {
  413. NSString *systemName = [[[UIDevice currentDevice] systemName] stringByReplacingOccurrencesOfString:@" " withString:@"-"];
  414. NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
  415. userAgent = [NSString stringWithFormat:@"%@/%@(/%@/%@/%@)", OSSUAPrefix, OSSSDKVersion, systemName, systemVersion, localeIdentifier];
  416. } else {
  417. userAgent = [NSString stringWithFormat:@"%@/%@(/%@)", OSSUAPrefix, OSSSDKVersion, localeIdentifier];
  418. }
  419. #elif TARGET_OS_OSX
  420. userAgent = [NSString stringWithFormat:@"%@/%@(/%@/%@/%@)", OSSUAPrefix, OSSSDKVersion, @"OSX", [NSProcessInfo processInfo].operatingSystemVersionString, localeIdentifier];
  421. #endif
  422. });
  423. if(customUserAgent){
  424. if(userAgent){
  425. tempUserAgent = [[userAgent stringByAppendingString:@"/"] stringByAppendingString:customUserAgent];
  426. }else{
  427. tempUserAgent = customUserAgent;
  428. }
  429. }else{
  430. tempUserAgent = userAgent;
  431. }
  432. return tempUserAgent;
  433. }
  434. @end
  435. @implementation OSSTimeSkewedFixingInterceptor
  436. - (OSSTask *)interceptRequestMessage:(OSSAllRequestNeededMessage *)request {
  437. request.date = [[NSDate oss_clockSkewFixedDate] oss_asStringValue];
  438. return [OSSTask taskWithResult:nil];
  439. }
  440. @end
  441. @implementation OSSRange
  442. - (instancetype)initWithStart:(int64_t)start withEnd:(int64_t)end {
  443. if (self = [super init]) {
  444. self.startPosition = start;
  445. self.endPosition = end;
  446. }
  447. return self;
  448. }
  449. - (NSString *)toHeaderString {
  450. NSString * rangeString = nil;
  451. if (self.startPosition < 0 && self.endPosition < 0) {
  452. rangeString = [NSString stringWithFormat:@"bytes=%lld-%lld", self.startPosition, self.endPosition];
  453. } else if (self.startPosition < 0) {
  454. rangeString = [NSString stringWithFormat:@"bytes=-%lld", self.endPosition];
  455. } else if (self.endPosition < 0) {
  456. rangeString = [NSString stringWithFormat:@"bytes=%lld-", self.startPosition];
  457. } else {
  458. rangeString = [NSString stringWithFormat:@"bytes=%lld-%lld", self.startPosition, self.endPosition];
  459. }
  460. return rangeString;
  461. }
  462. @end
  463. #pragma mark request and result objects
  464. @implementation OSSGetServiceRequest
  465. - (NSDictionary *)requestParams {
  466. NSMutableDictionary * params = [NSMutableDictionary dictionary];
  467. [params oss_setObject:self.prefix forKey:@"prefix"];
  468. [params oss_setObject:self.marker forKey:@"marker"];
  469. if (self.maxKeys > 0) {
  470. [params oss_setObject:[@(self.maxKeys) stringValue] forKey:@"max-keys"];
  471. }
  472. return [params copy];
  473. }
  474. @end
  475. @implementation OSSGetServiceResult
  476. @end
  477. @implementation OSSCreateBucketRequest
  478. - (instancetype)init
  479. {
  480. self = [super init];
  481. if (self) {
  482. _storageClass = OSSBucketStorageClassStandard;
  483. }
  484. return self;
  485. }
  486. - (NSString *)storageClassAsString {
  487. NSString *storageClassString = nil;
  488. switch (_storageClass) {
  489. case OSSBucketStorageClassStandard:
  490. storageClassString = @"Standard";
  491. break;
  492. case OSSBucketStorageClassIA:
  493. storageClassString = @"IA";
  494. break;
  495. case OSSBucketStorageClassArchive:
  496. storageClassString = @"Archive";
  497. break;
  498. default:
  499. storageClassString = @"Unknown";
  500. break;
  501. }
  502. return storageClassString;
  503. }
  504. @end
  505. @implementation OSSCreateBucketResult
  506. @end
  507. @implementation OSSDeleteBucketRequest
  508. @end
  509. @implementation OSSDeleteBucketResult
  510. @end
  511. @implementation OSSGetBucketRequest
  512. - (NSDictionary *)requestParams {
  513. NSMutableDictionary * params = [NSMutableDictionary dictionary];
  514. [params oss_setObject:self.delimiter forKey:@"delimiter"];
  515. [params oss_setObject:self.prefix forKey:@"prefix"];
  516. [params oss_setObject:self.marker forKey:@"marker"];
  517. if (self.maxKeys > 0) {
  518. [params oss_setObject:[@(self.maxKeys) stringValue] forKey:@"max-keys"];
  519. }
  520. return [params copy];
  521. }
  522. @end
  523. @implementation OSSListMultipartUploadsRequest
  524. - (NSDictionary *)requestParams {
  525. NSMutableDictionary * params = [NSMutableDictionary dictionary];
  526. [params oss_setObject:self.delimiter forKey:@"delimiter"];
  527. [params oss_setObject:self.prefix forKey:@"prefix"];
  528. [params oss_setObject:self.keyMarker forKey:@"key-marker"];
  529. [params oss_setObject:self.uploadIdMarker forKey:@"upload-id-marker"];
  530. [params oss_setObject:self.encodingType forKey:@"encoding-type"];
  531. if (self.maxUploads > 0) {
  532. [params oss_setObject:[@(self.maxUploads) stringValue] forKey:@"max-uploads"];
  533. }
  534. return [params copy];
  535. }
  536. @end
  537. @implementation OSSListMultipartUploadsResult
  538. @end
  539. @implementation OSSGetBucketResult
  540. @end
  541. @implementation OSSGetBucketACLRequest
  542. - (NSDictionary *)requestParams {
  543. return @{@"acl": @""};
  544. }
  545. @end
  546. @implementation OSSGetBucketACLResult
  547. @end
  548. @implementation OSSHeadObjectRequest
  549. @end
  550. @implementation OSSHeadObjectResult
  551. @end
  552. @implementation OSSGetObjectRequest
  553. @end
  554. @implementation OSSGetObjectResult
  555. @end
  556. @implementation OSSPutObjectACLRequest
  557. - (instancetype)init
  558. {
  559. self = [super init];
  560. if (self) {
  561. _acl = @"default";
  562. }
  563. return self;
  564. }
  565. @end
  566. @implementation OSSPutObjectACLResult
  567. @end
  568. @implementation OSSPutObjectRequest
  569. - (instancetype)init {
  570. if (self = [super init]) {
  571. self.objectMeta = [NSDictionary new];
  572. }
  573. return self;
  574. }
  575. @end
  576. @implementation OSSPutObjectResult
  577. @end
  578. @implementation OSSAppendObjectRequest
  579. - (instancetype)init {
  580. if (self = [super init]) {
  581. self.objectMeta = [NSDictionary new];
  582. }
  583. return self;
  584. }
  585. @end
  586. @implementation OSSAppendObjectResult
  587. @end
  588. @implementation OSSDeleteObjectRequest
  589. @end
  590. @implementation OSSDeleteObjectResult
  591. @end
  592. @implementation OSSCopyObjectRequest
  593. - (instancetype)init {
  594. if (self = [super init]) {
  595. self.objectMeta = [NSDictionary new];
  596. }
  597. return self;
  598. }
  599. @end
  600. @implementation OSSCopyObjectResult
  601. @end
  602. @implementation OSSInitMultipartUploadRequest
  603. - (instancetype)init {
  604. if (self = [super init]) {
  605. self.objectMeta = [NSDictionary new];
  606. }
  607. return self;
  608. }
  609. @end
  610. @implementation OSSInitMultipartUploadResult
  611. @end
  612. @implementation OSSUploadPartRequest
  613. @end
  614. @implementation OSSUploadPartResult
  615. @end
  616. @implementation OSSPartInfo
  617. + (instancetype)partInfoWithPartNum:(int32_t)partNum
  618. eTag:(NSString *)eTag
  619. size:(int64_t)size {
  620. return [self partInfoWithPartNum:partNum
  621. eTag:eTag
  622. size:size
  623. crc64:0];
  624. }
  625. + (instancetype)partInfoWithPartNum:(int32_t)partNum eTag:(NSString *)eTag size:(int64_t)size crc64:(uint64_t)crc64
  626. {
  627. OSSPartInfo *parInfo = [OSSPartInfo new];
  628. parInfo.partNum = partNum;
  629. parInfo.eTag = eTag;
  630. parInfo.size = size;
  631. parInfo.crc64 = crc64;
  632. return parInfo;
  633. }
  634. - (nonnull NSDictionary *)entityToDictionary
  635. {
  636. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  637. [dict setValue:@(_partNum) forKey:@"partNum"];
  638. if (_eTag)
  639. {
  640. [dict setValue:_eTag forKey:@"eTag"];
  641. }
  642. [dict setValue:@(_size) forKey:@"size"];
  643. [dict setValue:@(_crc64) forKey:@"crc64"];
  644. return [dict copy];
  645. }
  646. - (NSString *)description
  647. {
  648. return [NSString stringWithFormat:@"OSSPartInfo<%p>:{partNum: %d,eTag: %@,partSize: %lld,crc64: %llu}",self,self.partNum,self.eTag,self.size,self.crc64];
  649. }
  650. #pragma marks - Protocol Methods
  651. - (id)copyWithZone:(nullable NSZone *)zone
  652. {
  653. OSSPartInfo *instance = [[[self class] allocWithZone:zone] init];
  654. instance.partNum = self.partNum;
  655. instance.eTag = self.eTag;
  656. instance.size = self.size;
  657. instance.crc64 = self.crc64;
  658. return instance;
  659. }
  660. @end
  661. @implementation OSSCompleteMultipartUploadRequest
  662. @end
  663. @implementation OSSCompleteMultipartUploadResult
  664. @end
  665. @implementation OSSAbortMultipartUploadRequest
  666. @end
  667. @implementation OSSAbortMultipartUploadResult
  668. @end
  669. @implementation OSSListPartsRequest
  670. @end
  671. @implementation OSSListPartsResult
  672. @end
  673. @implementation OSSMultipartUploadRequest
  674. - (instancetype)init {
  675. if (self = [super init]) {
  676. self.partSize = 256 * 1024;
  677. self.threadNum = OSSDefaultThreadNum;
  678. }
  679. return self;
  680. }
  681. - (void)cancel {
  682. [super cancel];
  683. }
  684. @end
  685. @implementation OSSResumableUploadRequest
  686. - (instancetype)init {
  687. if (self = [super init]) {
  688. self.deleteUploadIdOnCancelling = YES;
  689. self.partSize = 256 * 1024;
  690. }
  691. return self;
  692. }
  693. - (void)cancel {
  694. [super cancel];
  695. if(_runningChildrenRequest){
  696. [_runningChildrenRequest cancel];
  697. }
  698. }
  699. @end
  700. @implementation OSSResumableUploadResult
  701. @end
  702. @implementation OSSCallBackRequest
  703. @end
  704. @implementation OSSCallBackResult
  705. @end
  706. @implementation OSSImagePersistRequest
  707. @end
  708. @implementation OSSImagePersistResult
  709. @end