GitHub Sale: sign up for any paid plan this week and pay nothing until January 1, 2009!  [ hide ]

public
Description: An iPhoto plugin to export photos to Gallery.
Homepage: http://zwily.com/iphoto
Clone URL: git://github.com/zwily/iphototogallery.git
iphototogallery / Source / ZWGallery.m
100644 676 lines (536 sloc) 25.924 kb
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//
// Copyright (c) Zach Wily
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - 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.
//
// - Neither the name of Zach Wily nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
//
 
#import "ZWGallery.h"
#import "ZWGalleryAlbum.h"
#import "NSString+misc.h"
#import "ZWURLConnection.h"
#import "InterThreadMessaging.h"
#import "ZWMutableURLRequest.h"
 
@interface ZWGallery (PrivateAPI)
- (void)loginThread:(NSDictionary *)threadDispatchInfo;
- (ZWGalleryRemoteStatusCode)doLogin;
 
- (void)getAlbumsThread:(NSDictionary *)threadDispatchInfo;
- (ZWGalleryRemoteStatusCode)doGetAlbums;
 
- (void)createAlbumThread:(NSDictionary *)threadDispatchInfo;
- (ZWGalleryRemoteStatusCode)doCreateAlbumWithName:(NSString *)name title:(NSString *)title summary:(NSString *)summary parent:(ZWGalleryAlbum *)parent;
 
@end
 
@implementation ZWGallery
 
#pragma mark Object Life Cycle
 
- (id)init {
    return self;
}
 
- (id)initWithURL:(NSURL*)newUrl username:(NSString*)newUsername {
    url = [newUrl retain];
    fullURL = [[NSURL alloc] initWithString:[[url absoluteString] stringByAppendingString:@"gallery_remote2.php"]];
    username = [newUsername retain];
    delegate = self;
    loggedIn = FALSE;
    majorVersion = 0;
    minorVersion = 0;
    type = GalleryTypeG1;
    
    return self;
}
 
- (id)initWithDictionary:(NSDictionary*)dictionary {
    [self initWithURL:[NSURL URLWithString:[dictionary objectForKey:@"url"]]
             username:[dictionary objectForKey:@"username"]];
    
    NSNumber *typeNumber = [dictionary objectForKey:@"type"];
    if (typeNumber)
        type = [typeNumber intValue];
    
    return self;
}
 
+ (ZWGallery*)galleryWithURL:(NSURL*)newUrl username:(NSString*)newUsername {
    return [[[ZWGallery alloc] initWithURL:newUrl username:newUsername] autorelease];
}
 
+ (ZWGallery*)galleryWithDictionary:(NSDictionary*)dictionary {
    return [[[ZWGallery alloc] initWithDictionary:dictionary] autorelease];
}
 
- (void)dealloc
{
    [url release];
    [username release];
    [password release];
    [albums release];
    [lastCreatedAlbumName release];
    
    [super dealloc];
}
 
#pragma mark NSComparisonMethods
 
- (BOOL)isEqual:(id)gal
{
    return ([username isEqual:[gal username]] && [[url absoluteString] isEqual:[[gal url] absoluteString]]);
}
 
- (NSComparisonResult)compare:(id)gal
{
    return [[self identifier] caseInsensitiveCompare:[gal identifier]];
}
 
#pragma mark Accessors
 
- (void)setDelegate:(id)newDelegate {
    delegate = newDelegate;
}
 
- (id)delegate {
    return delegate;
}
 
- (void)setPassword:(NSString*)newPassword {
    [newPassword retain];
    [password release];
    password = newPassword;
}
 
- (NSURL*)url {
    return url;
}
 
- (NSURL*)fullURL {
    return fullURL;
}
 
- (NSString*)identifier {
    return [NSString stringWithFormat:@"%@%@ (%@)", [url host], [url path], username];
}
 
- (NSString*)urlString {
    return [url absoluteString];
}
 
- (NSString*)username {
    return username;
}
 
- (int)majorVersion {
    return majorVersion;
}
 
