Codebase list agenda.app / upstream/0.43 GroupDAVStore.m
upstream/0.43

Tree @upstream/0.43 (Download .tar.gz)

GroupDAVStore.m @upstream/0.43raw · history · blame

  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
#import <AppKit/AppKit.h>
#import <GNUstepBase/GSXML.h>
#import "Event.h"
#import "Task.h"
#import "AgendaStore.h"
#import "WebDAVResource.h"
#import "iCalTree.h"
#import "NSString+SimpleAgenda.h"
#import "InvocationOperation.h"
#import "StoreManager.h"
#import "defines.h"

@interface GroupDAVStore : MemoryStore <AgendaStore>
{
  NSURL *_url;
  WebDAVResource *_calendar;
  WebDAVResource *_task;
  NSMutableDictionary *_uidhref;
  NSMutableDictionary *_hreftree;
  NSMutableDictionary *_hrefresource;
  NSMutableArray *_modifiedhref;
}
@end

@interface GroupDAVDialog : NSObject
{
  IBOutlet id panel;
  IBOutlet id name;
  IBOutlet id url;
  IBOutlet id cancel;
  IBOutlet id ok;
  IBOutlet id check;
  IBOutlet id calendar;
  IBOutlet id task;
}
- (BOOL)show;
- (NSString *)url;
- (NSString *)calendar;
- (NSString *)task;
- (void)selectItem:(id)sender;
@end
@implementation GroupDAVDialog
- (void)clearPopUps
{
  [calendar removeAllItems];
  [task removeAllItems];
  [calendar addItemWithTitle:@"None"];
  [task addItemWithTitle:@"None"];
}
- (id)initWithName:(NSString *)storeName
{
  self = [super init];
  if (self) {
    if (![NSBundle loadNibNamed:@"GroupDAV" owner:self])
      return nil;
    [name setStringValue:storeName];
    [url setStringValue:@"http://"];
    [self clearPopUps];
  }
  return self;
}
- (void)dealloc
{
  [panel close];
  [super dealloc];
}
- (BOOL)show
{
  [ok setEnabled:NO];
  return [NSApp runModalForWindow:panel];
}
- (void)buttonClicked:(id)sender
{
  if (sender == cancel)
    [NSApp stopModalWithCode:0];
  else if (sender == ok)
    [NSApp stopModalWithCode:1];
  else if (sender == check)
    [self controlTextDidEndEditing:nil];
}

- (void)updateOK
{
  if ([calendar indexOfSelectedItem] > 0 || [task indexOfSelectedItem] > 0)
    [ok setEnabled:YES];
  else
    [ok setEnabled:NO];
}
- (void)selectItem:(id)sender
{
  [self updateOK];
}
- (void)controlTextDidEndEditing:(NSNotification *)aNotification
{
  int i;
  WebDAVResource *resource;
  GSXMLParser *parser;
  NSString *body = @"<?xml version=\"1.0\" encoding=\"utf-8\"?><propfind xmlns=\"DAV:\"><prop><getlastmodified/><executable/><resourcetype/></prop></propfind>";
  GSXPathContext *xpc;
  GSXPathNodeSet *set;

  [self clearPopUps];
  if ([[url stringValue] isValidURL]) {
    resource = [[WebDAVResource alloc] initWithURL:[NSURL URLWithString:[url stringValue]]];
    if ([resource propfind:[body dataUsingEncoding:NSUTF8StringEncoding] attributes:[NSDictionary dictionaryWithObject:@"Infinity" forKey:@"Depth"]]) {
      parser = [GSXMLParser parserWithData:[resource data]];
      if ([parser parse]) {
	xpc = [[GSXPathContext alloc] initWithDocument:[[parser document] strippedDocument]];
	set = (GSXPathNodeSet *)[xpc evaluateExpression:@"//response[propstat/prop/resourcetype/vevent-collection]/href/text()"];
	for (i = 0; i < [set count]; i++)
	  [calendar addItemWithTitle:[[set nodeAtIndex:i] content]];
	set = (GSXPathNodeSet *)[xpc evaluateExpression:@"//response[propstat/prop/resourcetype/vtodo-collection]/href/text()"];
	for (i = 0; i < [set count]; i++)
	  [task addItemWithTitle:[[set nodeAtIndex:i] content]];
	RELEASE(xpc);
	if ([calendar numberOfItems] > 0)
	  [calendar selectItemAtIndex:1];
	if ([task numberOfItems] > 0)
	  [task selectItemAtIndex:1];
      }
    }
    [resource release];
  }
  [self updateOK];
}
- (NSString *)url
{
  return [url stringValue];
}
- (NSString *)calendar
{
  if ([calendar indexOfItem:[calendar selectedItem]] == 0)
    return nil;
  return [calendar titleOfSelectedItem];
}
- (NSString *)task
{
  if ([task indexOfItem:[task selectedItem]] == 0)
    return nil;
  return [task titleOfSelectedItem];;
}
@end

