summaryrefslogtreecommitdiff
path: root/QSDeliciousPlugIn_Source.m
blob: 49526e125f50310957428be9d27bffefd161332f (plain)
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
//
//  QSDeliciousPlugIn_Source.m
//  QSDeliciousPlugIn
//
//  Created by Nicholas Jitkoff on 9/18/04.
//  Copyright __MyCompanyName__ 2004. All rights reserved.
//

#import "QSDeliciousPlugIn_Source.h"
#import "Constants.h"
#import <QSCore/QSCore.h>
#import <Security/Security.h>

@implementation QSDeliciousPlugIn_Source

#pragma mark - Lifecycle

// This method will get called whenever we change which
// active entry is selected.
- (void)setSelectedEntry:(id)selectedEntry {
  [super setSelectedEntry:selectedEntry];
  [self loadPasswordFromKeychain];
}

#pragma mark - Quicksilver Source Methods

- (BOOL)indexIsValidFromDate:(NSDate *)indexDate
                    forEntry:(NSDictionary *)theEntry {
  return -[indexDate timeIntervalSinceNow] < 24 * 60 * 60;
}

- (BOOL)isVisibleSource {
  return YES;
}

- (NSImage *)iconForEntry:(NSDictionary *)dict {
  return [[NSBundle bundleForClass:[self class]] imageNamed:@"bookmark_icon"];
}

- (NSView *)settingsView {
  if (![super settingsView]) {
    [[NSBundle bundleForClass:[self class]]
           loadNibNamed:NSStringFromClass([self class])
                  owner:self
        topLevelObjects:NULL];
  }
  return [super settingsView];
}

#pragma mark - Settings Helpers

- (SocialSite)siteIndex {
  NSDictionary *settings = self.selectedEntry.sourceSettings;
  return [settings objectForKey:@"site"] != nil
             ? [[settings objectForKey:@"site"] integerValue]
             : SocialSiteDelicious;
}

- (NSString *)currentUsername {
  return [self.selectedEntry.sourceSettings objectForKey:@"username"];
}

- (NSString *)currentHost {
  return [self.selectedEntry.sourceSettings objectForKey:@"host"];
}

- (NSString *)currentPassword {
  return self.internalPassword;
}

- (BOOL)includeTags {
  return [[self.selectedEntry.sourceSettings objectForKey:@"includeTags"]
      boolValue];
}

// This method is called on action from all the NIB methods
// to force the catalog to save the current values.
- (IBAction)settingsChanged:(id)sender {
  [[NSNotificationCenter defaultCenter]
      postNotificationName:QSCatalogEntryChangedNotification
                    object:self.selectedEntry];
  [self willChangeValueForKey:@"isHostVisible"];
  [self didChangeValueForKey:@"isHostVisible"];
}

#pragma mark - Keychain Helper Methods

- (NSString *)keychainKeyForIdentifier:(NSString *)identifier {
  return [NSString stringWithFormat:@"QSSocialBookmarks-%@", identifier];
}

- (NSString *)passwordFromKeychainForKey:(NSString *)key {
  const char *service = "QSSocialBookmarks";
  const char *account = [key UTF8String];

  UInt32 passwordLength = 0;
  void *passwordData = NULL;

  OSStatus status = SecKeychainFindGenericPassword(
      NULL, (UInt32)strlen(service), service, (UInt32)strlen(account), account,
      &passwordLength, &passwordData, NULL);

  if (status == errSecSuccess && passwordData != NULL) {
    NSString *password = [[NSString alloc] initWithBytes:passwordData
                                                  length:passwordLength
                                                encoding:NSUTF8StringEncoding];
    SecKeychainItemFreeContent(NULL, passwordData);
    return password;
  }

  return nil;
}

- (OSStatus)savePasswordToKeychainForKey:(NSString *)key
                                password:(NSString *)password {
  const char *service = "QSSocialBookmarks";
  const char *account = [key UTF8String];
  const char *passwordCString = [password UTF8String];

  // First try to find existing item
  SecKeychainItemRef item = NULL;
  OSStatus findStatus = SecKeychainFindGenericPassword(
      NULL, (UInt32)strlen(service), service, (UInt32)strlen(account), account,
      NULL, NULL, &item);

  OSStatus status;
  if (findStatus == errSecSuccess) {
    // Update existing item
    status = SecKeychainItemModifyAttributesAndData(
        item, NULL, (UInt32)strlen(passwordCString), passwordCString);
    CFRelease(item);
  } else {
    // Create new item
    status = SecKeychainAddGenericPassword(
        NULL, (UInt32)strlen(service), service, (UInt32)strlen(account),
        account, (UInt32)strlen(passwordCString), passwordCString, NULL);
  }

  return status;
}

- (OSStatus)deletePasswordFromKeychainForKey:(NSString *)key {
  const char *service = "QSSocialBookmarks";
  const char *account = [key UTF8String];

  SecKeychainItemRef item = NULL;
  OSStatus findStatus = SecKeychainFindGenericPassword(
      NULL, (UInt32)strlen(service), service, (UInt32)strlen(account), account,
      NULL, NULL, &item);

  if (findStatus == errSecSuccess) {
    OSStatus deleteStatus = SecKeychainItemDelete(item);
    CFRelease(item);
    return deleteStatus;
  }

  return findStatus;
}

#pragma mark - Password Keychain Methods

