This repository has been archived by the owner on Dec 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Connection.cs
471 lines (433 loc) · 21.7 KB
/
Connection.cs
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Cloudsdale.Controls;
using Cloudsdale.Managers;
using Cloudsdale.Models;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Wp7Faye;
namespace Cloudsdale {
/// <summary>
/// Static class to aid in the static connection data that should be maintained for all things done with respect to the server
/// </summary>
public static class Connection {
public static Cloud CurrentCloud;
public static string FacebookUid;
public static int LoginType;
public static LoginResponse LoginResult;
public static string CloudsdaleClientId;
public static LoggedInUser CurrentCloudsdaleUser;
public static bool TransProxWorkaround;
public static readonly LoginState LoginState = new LoginState();
public static Uri LaunchedUri = null;
public static MessageHandler Faye;
public static void Connect(Page page = null, Dispatcher dispatcher = null, bool pulluserclouds = false) {
LoginState.Message = "Logging in...";
switch (LoginType) {
case 0:
break;
case 1:
// Should never be hit, but just in case
if (page == null) {
// ReSharper disable PossibleNullReferenceException
Deployment.Current.Dispatcher.BeginInvoke(
() => (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(
new Uri("/MainPage.xaml", UriKind.Relative)));
// ReSharper restore PossibleNullReferenceException
}
FacebookAuth.FBOANegotiator.FacebookLogin(page);
return;
default:
return;
}
if (pulluserclouds) {
PullUserClouds(() => FinishLogin(page, dispatcher));
} else {
SaveUser();
FinishConnecting(page, dispatcher);
}
}
public static void FinishLogin(Page page, Dispatcher dispatcher) {
if ((CurrentCloudsdaleUser.needs_name_change ?? false)
|| string.IsNullOrWhiteSpace(CurrentCloudsdaleUser.name)) {
Deployment.Current.Dispatcher.BeginInvoke(() => {
var settings = IsolatedStorageSettings.ApplicationSettings;
settings.Remove("lastuser");
settings.Save();
MainPage.reconstruction = true;
((PhoneApplicationFrame)Application.Current.RootVisual)
.Navigate(new Uri("/Account/SetName.xaml", UriKind.Relative));
});
return;
}
if (CurrentCloudsdaleUser.needs_password_change ?? false) {
Deployment.Current.Dispatcher.BeginInvoke(() => {
var settings = IsolatedStorageSettings.ApplicationSettings;
settings.Remove("lastuser");
settings.Save();
MainPage.reconstruction = true;
((PhoneApplicationFrame)Application.Current.RootVisual)
.Navigate(new Uri("/Account/SetPassword.xaml", UriKind.Relative));
});
return;
}
if (CurrentCloudsdaleUser.needs_email_change ?? false) {
Deployment.Current.Dispatcher.BeginInvoke(() => {
var settings = IsolatedStorageSettings.ApplicationSettings;
settings.Remove("lastuser");
settings.Save();
MainPage.reconstruction = true;
((PhoneApplicationFrame)Application.Current.RootVisual)
.Navigate(new Uri("/Account/SetEmail.xaml", UriKind.Relative));
});
return;
}
if (!(CurrentCloudsdaleUser.has_read_tnc ?? false)) {
Deployment.Current.Dispatcher.BeginInvoke(() => {
var settings = IsolatedStorageSettings.ApplicationSettings;
settings.Remove("lastuser");
settings.Save();
MainPage.reconstruction = true;
((PhoneApplicationFrame)Application.Current.RootVisual)
.Navigate(new Uri("/Account/TermsAndConditions.xaml", UriKind.Relative));
});
return;
}
if ((CurrentCloudsdaleUser.suspended_until ?? new DateTime(0)) > DateTime.Now) {
Deployment.Current.Dispatcher.BeginInvoke(() => {
MessageBox.Show("You are banned until" + CurrentCloudsdaleUser.suspended_until +
"\n" + CurrentCloudsdaleUser.reason_for_suspension);
Deployment.Current.Dispatcher.BeginInvoke(() => {
var settings = IsolatedStorageSettings.ApplicationSettings;
settings.Remove("lastuser");
settings.Save();
MainPage.reconstruction = true;
((PhoneApplicationFrame)Application.Current.RootVisual)
.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
});
});
return;
}
CurrentCloudsdaleUser.PropertyChanged += (sender, args) => {
if (args.PropertyName != "bans")
return;
foreach (var diff in BanDifferentiation.DifferentiateBans
(CurrentCloudsdaleUser.old_bans, CurrentCloudsdaleUser.bans)) {
if (diff.isnew && diff.active == true) {
MessageBox.Show("You have been banned from " +
PonyvilleDirectory.GetCloud(diff.cloud).name +
" for \"" + diff.reason + "\" until " + diff.due,
"Banned!", MessageBoxButton.OK);
if (CurrentCloud.id == diff.cloud) {
while (((TransitionFrame)Application.Current.RootVisual).CanGoBack) {
((TransitionFrame)Application.Current.RootVisual).GoBack();
}
}
} else if ((diff.due != null && diff.due < DateTime.Now) ||
(diff.active == false || diff.revoked == true)) {
MessageBox.Show("You are no longer banned from " +
PonyvilleDirectory.GetCloud(diff.cloud).name +
"!", "No longer banned!", MessageBoxButton.OK);
}
}
};
FinishConnecting(page, dispatcher);
}
public static void FinishConnecting(Page page = null, Dispatcher dispatcher = null, bool wss = false) {
PonyvilleAccounting.AddUser(CurrentCloudsdaleUser);
wss |= SettingBoundToggle.IsSet("connection.always_ssl");
LoginState.Message = "Connecting...";
if (wss) {
Faye = Wp7Faye.Faye.Connect(Resources.pushUrlSSL);
} else {
Faye = Wp7Faye.Faye.Connect(Resources.pushUrl);
Faye.Timeout = 10 * 1000;
Faye.ConnectTimeout += () => FinishConnecting(page, dispatcher, true);
}
Faye.MessageExt = JObject.FromObject(new { CurrentCloudsdaleUser.auth_token });
Faye.HandshakeResponse += response => {
CurrentCloudsdaleUser.clouds = (from cloud in CurrentCloudsdaleUser.clouds
select PonyvilleDirectory.RegisterCloud(cloud)).ToArray();
DerpyHoovesMailCenter.Init();
if (dispatcher == null)
foreach (var cloud in CurrentCloudsdaleUser.clouds) {
DerpyHoovesMailCenter.Subscribe(cloud);
}
if (page == null) {
if (dispatcher != null) {
dispatcher.BeginInvoke(() => {
var phoneApplicationFrame = Application.Current.RootVisual as PhoneApplicationFrame;
if (phoneApplicationFrame != null) {
phoneApplicationFrame.Navigate(new Uri("/Home.xaml", UriKind.Relative));
LoginState.Message = "Loading home...";
}
});
}
} else {
page.Dispatcher.BeginInvoke(
() => {
page.NavigationService.Navigate(new Uri("/Home.xaml", UriKind.Relative));
LoginState.Message = "Loading home...";
});
}
};
Faye.Connect();
}
public static void PullUserClouds(Action complete) {
var token = BCrypt.Net.BCrypt.HashPassword(CurrentCloudsdaleUser.id + "cloudsdale", Resources.InternalToken);
var oauth = string.Format(Resources.OAuthFormat, "cloudsdale", token, CurrentCloudsdaleUser.id);
var data = Encoding.UTF8.GetBytes(oauth);
var request = WebRequest.CreateHttp(Resources.loginUrl);
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/json";
request.Headers["Content-Length"] = data.Length.ToString();
request.BeginGetRequestStream(ar => {
using (var stream = request.EndGetRequestStream(ar)) {
stream.Write(data, 0, data.Length);
stream.Close();
}
request.BeginGetResponse(ac => {
try {
string json;
using (var response = request.EndGetResponse(ac))
using (var responseStream = response.GetResponseStream())
using (var responseReader = new StreamReader(responseStream)) {
json = responseReader.ReadToEnd();
}
LoginType = 0;
var settings = new JsonSerializerSettings {
DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
Error = (sender, args) => {
if (args.ErrorContext.OriginalObject is Ban) {
var property = args.ErrorContext.OriginalObject.GetType().GetField((string)args.ErrorContext.Member);
if (property.FieldType == typeof(DateTime?)) {
property.SetValue(args.ErrorContext.OriginalObject, (DateTime?)DateTime.Now.AddDays(2));
args.ErrorContext.Handled = true;
return;
}
}
Deployment.Current.Dispatcher.BeginInvoke(() => {
MessageBox.Show("Error receiving data from the server");
var isettings = IsolatedStorageSettings.ApplicationSettings;
isettings.Remove("lastuser");
isettings.Save();
MainPage.reconstruction = true;
((PhoneApplicationFrame)Application.Current.RootVisual).Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
});
}
};
LoginResult = JsonConvert.DeserializeObject<LoginResponse>(json, settings);
CloudsdaleClientId = LoginResult.result.client_id;
CurrentCloudsdaleUser = LoginResult.result.user;
SaveUser();
complete();
} catch {
Deployment.Current.Dispatcher.BeginInvoke(() => {
if (MessageBox.Show("An error occured logging in. Retry?", "",
MessageBoxButton.OKCancel) == MessageBoxResult.OK) {
PullUserClouds(complete);
return;
}
var settings = IsolatedStorageSettings.ApplicationSettings;
settings.Remove("lastuser");
settings.Save();
MainPage.reconstruction = true;
((PhoneApplicationFrame)Application.Current.RootVisual)
.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
});
}
}, null);
}, null);
}
public static void SendMessage(string cloud, string message, Action<JObject> callback) {
var dataObject = new JObject();
dataObject["content"] = message;
dataObject["client_id"] = Faye.ClientID;
dataObject["device"] = "mobile";
var data = Encoding.UTF8.GetBytes(dataObject.ToString());
var request = WebRequest.CreateHttp(Resources.SendEndpoint.Replace("{cloudid}", cloud));
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/json";
request.Headers["Content-Length"] = data.Length.ToString(CultureInfo.InvariantCulture);
request.Headers["X-Auth-Token"] = CurrentCloudsdaleUser.auth_token;
request.BeginGetRequestStream(ar => {
var reqs = request.EndGetRequestStream(ar);
reqs.Write(data, 0, data.Length);
reqs.Close();
request.BeginGetResponse(a => {
string responseData;
using (var response = request.EndGetResponse(a))
using (var responseStream = response.GetResponseStream())
using (var responseReader = new StreamReader(responseStream, Encoding.UTF8)) {
responseData = responseReader.ReadToEnd();
}
if (callback != null)
callback(JObject.Parse(responseData));
}, null);
}, null);
}
public static void JoinCloud(string id) {
var jObj = new JObject();
var dataString = jObj.ToString();
var data = Encoding.UTF8.GetBytes(dataString);
var request = WebRequest.CreateHttp(Resources.JoinCloudEndpoint.
Replace("{cloudid}", id).
Replace("{userid}", CurrentCloudsdaleUser.id));
request.Accept = "application/json";
request.Method = "PUT";
request.ContentType = "application/json";
request.Headers["Content-Length"] = data.Length.ToString();
request.Headers["X-Auth-Token"] = CurrentCloudsdaleUser.auth_token;
request.BeginGetRequestStream(ar => {
var requestStream = request.EndGetRequestStream(ar);
requestStream.Write(data, 0, data.Length);
requestStream.Close();
request.BeginGetResponse(a => {
try {
var response = request.EndGetResponse(a);
string message;
using (var responseStream = response.GetResponseStream())
using (var streamReader = new StreamReader(responseStream)) {
message = streamReader.ReadToEnd();
}
var user = JsonConvert.DeserializeObject<WebResponse<LoggedInUser>>(message).result;
user.CopyTo(CurrentCloudsdaleUser);
} catch (WebException ex) {
#if DEBUG
Debugger.Break();
#endif
}
}, null);
}, null);
}
public static void LeaveCloud(string id) {
Faye.Unsubscribe("/clouds/" + id + "/chat/messages");
Faye.Unsubscribe("/clouds/" + id + "/users/**");
var jObj = new JObject();
var dataString = jObj.ToString();
var data = Encoding.UTF8.GetBytes(dataString);
var request = WebRequest.CreateHttp(Resources.LeaveCloudEndpoint.
Replace("{cloudid}", id).
Replace("{userid}", CurrentCloudsdaleUser.id));
request.Accept = "application/json";
request.Method = "DELETE";
request.ContentType = "application/json";
request.Headers["Content-Length"] = data.Length.ToString();
request.Headers["X-Auth-Token"] = CurrentCloudsdaleUser.auth_token;
request.BeginGetRequestStream(ar => {
var requestStream = request.EndGetRequestStream(ar);
requestStream.Write(data, 0, data.Length);
requestStream.Close();
request.BeginGetResponse(a => {
try {
var response = request.EndGetResponse(a);
string message;
using (var responseStream = response.GetResponseStream())
using (var streamReader = new StreamReader(responseStream)) {
message = streamReader.ReadToEnd();
}
var user = JsonConvert.DeserializeObject<WebResponse<LoggedInUser>>(message).result;
user.CopyTo(CurrentCloudsdaleUser);
} catch (WebException ex) {
#if DEBUG
Debugger.Break();
#endif
}
}, null);
}, null);
}
public static void SaveUser() {
var serial = JsonConvert.SerializeObject(new SavedUser { id = CloudsdaleClientId, user = CurrentCloudsdaleUser },
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
});
Deployment.Current.Dispatcher.BeginInvoke(() => SaveUserInternal(serial));
}
private static void SaveUserInternal(string serial) {
var settings = IsolatedStorageSettings.ApplicationSettings;
settings["lastuser"] = serial;
settings.Save();
}
public static bool IsMemberOfCloud(string cloud) {
foreach (var c in CurrentCloudsdaleUser.clouds) {
if (c.id == cloud)
return true;
}
return false;
}
public static void ModifyUserProperty(string property, JToken value, Action success = null, Action<WebException> onError = null) {
var properties = new JObject();
properties[property] = value;
ModifyUserProperty(properties, success, onError);
}
public static void ModifyUserProperty(JToken properties, Action success, Action<WebException> onError) {
var requestData = new JObject();
requestData["user"] = properties;
var bytes = Encoding.UTF8.GetBytes(requestData.ToString());
var request = WebRequest.CreateHttp("http://www.cloudsdale.org/v1/users/" + CurrentCloudsdaleUser.id);
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
request.Headers["Content-Length"] = bytes.Length.ToString();
request.Headers["X-Auth-Token"] = CurrentCloudsdaleUser.auth_token;
request.BeginGetRequestStream(a => {
using (var requestStream = request.EndGetRequestStream(a)) {
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
request.BeginGetResponse(ai => {
try {
using (request.EndGetResponse(ai)) {
if (success != null)
Deployment.Current.Dispatcher.BeginInvoke(success);
}
} catch (WebException ex) {
if (onError != null)
onError(ex);
}
}, null);
}, null);
}
}
public class CloudGetResponse {
public Cloud[] result;
}
public class WebResponse<T> {
public T result;
}
public class LoginState : INotifyPropertyChanged {
private string _message;
public string Message {
get { return _message; }
set {
_message = value;
OnPropertyChanged("Message");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) {
var handler = PropertyChanged;
if (handler != null)
if (!Deployment.Current.Dispatcher.CheckAccess()) {
Deployment.Current.Dispatcher.BeginInvoke(
() => handler(this, new PropertyChangedEventArgs(propertyName)));
} else {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}