@interface GroupDAVStore(Private)
- (void)doRead;
- (void)doWrite;
@end

@implementation GroupDAVStore
- (NSDictionary *)defaults
{
  return [NSDictionary dictionaryWithObjectsAndKeys:[[NSColor redColor] description], ST_COLOR,
		       [[NSColor whiteColor] description], ST_TEXT_COLOR,
		       [NSNumber numberWithBool:NO], ST_RW,
		       [NSNumber numberWithBool:YES], ST_DISPLAY,
		       [NSNumber numberWithBool:YES], ST_ENABLED,
		       nil, nil];
}

- (id)initWithName:(NSString *)name
{
  self = [super initWithName:name];
  if (self) {
    _uidhref = [[NSMutableDictionary alloc] initWithCapacity:512];
    _hreftree = [[NSMutableDictionary alloc] initWithCapacity:512];
    _hrefresource = [[NSMutableDictionary alloc] initWithCapacity:512];
    _modifiedhref = [NSMutableArray new];
    _url = [[NSURL alloc] initWithString:[[self config] objectForKey:ST_URL]];
    _calendar = nil;
    _task = nil;
    if ([[self config] objectForKey:ST_CALENDAR_URL])
      _calendar = [[WebDAVResource alloc] initWithURL:[[NSURL alloc] initWithString:[[self config] objectForKey:ST_CALENDAR_URL]] authFromURL:_url];
    if ([[self config] objectForKey:ST_TASK_URL])
      _task = [[WebDAVResource alloc] initWithURL:[[NSURL alloc] initWithString:[[self config] objectForKey:ST_TASK_URL]] authFromURL:_url];
    [self read];
    [[NSNotificationCenter defaultCenter] addObserver:self 
					     selector:@selector(configChanged:) 
						 name:SAConfigManagerValueChanged 
					       object:[self config]];
  }
  return self;
}

+ (BOOL)isUserInstanciable
{
  return YES;
}

+ (BOOL)registerWithName:(NSString *)name
{
  ConfigManager *cm;
  GroupDAVDialog *dialog;
  NSURL *calendarURL = nil;
  NSURL *taskURL = nil;
  NSURL *baseURL;

  dialog = [[GroupDAVDialog alloc] initWithName:name];
  if ([dialog show] == YES) {
    baseURL = [NSURL URLWithString:[dialog url]];
    if ([dialog calendar])
      calendarURL = [NSURL URLWithString:[dialog calendar] possiblyRelativeToURL:baseURL];
    if ([dialog task])
      taskURL = [NSURL URLWithString:[dialog task] possiblyRelativeToURL:baseURL];
    [dialog release];
    cm = [[ConfigManager alloc] initForKey:name];
    [cm setObject:[dialog url] forKey:ST_URL];
    if (calendarURL)
      [cm setObject:[calendarURL absoluteString] forKey:ST_CALENDAR_URL];
    if (taskURL)
      [cm setObject:[taskURL absoluteString] forKey:ST_TASK_URL];
    [cm setObject:[[self class] description] forKey:ST_CLASS];
    [cm setObject:[NSNumber numberWithBool:YES] forKey:ST_RW];
    return YES;
  }
  [dialog release];
  return NO;
}