- (void)loadPasswordFromKeychain {
  if (!self.selectedEntry || !self.selectedEntry.identifier) {
    self.internalPassword = nil;
    return;
  }

  NSString *keychainKey =
      [self keychainKeyForIdentifier:self.selectedEntry.identifier];
  [self setPassword:[self passwordFromKeychainForKey:keychainKey]];
}

- (void)savePasswordToKeychain {
  if (!self.selectedEntry || !self.selectedEntry.identifier ||
      !self.internalPassword) {
    return;
  }

  NSString *keychainKey =
      [self keychainKeyForIdentifier:self.selectedEntry.identifier];
  OSStatus status = [self savePasswordToKeychainForKey:keychainKey
                                              password:self.internalPassword];

  if (status != errSecSuccess) {
    NSLog(@"Failed to save password to keychain for key: %@, status: %d",
          keychainKey, (int)status);
  }
}

#pragma mark - Password Property Accessors

- (NSString *)password {
  return self.internalPassword;
}

- (void)setPassword:(NSString *)password {
  self.internalPassword = password;

  // Save to keychain asynchronously
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
                 ^{
                   [self savePasswordToKeychain];
                 });
}

#pragma mark - Host Visibility Control
- (BOOL)isHostVisible {
  return [SocialSiteHelper hasVariableHost:[self siteIndex]];
}
- (void)setIsHostVisible:(BOOL)isVisible {
}

#pragma mark - Objects For Entry

- (NSArray *)objectsForEntry:(QSCatalogEntry *)theEntry {

  NSDictionary *settings = theEntry.sourceSettings;

  SocialSite site = [settings objectForKey:@"site"] != nil
                        ? [[settings objectForKey:@"site"] integerValue]
                        : SocialSiteDelicious;
  NSString *username = [settings objectForKey:@"username"];
  NSString *identifier = theEntry.identifier;
  NSString *keychainKey = [self keychainKeyForIdentifier:identifier];
  NSString *password = [self passwordFromKeychainForKey:keychainKey];
  NSString *host = [settings objectForKey:@"host"];
  BOOL includeTags = [settings objectForKey:@"includeTags"];

  QSBookmarkProviderFactory *factory =
      [QSBookmarkProviderFactory sharedFactory];
  id<QSBookmarkProvider> provider = [factory providerForSite:site
                                                    username:username
                                                    password:password
                                                        host:host];

  if (!provider) {
    NSLog(@"No provider available for site %ld with username %@", (long)site,
          username);
    return @[];
  }

  return [provider fetchBookmarksForSite:site
                                username:username
                                password:password
                              identifier:identifier
                                    host:host
                             includeTags:includeTags];
}

- (NSArray *)objectsForTag:(NSString *)tag
                      site:(SocialSite)site
                  username:(NSString *)username
                identifier:(NSString *)identifier
                      host:(NSString *)host {

  NSString *keychainKey = [self keychainKeyForIdentifier:identifier];
  NSString *password = [self passwordFromKeychainForKey:keychainKey];

  QSBookmarkProviderFactory *factory =
      [QSBookmarkProviderFactory sharedFactory];
  id<QSBookmarkProvider> provider = [factory providerForSite:site
                                                    username:username
                                                    password:password
                                                        host:host];

  if (!provider) {
    NSLog(@"No provider available for site %ld with username %@", (long)site,
          username);
    return @[];
  }

  // Check if provider supports tag-based fetching
  if ([provider respondsToSelector:@selector
                (fetchBookmarksForTag:site:username:password:host:)]) {
    return [provider fetchBookmarksForTag:tag
                                     site:site
                                 username:username
                                 password:password
                                     host:host];
  }

  return @[];
}

#pragma mark - Object Handler Methods

- (void)setQuickIconForObject:(QSObject *)object {
  if (@available(macOS 11.0, *)) {
    NSImage *image = [NSImage imageWithSystemSymbolName:@"tag"
                               accessibilityDescription:@"Bookmark"];
    [object setIcon:image];
  } else {
    [object setIcon:[[NSBundle bundleForClass:[self class]]
                        imageNamed:@"bookmark_icon"]];
  }
}

// All our objects will have children. URLs will have tags, and tags will have
// URLs.
- (BOOL)objectHasChildren:(QSObject *)object {
  return YES;
}

// This will receive a tag object. Tag objects will have the
// source configuration in the meta: source.username,
// source.site, source.host and source.identifier.
- (BOOL)loadChildrenForObject:(QSObject *)object {

  NSNumber *siteNumber = [object objectForMeta:@"source.site"];
  if (!siteNumber) {
    NSLog(@"The tag didn't have a valid site.");
    return NO;
  }

  SocialSite site = [siteNumber integerValue];

  NSString *username = [object objectForMeta:@"source.username"];
  if (!username) {
    NSLog(@"The tag didn't have a valid username.");
    return NO;
  }
  NSString *identifier = [object objectForMeta:@"source.identifier"];
  if (!identifier) {
    NSLog(@"The tag didn't have a valid identifier.");
    return NO;
  }

  NSString *host = [object objectForMeta:@"source.host"];
  if (site == SocialSiteLinkding && !host) {
    NSLog(@"The tag didn't have a host, and its site requires it.");
    return NO;
  }

  NSString *tag = [object objectForType:kTagType];
  if (!tag) {
    NSLog(@"We could not find a valid tag type.");
    return NO;
  }

  NSArray *children = [self objectsForTag:tag
                                     site:site
                                 username:username
                               identifier:identifier
                                     host:host];
  [object setChildren:children];
  return YES;
}

@end