Initial implementation of 'others shared'.
[pithos-macos] / pithos-macos / pithos_macosAppDelegate.m
1 //
2 //  pithos_macosAppDelegate.m
3 //  pithos-macos
4 //
5 // Copyright 2011 GRNET S.A. All rights reserved.
6 //
7 // Redistribution and use in source and binary forms, with or
8 // without modification, are permitted provided that the following
9 // conditions are met:
10 // 
11 //   1. Redistributions of source code must retain the above
12 //      copyright notice, this list of conditions and the following
13 //      disclaimer.
14 // 
15 //   2. Redistributions in binary form must reproduce the above
16 //      copyright notice, this list of conditions and the following
17 //      disclaimer in the documentation and/or other materials
18 //      provided with the distribution.
19 // 
20 // THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
21 // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
24 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
27 // USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 // POSSIBILITY OF SUCH DAMAGE.
32 // 
33 // The views and conclusions contained in the software and
34 // documentation are those of the authors and should not be
35 // interpreted as representing official policies, either expressed
36 // or implied, of GRNET S.A.
37
38 #import "pithos_macosAppDelegate.h"
39 #import "PithosBrowserController.h"
40 #import "PithosPreferencesController.h"
41 #import "ASIPithosRequest.h"
42 #import "ASIDownloadCache.h"
43
44 @implementation pithos_macosAppDelegate
45 @synthesize storageURLPrefix, publicURLPrefix;
46
47 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
48     // XXX hardcoded for now
49     storageURLPrefix = @"https://pithos.dev.grnet.gr/v1";
50     publicURLPrefix = @"https://pithos.dev.grnet.gr";
51     
52     [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self 
53                                                        andSelector:@selector(handleAppleEvent:withReplyEvent:) 
54                                                      forEventClass:kInternetEventClass 
55                                                         andEventID:kAEGetURL];
56     //[pithosBrowserController showWindow:self];
57     [self showPithosBrowser:self];
58     
59     [self authenticateWithAuthUser:[[userDefaultsController values] valueForKey:@"authUser"] 
60                          authToken:[[userDefaultsController values] valueForKey:@"authToken"]];
61 }
62
63 // Based on: http://cocoatutorial.grapewave.com/2010/01/creating-a-status-bar-application/
64 // and: http://www.cocoadev.com/index.pl?ThumbnailImages
65 - (void)awakeFromNib {
66     NSImage *sourceImage = [NSImage imageNamed:NSImageNameFolder];
67     
68     NSImage *smallImage = [[[NSImage alloc] initWithSize:NSMakeSize(18, 18)] autorelease];
69     [smallImage lockFocus];
70     [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
71     [sourceImage setSize:NSMakeSize(18, 18)];
72     [sourceImage compositeToPoint:NSZeroPoint operation:NSCompositeCopy];
73     [smallImage unlockFocus];
74     
75     statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
76     [statusItem setMenu:statusMenu];
77     [statusItem setImage:sourceImage];
78     [statusItem setHighlightMode:YES];
79 }
80
81 - (void)handleAppleEvent:(NSAppleEventDescriptor *)event withReplyEvent: (NSAppleEventDescriptor *)replyEvent {
82     NSURL *url = [NSURL URLWithString:[[event paramDescriptorForKeyword:keyDirectObject] stringValue]];
83     NSString *host = [url host];
84         NSString *query = [url query];
85     NSLog(@"host : '%@', query: '%@'", host, query);
86     NSProcessInfo *processInfo = [NSProcessInfo processInfo];
87     if ([host isEqualToString:[NSString stringWithFormat:@"%@_%d", [processInfo processName], [processInfo processIdentifier]]] && query) {
88         // user=
89         NSString *authUser;
90         NSRange userRange = [query rangeOfString:@"user=" options:NSCaseInsensitiveSearch];
91         if (userRange.length == 0)
92             // XXX maybe show an error message?
93             return;
94         NSUInteger authUserStartLocation = userRange.location + userRange.length;
95         NSRange userEndRange = [query rangeOfString:@"&" options:NSCaseInsensitiveSearch 
96                                               range:NSMakeRange(authUserStartLocation, [query length] - authUserStartLocation)];
97         if (userEndRange.length) {
98             authUser = [[query substringWithRange:NSMakeRange(authUserStartLocation, userEndRange.location - authUserStartLocation)]
99                         stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
100         } else {
101             authUser = [[query substringFromIndex:authUserStartLocation]
102                         stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
103         }
104         // token=
105         NSString *authToken;
106         NSRange tokenRange = [query rangeOfString:@"token=" options:NSCaseInsensitiveSearch];
107         if (tokenRange.length == 0)
108             // XXX maybe show an error message?
109             return;
110         NSUInteger authTokenStartLocation = tokenRange.location + tokenRange.length;
111         NSRange tokenEndRange = [query rangeOfString:@"&" options:NSCaseInsensitiveSearch 
112                                               range:NSMakeRange(authTokenStartLocation, [query length] - authTokenStartLocation)];
113         if (tokenEndRange.length) {
114             authToken = [[query substringWithRange:NSMakeRange(authTokenStartLocation, tokenEndRange.location - authTokenStartLocation)]
115                          stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
116         } else {
117             authToken = [[query substringFromIndex:authTokenStartLocation]
118                          stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
119         }
120         
121         NSLog(@"query authUser: '%@', authToken: '%@'", authUser, authToken);
122         if ([authUser length] && [authToken length]) {
123             [[userDefaultsController values] setValue:authUser forKey:@"authUser"];
124             [[userDefaultsController values] setValue:authToken forKey:@"authToken"];
125             
126             [self authenticateWithAuthUser:authUser authToken:authToken];
127         }
128         // XXX else maybe show an error message?
129     }
130     // XXX else maybe show an error message?
131 }
132
133 #pragma mark -
134 #pragma Actions
135
136 - (IBAction)showPithosBrowser:(id)sender {
137     [pithosBrowserController showWindow:sender];
138     [[pithosBrowserController window] makeKeyAndOrderFront:sender];
139     [NSApp activateIgnoringOtherApps:YES];
140 }
141
142 - (IBAction)showPithosPreferences:(id)sender {
143     [pithosPreferencesController showWindow:sender];
144     [[pithosPreferencesController window] makeKeyAndOrderFront:sender];
145     [NSApp activateIgnoringOtherApps:YES];
146 }
147
148 - (IBAction)aboutPithos:(id)sender {
149     [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://pithos.dev.grnet.gr/docs"]];
150 }
151
152 #pragma mark -
153 #pragma Authentication
154
155 - (void)authenticateWithAuthUser:(NSString *)authUser authToken:(NSString *)authToken {
156     NSLog(@"Authentication - storageURLPrefix:%@, authUser:%@, authToken:%@", storageURLPrefix, authUser, authToken);
157     if ([authUser length] && [authToken length]) {
158         [[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];
159         [ASIPithosRequest setAuthURL:storageURLPrefix];
160         [ASIPithosRequest setStorageURLPrefix:storageURLPrefix];
161         [ASIPithosRequest setAuthUser:authUser];
162         [ASIPithosRequest setAuthToken:authToken];
163         [ASIPithosRequest setPublicURLPrefix:publicURLPrefix];
164         
165         [[NSNotificationCenter defaultCenter] postNotificationName:@"PithosAuthenticationCredentialsUpdated" object:self];
166     }
167 }
168
169 @end