/
SettingsSiteViewController.m
414 lines (364 loc) · 18.1 KB
/
SettingsSiteViewController.m
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
//
// SettingsSite.m
// Moodle
//
// Created by Jerome Mouneyrac on 21/03/11.
// Copyright 2011 Moodle. All rights reserved.
//
#import "SettingsSiteViewController.h"
#import "WSClient.h"
#import "Constants.h"
#import "XMLRPCRequest.h"
#import "NSDataAdditions.h"
#import "ASIFormDataRequest.h"
#import "CJSONDeserializer.h"
@implementation SettingsSiteViewController
# pragma mark - private method
- (UITextField *)_createCellTextField {
UITextField *field = [[UITextField alloc] initWithFrame:CGRectZero];
[field setAdjustsFontSizeToFitWidth:YES];
[field setTextColor:[UIColor blackColor]];
[field setDelegate:self];
[field setBackgroundColor:[UIColor clearColor]];
[field setAutocorrectionType:UITextAutocorrectionTypeNo];
[field setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[field setTextAlignment:UITextAlignmentLeft];
[field setEnabled:YES];
[field setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
return [field autorelease];
}
# pragma mark - Button actions
-(IBAction)cancel: (id)sender{
[self.navigationController popViewControllerAnimated:YES];
}
-(void)deleteSite {
UIActionSheet *deleteActionSheet = [[UIActionSheet alloc]
initWithTitle:NSLocalizedString(@"deletesite", "Delete the site")
delegate:self
cancelButtonTitle: NSLocalizedString(@"donotdeletesite", "Do not delete the site")
destructiveButtonTitle: NSLocalizedString(@"dodeletesite", "Do delete the site")
otherButtonTitles:nil];
[deleteActionSheet showInView: self.view];
[deleteActionSheet release];
}
# pragma mark - action sheet delegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
//there is only one action sheet on this view, so we can check the buttonIndex against the cancel button
if (buttonIndex != [actionSheet cancelButtonIndex]) {
//delete the entry
[appDelegate.managedObjectContext deleteObject: appDelegate.site];
NSError *error;
if (![appDelegate.managedObjectContext save:&error]) {
NSLog(@"Failed to save to data store: %@", [error localizedDescription]);
NSArray *detailedErrors = [[error userInfo] objectForKey: NSDetailedErrorsKey];
if(detailedErrors != nil && [detailedErrors count] > 0) {
for(NSError* detailedError in detailedErrors) {
NSLog(@"Detailed Error: %@", [detailedError userInfo]);
}
} else {
NSLog(@" %@", [error userInfo]);
}
}
// send notification to appdelete to reset site
[[NSNotificationCenter defaultCenter] postNotificationName: kResetSite
object: nil];
//return the list of sites
NSArray *allControllers = self.navigationController.viewControllers;
UITableViewController *parent = [allControllers lastObject];
[parent.tableView reloadData];
[self.navigationController popViewControllerAnimated:YES];
}
}
- (BOOL) validateUrl: (NSString *) candidate {
NSString *urlRegEx = @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
return [urlTest evaluateWithObject:candidate];
}
- (IBAction)saveButtonPressed: (id)sender
{
NSManagedObjectContext *context = appDelegate.managedObjectContext;
NSString *siteurl;
siteurl = [siteurlField text];
if (![self validateUrl:siteurl]) {
siteurl = [NSString stringWithFormat: @"http://%@", siteurl];
}
if ([siteurl hasSuffix:@"/"]) {
siteurl = [siteurl substringToIndex:[siteurl length] - 1];
}
NSString *username = [usernameField text];
NSString *password = [passwordField text];
NSString *tokenURL = [NSString stringWithFormat:@"%@/login/token.php", siteurl];
NSURL *url = [NSURL URLWithString: tokenURL];
NSLog(@"%@", tokenURL);
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue: username forKey: @"username"];
[request setPostValue: password forKey: @"password"];
[request setPostValue: @"moodle_mobile_app" forKey: @"service"];
[request setCompletionBlock: ^{
NSLog(@"Token info: %@", [request responseString]);
NSDictionary *token = [[CJSONDeserializer deserializer] deserializeAsDictionary: [request responseData] error: nil];
NSLog(@"Token: %@", token);
NSString *sitetoken = [token valueForKey: @"token"];
@try {
//retrieve the site name
WSClient *client = [[WSClient alloc] initWithToken: sitetoken withHost: siteurl];
NSArray *wsparams = [[NSArray alloc] initWithObjects:nil];
NSDictionary *siteinfo = [client invoke: @"moodle_webservice_get_siteinfo" withParams: wsparams];
[wsparams release];
[client release];
if ([siteinfo isKindOfClass: [NSDictionary class]]) {
//check if the site url + userid is already in data core otherwise create a new site
NSError *error;
NSFetchRequest *siteRequest = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *siteEntity = [NSEntityDescription entityForName:@"Site" inManagedObjectContext:context];
[siteRequest setEntity: siteEntity];
NSPredicate *sitePredicate = [NSPredicate predicateWithFormat:@"(url = %@ AND mainuser.userid = %@)", siteurl, [siteinfo objectForKey:@"userid"]];
[siteRequest setPredicate:sitePredicate];
NSArray *sites = [context executeFetchRequest:siteRequest error:&error];
NSLog(@"Sites info %@", sites);
if ([sites count] > 0) {
appDelegate.site = [sites lastObject];
} else {
appDelegate.site = [NSEntityDescription insertNewObjectForEntityForName: [siteEntity name] inManagedObjectContext:context];
}
// profile pictre
NSString *userpictureurl = [siteinfo objectForKey: @"userpictureurl"];
NSString *sitename = [siteinfo objectForKey: @"sitename"];
//create/update the site
[appDelegate.site setValue: sitename forKey: @"name"];
[appDelegate.site setValue: userpictureurl forKey: @"userpictureurl"];
[appDelegate.site setValue: sitetoken forKey: @"token"];
[appDelegate.site setValue: siteurl forKey: @"url"];
NSManagedObject *user;
NSManagedObject *webservice;
NSArray *webservices = [siteinfo objectForKey:@"functions"];
//retrieve participant main user
if (newEntry) {
NSEntityDescription *mainUserDesc = [NSEntityDescription entityForName:@"MainUser" inManagedObjectContext:context];
user = [NSEntityDescription insertNewObjectForEntityForName: [mainUserDesc name]
inManagedObjectContext: context];
} else {
user = [appDelegate.site valueForKey:@"mainuser"];
// delete old records
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName: @"WebService" inManagedObjectContext: context];
[request setEntity: entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(site = %@)", appDelegate.site];
[request setPredicate: predicate];
NSArray *objects = [context executeFetchRequest: request error: nil];
for (NSManagedObject *info in objects) {
[context deleteObject: info];
}
[request release];
}
NSEntityDescription *wsDesc = [NSEntityDescription entityForName:@"WebService" inManagedObjectContext:context];
for (NSDictionary *ws in webservices) {
webservice = [NSEntityDescription insertNewObjectForEntityForName: [wsDesc name] inManagedObjectContext:context];
[webservice setValue:[ws valueForKey:@"name"] forKey:@"name"];
[webservice setValue:appDelegate.site forKey:@"site"];
int version = [[ws valueForKey:@"version"] intValue];
[webservice setValue: [NSNumber numberWithInt: version] forKey:@"version"];
}
[user setValue: [siteinfo objectForKey:@"userid"] forKey:@"userid"];
[user setValue: [siteinfo objectForKey:@"username"] forKey:@"username"];
[user setValue: [siteinfo objectForKey:@"firstname"] forKey:@"firstname"];
[user setValue: [siteinfo objectForKey:@"fullname"] forKey:@"fullname"];
[user setValue: [siteinfo objectForKey:@"lastname"] forKey:@"lastname"];
[user setValue: appDelegate.site forKey:@"site"];
[appDelegate.site setValue: user forKey: @"mainuser"];
// update active site info
sites = [context executeFetchRequest:siteRequest error:&error];
if ([sites count] > 0) {
appDelegate.site = [sites lastObject];
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//save the current site into user preference
[defaults setObject:[appDelegate.site valueForKey:@"url"] forKey:kSelectedSiteUrlKey];
[defaults setObject:[appDelegate.site valueForKey:@"name"] forKey:kSelectedSiteNameKey];
[defaults setObject:[appDelegate.site valueForKey:@"token"] forKey:kSelectedSiteTokenKey];
[defaults setObject:[appDelegate.site valueForKeyPath:@"mainuser.userid"] forKey:kSelectedUserIdKey];
[defaults synchronize];
//save the modification
if (![context save: &error]) {
NSLog(@"Failed to save to data store: %@", [error localizedDescription]);
NSArray *detailedErrors = [[error userInfo] objectForKey: NSDetailedErrorsKey];
if(detailedErrors != nil && [detailedErrors count] > 0) {
for(NSError* detailedError in detailedErrors) {
NSLog(@"Detailed Error: %@", [detailedError userInfo]);
}
} else {
NSLog(@" %@", [error userInfo]);
}
}
[self.navigationController popToRootViewControllerAnimated:YES];
}
}
@catch (NSException *exception) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[exception name] message:[exception reason] delegate:self cancelButtonTitle:@"Continue" otherButtonTitles: nil];
[alert show];
[alert release];
}
}];
[request startAsynchronous];
}
-(IBAction)textFieldDone:(id)sender {
UITableViewCell *cell = (UITableViewCell *)[[sender superview] superview];
UITableView *table = (UITableView *)[cell superview];
NSIndexPath *textFieldIndexPath = [table indexPathForCell:cell];
NSUInteger row = [textFieldIndexPath row];
row++;
if (row >= kNumberOfEditableRows) {
row = 0;
}
NSUInteger newIndex[] = {0, row};
NSIndexPath *newPath = [[NSIndexPath alloc] initWithIndexes:newIndex length:2];
UITableViewCell *nextCell = [self.tableView cellForRowAtIndexPath:newPath];
UITextField *nextField = nil;
for (UIView *oneView in nextCell.contentView.subviews) {
if ([oneView isMemberOfClass:[UITextField class]]) {
nextField = (UITextField *)oneView;
}
}
[newPath release];
[nextField becomeFirstResponder];
}
#pragma mark - View lifecycle
- (id)initWithNew: (NSString *)new {
if ((self = [self initWithStyle:UITableViewStyleGrouped])) {
}
if ([new isEqualToString:@"no"]) {
newEntry = NO;
} else {
newEntry = YES;
}
return self;
}
- (void)loadView {
[super loadView];
}
- (void)dealloc {
[super dealloc];
}
- (void)viewWillAppear:(BOOL)animated {
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[[self navigationController] setNavigationBarHidden:NO animated:NO];
[super viewWillAppear:animated];
self.navigationController.view.backgroundColor = UIColorFromRGB(LoginBackground);
self.tableView.backgroundColor = [UIColor clearColor];
siteurlCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
[[siteurlCell textLabel] setText: @"Site URL"];
siteurlField = [self _createCellTextField];
siteurlField.frame = CGRectMake(115, 12, siteurlCell.bounds.size.width - 125, 30);
[siteurlField setReturnKeyType:UIReturnKeyNext];
[siteurlCell addSubview:siteurlField];
if (!newEntry) {
siteurlField.text = [appDelegate.site valueForKey:@"url"];
} else {
siteurlField.text = @"http://dongsheng.moodle.local/moodle";
}
usernameCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
[[usernameCell textLabel] setText:@"Username"];
usernameField = [self _createCellTextField];
usernameField.frame = CGRectMake(115, 12, usernameCell.bounds.size.width - 125, 30);
[usernameField setReturnKeyType:UIReturnKeyNext];
[usernameCell addSubview:usernameField];
if (!newEntry) {
usernameField.text = [appDelegate.site valueForKeyPath:@"mainuser.username"];
} else {
usernameField.text = @"teacher";
}
passwordCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
[[passwordCell textLabel] setText:@"Password"];
passwordField = [self _createCellTextField];
passwordField.frame = CGRectMake(115, 12, passwordCell.bounds.size.width - 125, 30);
[passwordField setSecureTextEntry:YES];
[passwordField setReturnKeyType:UIReturnKeyDone];
[passwordCell addSubview:passwordField];
if (!newEntry) {
passwordField.text = @"******";
} else {
passwordField.text = @"cds";
}
topLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [self.view bounds].size.width, 40.0f)];
[topLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin];
[topLabel setTextAlignment:UITextAlignmentCenter];
[topLabel setBackgroundColor:[UIColor clearColor]];
[topLabel setShadowColor:[UIColor blackColor]];
[topLabel setShadowOffset:CGSizeMake(0, 1.0f)];
[topLabel setFont:[UIFont boldSystemFontOfSize:30.0f]];
[topLabel setTextColor: [UIColor whiteColor]];
[topLabel setText:@"Moodle"];
if (!newEntry) {
int buttonWidth = 300;
int buttonHeight = 45;
UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, buttonWidth, buttonHeight)];
UIButton *btnDelete = [UIButton buttonWithType:UIButtonTypeCustom];
[btnDelete setBackgroundImage:[UIImage imageNamed:@"button_red.png"] forState:UIControlStateNormal];
[btnDelete setTitle: NSLocalizedString(@"delete", "delete") forState:UIControlStateNormal];
[btnDelete setFrame:CGRectMake(0, 0, buttonWidth, buttonHeight)];
[btnDelete.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
[btnDelete addTarget:self action:@selector(deleteSite) forControlEvents:UIControlEventTouchUpInside];
[buttonView addSubview:btnDelete];
self.tableView.tableFooterView = buttonView;
}
}
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]
initWithTitle:NSLocalizedString(@"cancel", nil)
style:UIBarButtonItemStylePlain
target:self
action:@selector(cancel:)];
self.navigationItem.leftBarButtonItem = cancelButton;
[cancelButton release];
UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
initWithTitle: NSLocalizedString(@"save", nil)
style:UIBarButtonItemStyleDone
target:self
action:@selector(saveButtonPressed:)];
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];
if (!newEntry) {
// case of Updating a site
self.title = NSLocalizedString(@"updatesite", nil);
} else {
//case of Adding a new site
self.title = NSLocalizedString(@"addsite", nil);
}
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return kNumberOfEditableRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([indexPath row] == 0) {
return siteurlCell;
} else if ([indexPath row] == 1) {
return usernameCell;
} else if ([indexPath row] == 2) {
return passwordCell;
} else {
return nil;
}
}
#pragma mark -
#pragma mark Table Delegate Methods
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if (section == 0) {
return 65.0f;
} else {
return 0.0f;
}
}
- (UIView *)tableView:(UITableView *)table viewForHeaderInSection:(NSInteger)section {
if (section == 0) {
return topLabel;
} else {
return nil;
}
}
@end