~jose-exposito89/ubuntuone-ios-files/social-networking

« back to all changes in this revision

Viewing changes to Dependencies/ShareKit/Classes/ShareKit/Sharers/Services/Evernote/SHKEvernote.m

  • Committer: José Expósito
  • Date: 2012-10-23 15:22:36 UTC
  • Revision ID: jose.exposito89@gmail.com-20121023152236-f2rfafq000ex0vgz
Added support to share links in social networks

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
//
 
2
//  SHKEvernote
 
3
//  ShareKit Evernote Additions
 
4
//
 
5
//  Created by Atsushi Nagase on 8/28/10.
 
6
//  Copyright 2010 LittleApps Inc. All rights reserved.
 
7
//
 
8
 
 
9
#import "SHKEvernote.h"
 
10
#import "NSData+md5.h"
 
11
#import "SHKConfiguration.h"
 
12
#import "EvernoteSDK.h"
 
13
#import "GTMNSString+HTML.h"
 
14
#import "SHKActivityIndicator.h"
 
15
 
 
16
@implementation SHKEvernoteItem
 
17
@synthesize note;
 
18
 
 
19
- (void)dealloc {
 
20
        [note release];
 
21
        [super dealloc];        
 
22
}
 
23
 
 
24
@end
 
25
 
 
26
@implementation SHKEvernote
 
27
 
 
28
- (id)init
 
29
{
 
30
    self = [super init];
 
31
    if (self) {
 
32
        [[self class] fillEvernoteSessionWithAppConfig];
 
33
    }
 
34
    return self;
 
35
}
 
36
 
 
37
+ (void)fillEvernoteSessionWithAppConfig
 
38
{
 
39
    NSString *evernoteHost = SHKCONFIG(evernoteHost);
 
40
    NSString *consumerKey = SHKCONFIG(evernoteConsumerKey);
 
41
    NSString *consumerSecret = SHKCONFIG(evernoteSecret);
 
42
    [EvernoteSession setSharedSessionHost:evernoteHost
 
43
                              consumerKey:consumerKey 
 
44
                           consumerSecret:consumerSecret];
 
45
}
 
46
 
 
47
#pragma mark -
 
48
#pragma mark Configuration : Service Defination
 
49
 
 
50
+ (NSString *)sharerTitle { return @"Evernote"; }
 
51
+ (BOOL)canShareURL   { return YES; }
 
52
+ (BOOL)canShareImage { return YES; }
 
53
+ (BOOL)canShareText  { return YES; }
 
54
+ (BOOL)canShareFile  { return YES; }
 
55
+ (BOOL)requiresAuthentication { return YES; }
 
56
 
 
57
 
 
58
#pragma mark -
 
59
#pragma mark Configuration : Dynamic Enable
 
60
 
 
61
+ (BOOL)canShare {      return YES; }
 
62
 
 
63
#pragma mark -
 
64
#pragma mark Authentication
 
65
 
 
66
- (BOOL)isAuthorized {
 
67
    EvernoteSession *session = [EvernoteSession sharedSession];
 
68
    return session.isAuthenticated;
 
69
}
 
70
 
 
71
- (void)promptAuthorization {
 
72
    EvernoteSession *session = [EvernoteSession sharedSession];
 
73
    [session authenticateWithViewController:[SHK currentHelper].rootViewForCustomUIDisplay completionHandler:^(NSError *error) {
 
74
        BOOL success = (error == nil) && session.isAuthenticated;
 
75
        [self authDidFinish:success];
 
76
        if (error) {
 
77
            [[[[UIAlertView alloc] initWithTitle:SHKLocalizedString(@"Authorize Error")
 
78
                                         message:SHKLocalizedString(@"There was an error while authorizing")
 
79
                                        delegate:nil
 
80
                                   cancelButtonTitle:SHKLocalizedString(@"Close")
 
81
                                   otherButtonTitles:nil] autorelease] show];
 
82
            
 
83
        } else if (session.isAuthenticated && self.item) {
 
84
            [self tryPendingAction];
 
85
        } 
 
86
    }];
 
87
}
 
88
 
 
89
+ (void)logout {
 
90
    
 
91
    [self fillEvernoteSessionWithAppConfig];
 
92
    EvernoteSession *session = [EvernoteSession sharedSession];
 
93
    [session logout];
 
94
}
 
95
 
 
96
 
 
97
#pragma mark -
 
98
#pragma mark Share Form
 
99
 
 
100
- (NSArray *)shareFormFieldsForType:(SHKShareType)type 
 