- (int)minorVersion {
    return minorVersion;
}
 
- (BOOL)loggedIn {
    return loggedIn;
}
 
- (NSArray*)albums {
    return albums;
}
 
- (NSDictionary*)infoDictionary {
    return [NSDictionary dictionaryWithObjectsAndKeys:
        username, @"username",
        [url absoluteString], @"url",
        [NSNumber numberWithInt:(int)type], @"type",
        nil];
}
 
- (BOOL)isGalleryV2 {
  return ([self type] == GalleryTypeG2 || [self type] == GalleryTypeG2XMLRPC);
}
 
- (ZWGalleryType)type {
    return type;
}
 
- (NSString *)lastCreatedAlbumName
{
    return lastCreatedAlbumName;
}
 
- (NSStringEncoding)sniffedEncoding
{
    return sniffedEncoding;
}
 
#pragma mark Actions
 
- (void)cancelOperation
{
    if (currentConnection && ![currentConnection isCancelled]) {
        [currentConnection cancel];
    }
}
 
- (void)login {
    NSDictionary *threadDispatchInfo = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSThread currentThread], @"CallingThread",
        nil];
    [NSThread detachNewThreadSelector:@selector(loginThread:) toTarget:self withObject:threadDispatchInfo];
}
 
- (void)logout {
    loggedIn = FALSE;
}
 
- (void)createAlbumWithName:(NSString *)name title:(NSString *)title summary:(NSString *)summary parent:(ZWGallery *)parent
{
    if (parent == nil)
        (id)parent = (id)[NSNull null];
        
    NSDictionary *threadDispatchInfo = [NSDictionary dictionaryWithObjectsAndKeys:
        name, @"AlbumName",
        title, @"AlbumTitle",
        summary, @"AlbumSummary",
        parent, @"AlbumParent",
        [NSThread currentThread], @"CallingThread",
        nil];
 
    [NSThread detachNewThreadSelector:@selector(createAlbumThread:) toTarget:self withObject:threadDispatchInfo];
}
 
- (void)getAlbums {
    NSDictionary *threadDispatchInfo = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSThread currentThread], @"CallingThread",
        nil];
    [NSThread detachNewThreadSelector:@selector(getAlbumsThread:) toTarget:self withObject:threadDispatchInfo];
}
 
#pragma mark Helpers
 