+ (NSString *)storeTypeName
{
  return @"GroupDAV";
}

- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [_url release];
  [_calendar release];
  [_task release];
  [_uidhref release];
  [_hreftree release];
  [_hrefresource release];
  [_modifiedhref release];
  [super dealloc];
}

- (void)refreshData:(NSTimer *)timer
{
  [self read];
}

- (void)add:(Element *)elt
{
  NSURL *url;
  WebDAVResource *resource;
  iCalTree *tree;

  if ([elt isKindOfClass:[Event class]])
    url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", [[_calendar url] absoluteString], [elt UID]]];
  else
    url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", [[_task url] absoluteString], [elt UID]]];
  resource = [[WebDAVResource alloc] initWithURL:url authFromURL:_url];
  tree = [iCalTree new];
  if ([tree add:elt]) {
    [resource put:[tree iCalTreeAsData] attributes:[NSDictionary dictionaryWithObjectsAndKeys:@"text/calendar; charset=utf-8", @"Content-Type", @"*", @"If-None-Match", nil, nil]];
    if ([resource httpStatus] > 199 && [resource httpStatus] < 300)
      /* FIXME : this is extremely slow. We should only load attributes and fetch new or modified elements */
      /* Reloading all data is a way to handle href and uid modification done by the server */
      [self doRead];
    else
      NSLog(@"Error %d writing event to %@", [resource httpStatus], [url anonymousAbsoluteString]);
  }
  [tree release];
  [resource release];
}

- (void)remove:(Element *)elt
{
  NSURL *href = [_uidhref objectForKey:[elt UID]];
  WebDAVResource *resource = [_hrefresource objectForKey:href];

  [resource delete];
  if ([resource httpStatus] == 412) {
    /* FIXME : force a visual refresh ? */
    [resource updateAttributes];
    NSLog(@"Couldn't delete item, it has changed on the server");
  } else {
    [_hrefresource removeObjectForKey:href];
    [_uidhref removeObjectForKey:[elt UID]];
    [super remove:elt];
  }
}

/* FIXME : update the iCal tree iif data was written succesfully */
- (void)update:(Element *)elt
{
  NSString *href = [_uidhref objectForKey:[elt UID]];
  iCalTree *tree = [_hreftree objectForKey:href];

  if ([tree update:(Event *)elt]) {
    [super update:elt];
    [_modifiedhref addObject:href];
    [self write];
  }
}

- (void)read
{
  if ([self enabled])
    [[[StoreManager globalManager] operationQueue] addOperation:[[[InvocationOperation alloc] initWithTarget:self 
												    selector:@selector(doRead) 
												      object:nil] autorelease]];
}

- (void)write
{
  if (![self enabled] || ![self writable])
    return;
  [[[StoreManager globalManager] operationQueue] addOperation:[[[InvocationOperation alloc] initWithTarget:self 
												  selector:@selector(doWrite)
												    object:nil] autorelease]];
}

- (void)configChanged:(NSNotification *)not
{
  NSString *key = [[not userInfo] objectForKey:@"key"];
  if ([key isEqualToString:ST_ENABLED]) {
    if ([self enabled])
      [self read];
  }
}
@end


@implementation GroupDAVStore(Private)
static NSString * const PROPFINDGETETAG = @"<?xml version=\"1.0\" encoding=\"utf-8\"?><propfind xmlns=\"DAV:\"><prop><getetag/></prop></propfind>";
static NSString * const EXPRGETHREF = @"//response[propstat/prop/getetag]/href/text()";
- (NSArray *)itemsUnderRessource:(WebDAVResource *)ressource
{
  int i;
  GSXMLParser *parser;
  NSMutableArray *result;
  GSXPathContext *xpc;
  GSXPathNodeSet *set;
  NSURL *elementURL;

  if (![ressource propfind:[PROPFINDGETETAG dataUsingEncoding:NSUTF8StringEncoding] 
		attributes:[NSDictionary dictionaryWithObject:@"1" forKey:@"Depth"]])
    return nil;
  result = [NSMutableArray arrayWithCapacity:256];
  parser = [GSXMLParser parserWithData:[ressource data]];
  if ([parser parse]) {
    xpc = [[GSXPathContext alloc] initWithDocument:[[parser document] strippedDocument]];
    set = (GSXPathNodeSet *)[xpc evaluateExpression:EXPRGETHREF];
    for (i = 0; i < [set count]; i++) {
      elementURL = [NSURL URLWithString:[[set nodeAtIndex:i] content] possiblyRelativeToURL:[ressource url]];
      if (elementURL)
	[result addObject:elementURL];
    }
    RELEASE(xpc);
  }
  return result;
}