101
{
 
102
        return [NSArray arrayWithObjects:
 
103
         [SHKFormFieldSettings label:SHKLocalizedString(@"Title") key:@"title" type:SHKFormFieldTypeText start:item.title],
 
104
         //[SHKFormFieldSettings label:SHKLocalizedString(@"Memo")  key:@"text" type:SHKFormFieldTypeText start:item.text],
 
105
         [SHKFormFieldSettings label:SHKLocalizedString(@"Tag, tag")  key:@"tags" type:SHKFormFieldTypeText start:[item.tags componentsJoinedByString:@", "]],
 
106
         nil];
 
107
}
 
108
 
 
109
- (void)shareFormValidate:(SHKFormController *)form 
 
110
{       
 
111
        [form saveForm];
 
112
}
 
113
 
 
114
#pragma mark -
 
115
#pragma mark Implementation
 
116
 
 
117
- (BOOL)send {
 
118
        if (![self validateItem])
 
119
                return NO;
 
120
        [self sendDidStart];
 
121
    
 
122
    EvernoteNoteStore *noteStore = [EvernoteNoteStore noteStore];
 
123
    
 
124
    SHKEvernoteItem *enItem = nil;
 
125
    NSMutableArray *resources = nil;
 
126
    EDAMNote *note = nil;
 
127
    if([item isKindOfClass:[SHKEvernoteItem class]]) {
 
128
        enItem = (SHKEvernoteItem *)item;
 
129
        note = enItem.note;
 
130
        resources = [note.resources mutableCopy];
 
131
    }
 
132
    
 
133
    if(!resources)
 
134
        resources = [[NSMutableArray alloc] init];
 
135
    if(!note)
 
136
        note = [[[EDAMNote alloc] init] autorelease];
 
137
    
 
138
    
 
139
    EDAMNoteAttributes *atr = [note attributesIsSet] ? [note.attributes retain] : [[EDAMNoteAttributes alloc] init];
 
140
    
 
141
    if(![atr sourceURLIsSet]&&enItem.URL) {
 
142
        [atr setSourceURL:[enItem.URL absoluteString]];
 
143
    }
 
144
    
 
145
    note.title = item.title.length > 0 ? item.title :( [note titleIsSet] ? note.title : SHKLocalizedString(@"Untitled") );
 
146
    
 
147
    if(![note tagNamesIsSet]&&item.tags)
 
148
        [note setTagNames:item.tags];
 
149
    
 
150
    if(![note contentIsSet]) {
 
151
        NSMutableString* contentStr = [[NSMutableString alloc] initWithString:kENMLPrefix];
 
152
        NSString * strURL = [item.URL absoluteString];
 
153
        
 
154
        // Evernote doesn't accept unenencoded ampersands
 
155
        strURL = SHKEncode(strURL);
 
156
        
 
157
        if(strURL.length>0) {
 
158
            if(item.title.length>0)
 
159
                [contentStr appendFormat:@"<h1><a href=\"%@\">%@</a></h1>",strURL,[item.title gtm_stringByEscapingForHTML]];
 
160
            [contentStr appendFormat:@"<p><a href=\"%@\">%@</a></p>",strURL,strURL ];
 
161
            atr.sourceURL = strURL;
 
162
        } else if(item.title.length>0)
 
163
            [contentStr appendFormat:@"<h1>%@</h1>",[item.title gtm_stringByEscapingForHTML]];
 
164
        
 
165
        if(item.text.length>0 )
 
166
            [contentStr appendFormat:@"<p>%@</p>", [SHKFlattenHTML(item.text, YES) gtm_stringByEscapingForHTML]];
 
167
        
 
168
        if(item.image) {
 
169
            EDAMResource *img = [[[EDAMResource alloc] init] autorelease];
 
170
            NSData *rawimg = UIImageJPEGRepresentation(item.image, 0.6);
 
171
            EDAMData *imgd = [[[EDAMData alloc] initWithBodyHash:rawimg size:[rawimg length] body:rawimg] autorelease];
 
172
            [img setData:imgd];
 
173
            [img setRecognition:imgd];
 
174
            [img setMime:@"image/jpeg"];
 
175
            [resources addObject:img];
 
176
            [contentStr appendString:[NSString stringWithFormat:@"<p>%@</p>",[self enMediaTagWithResource:img width:item.image.size.width height:item.image.size.height]]];
 
177
        }
 
178
        
 
179
        if(item.data) {
 
180
            EDAMResource *file = [[[EDAMResource alloc] init] autorelease];     
 
181
            EDAMData *filed = [[[EDAMData alloc] initWithBodyHash:item.data size:[item.data length] body:item.data] autorelease];
 
182
            [file setData:filed];
 
183
            [file setRecognition:filed];
 
184
            [file setMime:item.mimeType];
 
185
            [resources addObject:file];
 
186
            [contentStr appendString:[NSString stringWithFormat:@"<p>%@</p>",[self enMediaTagWithResource:file width:0 height:0]]];
 
187
        }
 
188
        [contentStr appendString:kENMLSuffix];
 
189
        [note setContent:contentStr];
 
190
        [contentStr release];
 
191
    }
 
192
    
 
193
    ////////////////////////////////////////////////
 
194
    // Replace <img> HTML elements with en-media elements
 
195
        ////////////////////////////////////////////////
 
196
    
 
197
    for(EDAMResource *res in resources) {
 
198
        if(![res dataIsSet]&&[res attributesIsSet]&&res.attributes.sourceURL.length>0&&[res.mime isEqualToString:@"image/jpeg"]) {
 
199
            @try {
 
200
                NSData *rawimg = [NSData dataWithContentsOfURL:[NSURL URLWithString:res.attributes.sourceURL]];
 
201
                UIImage *img = [UIImage imageWithData:rawimg];
 
202
                if(img) {
 
203
                    EDAMData *imgd = [[[EDAMData alloc] initWithBodyHash:rawimg size:[rawimg length] body:rawimg] autorelease];
 
204
                    [res setData:imgd];
 
205
                    [res setRecognition:imgd];
 
206
                    [note setContent:
 
207
                     [note.content stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"<img src=\"%@\" />",res.attributes.sourceURL]
 
208
                                                             withString:[self enMediaTagWithResource:res width:img.size.width height:img.size.height]]];
 
209
                }
 
210
            }
 
211
            @catch (NSException * e) {
 
212
                SHKLog(@"Caught: %@",e);
 
213
            }
 
214
        }
 
215
    }
 