- (NSDictionary*)parseResponseData:(NSData*)responseData {
    NSString *response = [[[NSString alloc] initWithData:responseData encoding:[self sniffedEncoding]] autorelease];
    
    if (response == nil) {
        NSLog(@"Could not convert response data into a string with encoding: %i", [self sniffedEncoding]);
        return nil;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSScanner *scanner = [NSScanner scannerWithString:response];
    // first scan up to the #__GR2PROTO__ line
    [scanner scanUpToString:@"#__GR2PROTO__\n" intoString:nil];
    if (![scanner scanString:@"#__GR2PROTO__\n" intoString:nil]) {
        return nil;
    }
    while ([scanner isAtEnd] == NO) {
        NSString *line;
        if ([scanner scanUpToString:@"\n" intoString:&line]) {
            NSArray *pair = [line componentsSeparatedByString:@"="];
            if ([pair count] > 1)
                [dict setObject:[pair objectAtIndex:1] forKey:[pair objectAtIndex:0]];
        }
    }
    
    // "status" is required - let's help ourselves out and make it an int right now
    NSString *statusStr = [dict objectForKey:@"status"];
    if (statusStr == nil) {
        return nil;
    }
    [dict setObject:[NSNumber numberWithInt:[statusStr intValue]] forKey:@"statusCode"];
    
    return [NSDictionary dictionaryWithDictionary:dict];
}
 
- (NSString *)formNameWithName:(NSString *)paramName
{
    // Gallery 1 names don't need mangling
    if (![self isGalleryV2])
        return paramName;
    
    // For some reason userfile is just changed to g2_userfile
    if ([paramName isEqualToString:@"userfile"])
        return @"g2_userfile";
    
    // All other G2 params are mangled like this:
    return [NSString stringWithFormat:@"g2_form[%@]", paramName];
}
 
#pragma mark Threads
 
- (void)loginThread:(NSDictionary *)threadDispatchInfo {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    [NSThread prepareForInterThreadMessages];
 
    NSThread *callingThread = [threadDispatchInfo objectForKey:@"CallingThread"];
    
    ZWGalleryRemoteStatusCode status = [self doLogin];
    
    if (status == GR_STAT_SUCCESS)
        [delegate performSelector:@selector(galleryDidLogin:)
                       withObject:self
                         inThread:callingThread];
    else
        [delegate performSelector:@selector(gallery:loginFailedWithCode:)
                       withObject:self
                       withObject:[NSNumber numberWithInt:status]
                         inThread:callingThread];
    
    [pool release];
}
    
- (ZWGalleryRemoteStatusCode)doLogin
{
    // remove the cookies sent to the gallery (the login function ain't so smart)
    NSHTTPCookieStorage *cookieStore = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookies = [cookieStore cookiesForURL:fullURL];
    id cookie;
    NSEnumerator *enumerator = [cookies objectEnumerator];
    while (cookie = [enumerator nextObject]) {
        [cookieStore deleteCookie:cookie];
    }
    
    // do an initial connection to get the session key
    NSMutableURLRequest *setupRequest = [NSMutableURLRequest requestWithURL:url
                                                                cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                            timeoutInterval:60.0];
    [setupRequest setHTTPMethod:@"GET"];
    
    currentConnection = [ZWURLConnection connectionWithRequest:setupRequest];
    while ([currentConnection isRunning])
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]];
    
    if ([currentConnection isCancelled])
        return ZW_GALLERY_OPERATION_DID_CANCEL;
    
    // Default to UTF-8
    sniffedEncoding = NSUTF8StringEncoding;
    NSURLResponse *response = [currentConnection response];
    NSString *encodingString = [response textEncodingName];
    if (encodingString) {
        CFStringEncoding cfStrEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)encodingString);
        if (cfStrEncoding)
            sniffedEncoding = CFStringConvertEncodingToNSStringEncoding(cfStrEncoding);
    }
    if (!sniffedEncoding)
        sniffedEncoding = NSUTF8StringEncoding;
    
    // Now try to log in (try twice - switch to other type of gallery if first try fails)
    BOOL tryGalleryV2 = [self isGalleryV2];
    NSDictionary *galleryResponse = nil;
    int tries;
    for (tries = 0; tries < 2; tries++) {
        if (!tryGalleryV2) {
            // try logging into Gallery v1
            fullURL = [[NSURL alloc] initWithString:[[url absoluteString] stringByAppendingString:@"gallery_remote2.php"]];
            NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:fullURL
                                                                      cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                                  timeoutInterval:60.0];
            [theRequest setValue:@"iPhotoToGallery 0.63" forHTTPHeaderField:@"User-Agent"];
            
            [theRequest setHTTPMethod:@"POST"];
            
            NSString *requestString = [NSString stringWithFormat:@"cmd=login&protocol_version=2.1&uname=%s&password=%s",
                [[username stringByEscapingURL] UTF8String], [[password stringByEscapingURL] UTF8String]];
            NSData *requestData = [requestString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            [theRequest setHTTPBody:requestData];
            
            currentConnection = [ZWURLConnection connectionWithRequest:theRequest];
            while ([currentConnection isRunning]) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]];
            }
            
            if ([currentConnection isCancelled])
                return ZW_GALLERY_OPERATION_DID_CANCEL;
            
            NSData *data = [currentConnection data];
            response = [currentConnection response];
 
            if (data == nil) {
                if (tryGalleryV2)
                    return ZW_GALLERY_COULD_NOT_CONNECT;
                
                // There is at least one instance (reported by adeh@desandies.com) where
                // data will be nil, even though a G2 installation does exist. In that case,
                // let's try G2 if we haven't already.
                tryGalleryV2 = YES;
                continue;
            }
            
            galleryResponse = [self parseResponseData:data];
            
            if ([(NSHTTPURLResponse *)response statusCode] == 404 || galleryResponse == nil)
                tryGalleryV2 = YES;
            else {
                // we successfully logged into a G1
                type = GalleryTypeG1;
                break;
            }
        }
        else {
            // try logging into Gallery v2
            fullURL = [[NSURL alloc] initWithString:[[url absoluteString] stringByAppendingString:@"main.php"]];
            
            NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:fullURL
                                                                      cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                                  timeoutInterval:60.0];
            [theRequest setValue:@"iPhotoToGallery" forHTTPHeaderField:@"User-Agent"];
            [theRequest setHTTPMethod:@"POST"];
            
            NSString *requestString = [NSString stringWithFormat:@"g2_controller=remote:GalleryRemote&g2_form[cmd]=login&g2_form[protocol_version]=2.2&g2_form[uname]=%s&g2_form[password]=%s",
                [[username stringByEscapingURL] UTF8String], [[password stringByEscapingURL] UTF8String]];
            NSData *requestData = [requestString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            [theRequest setHTTPBody:requestData];
            
            currentConnection = [ZWURLConnection connectionWithRequest:theRequest];
            while ([currentConnection isRunning]) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]];
            }
            
            if ([currentConnection isCancelled])
                return ZW_GALLERY_OPERATION_DID_CANCEL;
            
            NSData *data = [currentConnection data];
            response = [currentConnection response];
            
            if (data == nil)
                return ZW_GALLERY_COULD_NOT_CONNECT;
            
            galleryResponse = [self parseResponseData:data];
            if ([(NSHTTPURLResponse *)response statusCode] == 404 || galleryResponse == nil)
                tryGalleryV2 = NO;
            else {
                // we successfully logged into a G2
                type = GalleryTypeG2;
                break;
            }
        }
    }
    
    if (galleryResponse == nil)
        return ZW_GALLERY_PROTOCOL_ERROR;
    
    ZWGalleryRemoteStatusCode status = (ZWGalleryRemoteStatusCode)[[galleryResponse objectForKey:@"statusCode"] intValue];
    
    if (status == GR_STAT_PASSWD_WRONG)
        return GR_STAT_PASSWD_WRONG;
    
    // lookup version
    NSString *version = [galleryResponse objectForKey:@"server_version"];
    if (version == nil)
        return ZW_GALLERY_PROTOCOL_ERROR;
    NSArray *versionArray = [version componentsSeparatedByString:@"."];
    majorVersion = [[versionArray objectAtIndex:0] intValue];
    minorVersion = [[versionArray objectAtIndex:1] intValue];
    
    if (status == GR_STAT_SUCCESS) {
        loggedIn = YES;
        
        NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[(NSHTTPURLResponse*)response allHeaderFields] forURL:fullURL];
        NSEnumerator *c = [cookies objectEnumerator];
        id cookie;
        while (cookie = [c nextObject])
            [cookieStore setCookie:cookie];
 
        return GR_STAT_SUCCESS;
    }
    
    return ZW_GALLERY_UNKNOWN_ERROR;
}
 
- (void)getAlbumsThread:(NSDictionary *)threadDispatchInfo {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
    [NSThread prepareForInterThreadMessages];
 
    NSThread *callingThread = [threadDispatchInfo objectForKey:@"CallingThread"];
    
    ZWGalleryRemoteStatusCode status = [self doGetAlbums];
    
    if (status == GR_STAT_SUCCESS)
        [delegate performSelector:@selector(galleryDidGetAlbums:)
                       withObject:self
                         inThread:callingThread];
    else
        [delegate performSelector:@selector(gallery:getAlbumsFailedWithCode:)
                       withObject:self
                       withObject:[NSNumber numberWithInt:status]
                         inThread:callingThread];
 
    [pool release];
}
 
- (ZWGalleryRemoteStatusCode)doGetAlbums
{
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:fullURL
                                                              cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                          timeoutInterval:60.0];
    [theRequest