- (void)add:(NSArray *)items toSet:(NSMutableSet *)loadedData
{
  WebDAVResource *element;
  iCalTree *tree;
  NSEnumerator *enumerator;
  NSURL *href;
  NSSet *components;

  enumerator = [items objectEnumerator];
  while ((href = [enumerator nextObject])) {
    element = [[WebDAVResource alloc] initWithURL:href authFromURL:_url];
    tree = [iCalTree new];
    if ([element get] && [tree parseData:[element data]]) {
      components = [tree components];
      if ([components count] > 0) {
	[loadedData unionSet:components];
	[_hreftree setObject:tree forKey:href];
	[_hrefresource setObject:element forKey:href];
	[_uidhref setObject:href forKey:[[components anyObject] UID]];
      }
    }
    [tree release];
    [element release];
  }
}
- (void)doRead
{
  NSMutableSet *loadedData = [[NSMutableSet alloc] initWithCapacity:512];
  BOOL error = NO;
  NSArray *items;

  if (_calendar) {
    items = [self itemsUnderRessource:_calendar];
    if (items)
      [self add:items toSet:loadedData];
    else
      error = YES;
  }
  if (_task && !error) {
    items = [self itemsUnderRessource:_task];
    if (items)
      [self add:items toSet:loadedData];
    else
      error = YES;
  }
  if (error) {
    NSLog(@"Error while reading %@", [self description]);
    [[NSNotificationCenter defaultCenter] postNotificationName:SAErrorReadingStore 
							object:self
						      userInfo:[NSDictionary dictionary]];
  } else {
    [self performSelectorOnMainThread:@selector(fillWithElements:) withObject:loadedData waitUntilDone:YES];
    NSLog(@"GroupDAVStore from %@ : loaded %d appointment(s)", [_url anonymousAbsoluteString], [[self events] count]);
    NSLog(@"GroupDAVStore from %@ : loaded %d tasks(s)", [_url anonymousAbsoluteString], [[self tasks] count]);
  }
  [loadedData release];
}

- (void)doWrite
{
  NSDictionary *attr = [NSDictionary dictionaryWithObject:@"text/calendar; charset=utf-8" forKey:@"Content-Type"];
  NSEnumerator *enumerator;
  WebDAVResource *element;
  iCalTree *tree;
  NSURL *href;
  NSArray *copy;
  BOOL error = NO;

  copy = [_modifiedhref copy];
  enumerator = [copy objectEnumerator];
  while ((href = [enumerator nextObject])) {
    element = [_hrefresource objectForKey:href];
    tree = [_hreftree objectForKey:href];
    if ([element put:[tree iCalTreeAsData] attributes:attr]) {
      /* Read it back to update the attributes */ 
      /* FIXME : RFC says we should update the list instead */
      [element updateAttributes];
      [_modifiedhref removeObject:href];
      NSLog(@"Written %@", [href anonymousAbsoluteString]);
    } else {
      NSLog(@"Unable to write to %@", [href anonymousAbsoluteString]);
      error = YES;
    }
  }
  if (error) {
    NSLog(@"Calendar %@ will be made read only and data reread", [self description]);
    [[NSNotificationCenter defaultCenter] postNotificationName:SAErrorWritingStore 
							object:self
						      userInfo:[NSDictionary dictionary]];
  }
  [copy release];
}
@end