This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.m
453 lines (393 loc) · 16.3 KB
/
util.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// Copyright (c) 2009 Imageshack Corp.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include "util.h"
#import "MGTwitterEngine.h"
void LogStringArray(NSArray* ar, NSString* descriptionString)
{
#ifdef DEBUG
NSLog(@"========================Start=====================");
if(descriptionString)
NSLog(descriptionString);
NSEnumerator *enumerator = [ar objectEnumerator];
id obj;
while (obj = [enumerator nextObject])
if([obj isKindOfClass:[NSString class]])
NSLog((NSString*)obj);
else
NSLog(@"------------------Non-string item");
NSLog(@"========================End=====================");
#endif
}
void LogDictionaryStringKeys(NSDictionary* dict, NSString* descriptionString)
{
#ifdef DEBUG
LogStringArray([dict allKeys], descriptionString);
#endif
}
void LogStringSet(NSSet* set, NSString* descriptionString)
{
#ifdef DEBUG
LogStringArray([set allObjects], descriptionString);
#endif
}
UIActionSheet * ShowActionSheet(NSString* title, id <UIActionSheetDelegate> delegate,
NSString *cancelButtonTitle, UIView* forView)
{
UIActionSheet* progressSheet = [[UIActionSheet alloc] initWithTitle:title delegate:delegate cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:nil otherButtonTitles:nil];
progressSheet.actionSheetStyle = UIActionSheetStyleDefault;
UIActivityIndicatorView* progressInd = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(-18.5, -3.0, 40.0, 40.0)];
progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
[progressInd sizeToFit];
progressInd.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleBottomMargin);
[progressInd startAnimating];
[progressSheet addSubview:progressInd];
[progressInd autorelease];
[progressSheet showInView:forView];
return [progressSheet autorelease];
}
// may cause a crash in non main thead
UIImage* imageScaledToSize(UIImage* image, int maxDimension)
{
CGImageRef imgRef = image.CGImage;
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGAffineTransform transform = CGAffineTransformIdentity;
CGRect bounds = CGRectMake(0, 0, width, height);
if(maxDimension > 0) //need scale
{
if (width > maxDimension || height > maxDimension)
{
CGFloat ratio = width/height;
if (ratio > 1)
{
bounds.size.width = maxDimension;
bounds.size.height = bounds.size.width / ratio;
}
else
{
bounds.size.height = maxDimension;
bounds.size.width = bounds.size.height * ratio;
}
}
}
CGFloat scaleRatio = bounds.size.width / width;
CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
CGFloat boundHeight;
UIImageOrientation orient = image.imageOrientation;
switch(orient)
{
case UIImageOrientationUp: //EXIF = 1
transform = CGAffineTransformIdentity;
break;
case UIImageOrientationUpMirrored: //EXIF = 2
transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
break;
case UIImageOrientationDown: //EXIF = 3
transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationDownMirrored: //EXIF = 4
transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
break;
case UIImageOrientationLeftMirrored: //EXIF = 5
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationLeft: //EXIF = 6
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationRightMirrored: //EXIF = 7
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeScale(-1.0, 1.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
case UIImageOrientationRight: //EXIF = 8
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
default:
[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
}
UIGraphicsBeginImageContext(bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft)
{
CGContextScaleCTM(context, -scaleRatio, scaleRatio);
CGContextTranslateCTM(context, -height, 0);
}
else
{
CGContextScaleCTM(context, scaleRatio, -scaleRatio);
CGContextTranslateCTM(context, 0, -height);
}
CGContextConcatCTM(context, transform);
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageCopy;
}
int isImageNeedToConvert(UIImage* testImage, BOOL *needToResize, BOOL *needToRotate)
{
*needToResize = [[NSUserDefaults standardUserDefaults] boolForKey:@"ScalePhotosBeforeUploading"] &&
(testImage.size.width > IMAGE_SCALING_SIZE || testImage.size.height > IMAGE_SCALING_SIZE);
*needToRotate = testImage.imageOrientation != UIImageOrientationUp;
if(*needToResize)
return IMAGE_SCALING_SIZE;
else
return -1;
}
NSString* ValidateYFrogLink(NSString *yfrogUrl)
{
//if host is not yfrog.com it's not a link to yfrog
NSURL *url = [NSURL URLWithString:yfrogUrl];
if([[url host] rangeOfString:@"yfrog." options:NSCaseInsensitiveSearch].location == NSNotFound)
return nil;
NSString *path = [url path];
if(!path || [path length] <= 1)
return nil; //it's a path to the site start page
//Image and mp4 video URLs don't end with x and y.
if([path hasSuffix:@"x"] || [path hasSuffix:@"y"])
return nil;
//If it's a link to a thunbnail, truncate .th.jpg to get a link to an image page
NSRange range = [path rangeOfString:@".th.jpg"];
if(range.location != NSNotFound)
path = [path substringToIndex:range.location];
//If there is a '.' character, it's not a proper link to picture
range = [path rangeOfString:@"."];
if(range.location != NSNotFound)
return nil;
range = [path rangeOfString:@":"];
if(range.location != NSNotFound)
path = [path substringToIndex:range.location];
url = [[[NSURL alloc] initWithScheme:[url scheme] host:[url host] path:path] autorelease];
return [url absoluteString];
}
BOOL isVideoLink(NSString *yfrogUrl)
{
NSURL *url = [NSURL URLWithString:yfrogUrl];
if([[url host] rangeOfString:@"yfrog." options:NSCaseInsensitiveSearch].location == NSNotFound)
return NO;
NSString *path = [url path];
if(!path || [path length] <= 1)
return NO; //it's a path to the site start page
if([path hasSuffix:@"z"])
return YES; //It's mp4 video
return NO;
}
NSString* getLinkWithTag(NSString *tag)
{
NSString *link = nil;
NSRange range = [tag rangeOfString:@" href"];
if (range.length > 0)
{
char buf[1024];
unsigned len = [tag length];
unsigned idx = range.location + range.length;
while ([tag characterAtIndex:idx] != '=' && idx < len)
idx++;
unichar ch, endCh = ' ';
do {
idx++;
ch = [tag characterAtIndex:idx];
if (ch == '"' || ch == '\'')
endCh = ch;
} while (ch == ' ' || ch == '"' || ch == '\'' && idx < len);
unsigned i = 0;
while (((ch = [tag characterAtIndex:idx]) != endCh) && (idx < len))
{
buf[i++] = (char)ch;
idx++;
}
buf[i] = 0;
link = [NSString stringWithCString:buf length:i];
}
return link;
}
static struct
{
NSString *codeForm, *literalForm;
} EntityTable[] =
{
{@""", @"""},// quotation mark
{@"'", @"'"},// (does not work in IE) apostrophe
{@"&", @"&"},// ampersand
{@"<", @"<"},// less-than
{@">", @">"},// greater-than
{@" ", @" "},// non-breaking space
{@"¡", @"¡"},// inverted exclamation mark
{@"¢", @"¢"},// cent
{@"£", @"£"},// pound
{@"¤", @"¤"},// currency
{@"¥", @"¥"},// yen
{@"¦", @"¦"},// broken vertical bar
{@"§", @"§"},// section
{@"¨", @"¨"},// spacing diaeresis
{@"©", @"©"},// copyright
{@"ª", @"ª"},// feminine ordinal indicator
{@"«", @"«"},// angle quotation mark (left)
{@"¬", @"¬"},// negation
{@"­", @"­"},// soft hyphen
{@"®", @"®"},// registered trademark
{@"¯", @"¯"},// spacing macron
{@"°", @"°"},// degree
{@"±", @"±"},// plus-or-minus
{@"²", @"²"},// superscript 2
{@"³", @"³"},// superscript 3
{@"´", @"´"},// spacing acute
{@"µ", @"µ"},// micro
{@"¶", @"¶"},// paragraph
{@"·", @"·"},// middle dot
{@"¸", @"¸"},// spacing cedilla
{@"¹", @"¹"},// superscript 1
{@"º", @"º"},// masculine ordinal indicator
{@"»", @"»"},// angle quotation mark (right)
{@"¼", @"¼"},// fraction 1/4
{@"½", @"½"},// fraction 1/2
{@"¾", @"¾"},// fraction 3/4
{@"¿", @"¿"},// inverted question mark
{@"×", @"×"},// multiplication
{@"÷", @"÷"},// division
{@"À", @"À"},// capital a, grave accent
{@"Á", @"Á"},// capital a, acute accent
{@"Â", @"Â"},// capital a, circumflex accent
{@"Ã", @"Ã"},// capital a, tilde
{@"Ä", @"Ä"},// capital a, umlaut mark
{@"Å", @"Å"},// capital a, ring
{@"Æ", @"Æ"},// capital ae
{@"Ç", @"Ç"},// capital c, cedilla
{@"È", @"È"},// capital e, grave accent
{@"É", @"É"},// capital e, acute accent
{@"Ê", @"Ê"},// capital e, circumflex accent
{@"Ë", @"Ë"},// capital e, umlaut mark
{@"Ì", @"Ì"},// capital i, grave accent
{@"Í", @"Í"},// capital i, acute accent
{@"Î", @"Î"},// capital i, circumflex accent
{@"Ï", @"Ï"},// capital i, umlaut mark
{@"Ð", @"Ð"},// capital eth, Icelandic
{@"Ñ", @"Ñ"},// capital n, tilde
{@"Ò", @"Ò"},// capital o, grave accent
{@"Ó", @"Ó"},// capital o, acute accent
{@"Ô", @"Ô"},// capital o, circumflex accent
{@"Õ", @"Õ"},// capital o, tilde
{@"Ö", @"Ö"},// capital o, umlaut mark
{@"Ø", @"Ø"},// capital o, slash
{@"Ù", @"Ù"},// capital u, grave accent
{@"Ú", @"Ú"},// capital u, acute accent
{@"Û", @"Û"},// capital u, circumflex accent
{@"Ü", @"Ü"},// capital u, umlaut mark
{@"Ý", @"Ý"},// capital y, acute accent
{@"Þ", @"Þ"},// capital THORN, Icelandic
{@"ß", @"ß"},// small sharp s, German
{@"à", @"à"},// small a, grave accent
{@"á", @"á"},// small a, acute accent
{@"â", @"â"},// small a, circumflex accent
{@"ã", @"ã"},// small a, tilde
{@"ä", @"ä"},// small a, umlaut mark
{@"å", @"å"},// small a, ring
{@"æ", @"æ"},// small ae
{@"ç", @"ç"},// small c, cedilla
{@"è", @"è"},// small e, grave accent
{@"é", @"é"},// small e, acute accent
{@"ê", @"ê"},// small e, circumflex accent
{@"ë", @"ë"},// small e, umlaut mark
{@"ì", @"ì"},// small i, grave accent
{@"í", @"í"},// small i, acute accent
{@"î", @"î"},// small i, circumflex accent
{@"ï", @"ï"},// small i, umlaut mark
{@"ð", @"ð"},// small eth, Icelandic
{@"ñ", @"ñ"},// small n, tilde
{@"ò", @"ò"},// small o, grave accent
{@"ó", @"ó"},// small o, acute accent
{@"ô", @"ô"},// small o, circumflex accent
{@"õ", @"õ"},// small o, tilde
{@"ö", @"ö"},// small o, umlaut mark
{@"ø", @"ø"},// small o, slash
{@"ù", @"ù"},// small u, grave accent
{@"ú", @"ú"},// small u, acute accent
{@"û", @"û"},// small u, circumflex accent
{@"ü", @"ü"},// small u, umlaut mark
{@"ý", @"ý"},// small y, acute accent
{@"þ", @"þ"},// small thorn, Icelandic
{@"ÿ", @"ÿ"},// small y, umlaut mark
};
static NSString *decodedStringForEntity(int entityIndex)
{
NSString *codeForm = EntityTable[entityIndex].codeForm;
int code;
sscanf([[codeForm substringFromIndex:2] UTF8String], "%d", &code);
char codeStr[2];
codeStr[0] = (char)code;
codeStr[1] = 0;
return [NSString stringWithCString:codeStr encoding:NSISOLatin1StringEncoding];
}
NSString *DecodeEntities(NSString *str)
{
NSMutableString *bufstr = [[str mutableCopy] autorelease];
for(int i = 0; i < sizeof(EntityTable)/sizeof(*EntityTable); ++i)
{
NSRange entRange = [bufstr rangeOfString:EntityTable[i].codeForm];
if(entRange.location != NSNotFound)
{
[bufstr replaceCharactersInRange:entRange withString:decodedStringForEntity(i)];
}
entRange = [bufstr rangeOfString:EntityTable[i].literalForm];
if(entRange.location != NSNotFound)
{
[bufstr replaceCharactersInRange:entRange withString:decodedStringForEntity(i)];
}
}
return bufstr;
}
NSURLRequest* tweeteroURLRequest(NSURL* url)
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setValue:[MGTwitterEngine userAgent] forHTTPHeaderField:@"User-Agent"];
return req;
}
NSMutableURLRequest* tweeteroMutableURLRequest(NSURL* url)
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setValue:[MGTwitterEngine userAgent] forHTTPHeaderField:@"User-Agent"];
return req;
}