summaryrefslogtreecommitdiffstats
path: root/remoting/ios/data_store.mm
blob: 1cfbc3f9ac2bb85d571e835ebc6932cbb77f4ebf (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
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif

#import "remoting/ios/data_store.h"

@interface DataStore (Private)
- (NSString*)itemArchivePath;
@end

@implementation DataStore {
 @private
  NSMutableArray* _allHosts;
  NSManagedObjectContext* _context;
  NSManagedObjectModel* _model;
}

// Create or Get a static data store
+ (DataStore*)sharedStore {
  static DataStore* sharedStore = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken,
                ^{ sharedStore = [[super allocWithZone:nil] init]; });

  return sharedStore;
}

// General methods
+ (id)allocWithZone:(NSZone*)zone {
  return [self sharedStore];
}

// Load data store from SQLLite backing store
- (id)init {
  self = [super init];

  if (self) {
    // Read in ChromotingModel.xdatamodeld
    _model = [NSManagedObjectModel mergedModelFromBundles:nil];

    NSPersistentStoreCoordinator* psc = [[NSPersistentStoreCoordinator alloc]
        initWithManagedObjectModel:_model];

    NSString* path = [self itemArchivePath];
    NSURL* storeUrl = [NSURL fileURLWithPath:path];

    NSError* error = nil;

    NSDictionary* tryOptions = @{
      NSMigratePersistentStoresAutomaticallyOption : @YES,
      NSInferMappingModelAutomaticallyOption : @YES
    };
    NSDictionary* makeOptions =
        @{NSMigratePersistentStoresAutomaticallyOption : @YES};

    if (![psc addPersistentStoreWithType:NSSQLiteStoreType
                           configuration:nil
                                     URL:storeUrl
                                 options:tryOptions
                                   error:&error]) {
      // An incompatible version of the store exists, delete it and start over
      [[NSFileManager defaultManager] removeItemAtURL:storeUrl error:nil];

      [psc addPersistentStoreWithType:NSSQLiteStoreType
                        configuration:nil
                                  URL:storeUrl
                              options:makeOptions
                                error:&error];
      [NSException raise:@"Open failed"
                  format:@"Reason: %@", [error localizedDescription]];
    }

    // Create the managed object context
    _context = [[NSManagedObjectContext alloc] init];
    [_context setPersistentStoreCoordinator:psc];

    // The managed object context can manage undo, but we don't need it
    [_context setUndoManager:nil];

    _allHosts = nil;
  }
  return self;
}

// Committing to backing store
- (BOOL)saveChanges {
  NSError* err = nil;
  BOOL successful = [_context save:&err];
  return successful;
}

// Looking up the backing store path
- (NSString*)itemArchivePath {
  NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(
      NSDocumentDirectory, NSUserDomainMask, YES);

  // Get one and only document directory from that list
  NSString* documentDirectory = [documentDirectories objectAtIndex:0];

  return [documentDirectory stringByAppendingPathComponent:@"store.data"];
}

// Return an array of all known hosts, if the list hasn't been loaded yet, then
// load it now
- (NSArray*)allHosts {
  if (!_allHosts) {
    NSFetchRequest* request = [[NSFetchRequest alloc] init];

    NSEntityDescription* e =
        [[_model entitiesByName] objectForKey:@"HostPreferences"];

    [request setEntity:e];

    NSError* error;
    NSArray* result = [_context executeFetchRequest:request error:&error];
    if (!result) {
      [NSException raise:@"Fetch failed"
                  format:@"Reason: %@", [error localizedDescription]];
    }
    _allHosts = [result mutableCopy];
  }

  return _allHosts;
}

// Return a HostPreferences if it already exists, otherwise create a new
// HostPreferences to use
- (const HostPreferences*)createHost:(NSString*)hostId {

  const HostPreferences* p = [self getHostForId:hostId];

  if (p == nil) {
    p = [NSEntityDescription insertNewObjectForEntityForName:@"HostPreferences"
                                      inManagedObjectContext:_context];
    p.hostId = hostId;
    [_allHosts addObject:p];
  }
  return p;
}

- (void)removeHost:(HostPreferences*)p {
  [_context deleteObject:p];
  [_allHosts removeObjectIdenticalTo:p];
}

// Search the store for any matching HostPreferences
// return the 1st match or nil
- (const HostPreferences*)getHostForId:(NSString*)hostId {
  NSFetchRequest* request = [[NSFetchRequest alloc] init];

  NSEntityDescription* e =
      [[_model entitiesByName] objectForKey:@"HostPreferences"];
  [request setEntity:e];

  NSPredicate* predicate =
      [NSPredicate predicateWithFormat:@"(hostId = %@)", hostId];
  [request setPredicate:predicate];

  NSError* error;
  NSArray* result = [_context executeFetchRequest:request error:&error];
  if (!result) {
    [NSException raise:@"Fetch failed"
                format:@"Reason: %@", [error localizedDescription]];
  }

  for (HostPreferences* curHost in result) {
    return curHost;
  }
  return nil;
}

@end