216
    [note setResources:resources];
 
217
    [note setAttributes:atr];
 
218
    [resources release];
 
219
    [atr release];
 
220
    [note setCreated:(long long)[[NSDate date] timeIntervalSince1970] * 1000];
 
221
    
 
222
    
 
223
    void (^successBlock)(EDAMNote *note) = ^(EDAMNote *note) {        
 
224
        [self sendDidFinish];
 
225
    };
 
226
    void (^failureBlock)(NSError *error) = ^(NSError *error) {
 
227
        if (error.code == EDAMErrorCode_INVALID_AUTH || error.code == EDAMErrorCode_AUTH_EXPIRED) {
 
228
            [self shouldReloginWithPendingAction:SHKPendingSend];
 
229
        } else {
 
230
            [self sendDidFailWithError:[SHK error:SHKLocalizedString(@"There was a problem sharing with Evernote")]];
 
231
        }
 
232
    };
 
233
    
 
234
    if(![note notebookGuidIsSet]) {
 
235
        [noteStore getDefaultNotebookWithSuccess:^(EDAMNotebook *notebook) {
 
236
            [note setNotebookGuid:[notebook guid]];
 
237
            [noteStore createNote:note success:successBlock failure:failureBlock];
 
238
        } failure:^(NSError *error) {
 
239
            if (error.code == EDAMErrorCode_INVALID_AUTH || error.code == EDAMErrorCode_AUTH_EXPIRED) {
 
240
                [self shouldReloginWithPendingAction:SHKPendingSend];
 
241
            } else {
 
242
                [self sendDidFailWithError:[SHK error:SHKLocalizedString(@"There was a problem sharing with Evernote")]];
 
243
                [noteStore createNote:note success:successBlock failure:failureBlock];
 
244
            }
 
245
        }];
 
246
    } else {
 
247
        [noteStore createNote:note success:successBlock failure:failureBlock];
 
248
    }
 
249
        return YES;
 
250
}
 
251
 
 
252
- (NSString *)enMediaTagWithResource:(EDAMResource *)src width:(CGFloat)width height:(CGFloat)height {
 
253
        NSString *sizeAtr = width > 0 && height > 0 ? [NSString stringWithFormat:@"height=\"%.0f\" width=\"%.0f\" ",height,width]:@"";
 
254
        return [NSString stringWithFormat:@"<en-media type=\"%@\" %@hash=\"%@\"/>",src.mime,sizeAtr,[src.data.body md5]];
 
255
}
 
256
 
 
257
@end