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 1
/
Main.cs
499 lines (439 loc) · 17.9 KB
/
Main.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using Cloudsdale.lib.Controllers;
using Cloudsdale.lib.connection;
using Cloudsdale.lib.Controllers.CloudSubscriber;
using Cloudsdale.lib.Controllers.MessageController;
using Cloudsdale.lib.Controllers.MessageController.Processors;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Cloudsdale.lib;
using Cloudsdale.lib.Models;
namespace Cloudsdale
{
public partial class Main : Form
{
public bool SettingsVisible;
public static Main Instance = new Main();
public static JObject User;
public static JToken CurrentCloud;
public static Regex LinkRegex =
new Regex(
@"(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'"".,<>?«»“”‘’]))",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
public bool DirectedToHome;
public bool LoggedIn;
public Main()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Email.Text = CloudsdaleSettings.Default.PreviousEmail;
Password.Text = CloudsdaleSettings.Default.PreviousPassword;
autologin.Checked = CloudsdaleSettings.Default.AutoLogin;
LoadAnimation.Visible = false;
ImageAnimator.Animate(CloudAnimation.Image, null);
LoggedIn = false;
this.Width = 900;
LoginPanel.BringToFront();
LoginPanel.Dock = DockStyle.Fill;
if (LoginPanel.Visible == true)
{
this.MaximizeBox = false;
}
LeaveSettings();
if (autologin.Checked)
{
if (Email.Text != null)
{
button1_Click(Login, EventArgs.Empty);
}
}
CloudSubList.AddCloud("hang_out");
}
private async void button1_Click(object sender, EventArgs e)
{
try
{
CloudsdaleSettings.Default.PreviousEmail = Email.Text;
CloudsdaleSettings.Default.PreviousPassword = Password.Text;
CloudsdaleSettings.Default.AutoLogin = autologin.Checked;
CloudsdaleSettings.Default.Save();
LoadAnimation.Visible = true;
ImageAnimator.Animate(LoadAnimation.Image, null);
this.Text = "Logging in...";
Login.Enabled = false;
Register.Enabled = false;
Email.ReadOnly = true;
Password.ReadOnly = true;
await LoginRequest();
this.Text = "Login succesful!";
Token.SaveToken((string)User["user"]["auth_token"]);
this.AcceptButton = m_SendMessage;
this.MaximizeBox = true;
Connection.MessageReceived += o =>
{
if (o["data"] == null) return;
var cloudId = ((string) o["channel"]).Split('/')[2];
var source = MessageSource.GetSource(cloudId);
LoadMessageToSource(source, o["data"], cloudId);
};
await Connection.InitializeAsync();
this.Text = "Loading clouds...";
Main MainWindow = new Main();
await PreloadMessages((JArray) User["user"]["clouds"]);
h_avatar.BackgroundImage = AvatarConverter.LoadImage((string) User["user"]["avatar"]["normal"]);
h_avatar.BackgroundImageLayout = ImageLayout.Zoom;
Login.Enabled = true;
Register.Enabled = true;
Email.ReadOnly = false;
Password.ReadOnly = false;
LoginPanel.Visible = false;
//UserCheck.Authorize(User["user"]["name"].ToString());
//Discord's fault.
MessageGroup.Text = "Welcome back, " + User["user"]["name"] + "!";
var calDate = User["user"]["member_since"].ToString();
var newDate = calDate.Replace("+0000", "");
h_memberSince.Text = "Member since " + newDate;
SetupUserMenu();
RedirectHome(true);
LoggedIn = true;
}
catch (CouldNotLoginException ex)
{
System.Windows.MessageBox.Show(ex.Message);
Login.Enabled = true;
Register.Enabled = true;
Email.ReadOnly = false;
Password.ReadOnly = false;
this.Text = "Cloudsdale";
}
catch (WebException webex)
{
System.Windows.MessageBox.Show(webex.Message);
Login.Enabled = true;
Register.Enabled = true;
Email.ReadOnly = false;
Password.ReadOnly = false;
this.Text = "Cloudsdale";
}
LoadAnimation.Visible = false;
}
public async Task LoginRequest()
{
var dataObject = new JObject();
dataObject["email"] = Email.Text;
dataObject["password"] = Password.Text;
var data = Encoding.UTF8.GetBytes(dataObject.ToString(Formatting.None));
var request = WebRequest.CreateHttp(Endpoints.Session);
request.Method = "POST";
request.ContentLength = data.Length;
request.ContentType = "application/json";
request.Accept = "application/json";
request.Timeout = 1500;
using (var requestStream = await request.GetRequestStreamAsync())
{
await requestStream.WriteAsync(data, 0, data.Length);
await requestStream.FlushAsync();
requestStream.Close();
}
string responseData;
try
{
using (var response = await request.GetResponseAsync())
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null) return;
using (var responseStreamReader = new StreamReader(responseStream, Encoding.UTF8))
{
responseData = await responseStreamReader.ReadToEndAsync();
}
}
}
catch (WebException ex)
{
using (var response = ex.Response)
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null) return;
using (var responseStreamReader = new StreamReader(responseStream, Encoding.UTF8))
{
responseData = responseStreamReader.ReadToEnd();
}
}
throw new CouldNotLoginException(responseData);
}
var responseObject = JObject.Parse(responseData);
Main.User = (JObject) responseObject["result"];
await Connection.InitializeAsync();
}
private void LoadMessageToSource(MessageSource source, JToken message, string cloudId)
{
message["orgcontent"] = message["content"] =
message["content"].ToString().UnescapeLiteral().RegexReplace(@"[ ]+", " ");
lock (source)
{
JToken lastMsg;
if (source.Messages.Any()
&& (string) (lastMsg = source.Messages.Last())["author"]["id"] == (string) message["author"]["id"]
&& !lastMsg["orgcontent"].ToString().StartsWith("/me")
&& !message["content"].ToString().StartsWith("/me"))
{
lastMsg["content"] += "\n" + message["content"];
lastMsg["drops"] = new JArray(lastMsg["drops"].Concat(message["drops"]));
source.Messages.RemoveAt(source.Messages.Count - 1);
source.Messages.Add(lastMsg);
}
else
{
message["content"] = message["content"]
.ToString().RegexReplace("^/me", (string) message["author"]["name"]);
source.AddMessage(message);
}
if (LoggedIn)
{
NotificationControl.ShowSimple(cloudId, (string)message["author"]["id"]);
}
}
}
private async Task PreloadMessages(ICollection<JToken> clouds)
{
foreach (var cloud in clouds)
{
try
{
this.Text = "Loading messages from " + (string)cloud["name"] + "...";
var request =
WebRequest.CreateHttp(Endpoints.CloudMessages.Replace("[:id]", cloud["id"].ToString()));
request.Accept = "application/json";
using (var response = await request.GetResponseAsync())
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null) continue;
using (var responseReader = new StreamReader(responseStream))
{
var responseData = JObject.Parse(await responseReader.ReadToEndAsync());
var source = MessageSource.GetSource(cloud);
foreach (var message in responseData["result"])
{
LoadMessageToSource(source, message, (string)cloud["id"]);
}
FayeConnector.Subscribe("/clouds/" + cloud["id"] + "/chat/messages");
CloudList.SmallImageList.Images.Add((string)cloud["id"],
LoadImage((string)cloud["avatar"]["normal"]));
CloudList.Items.Add((string)cloud["id"], cloud["name"].ToString().TrimStart(),
CloudList.SmallImageList.Images.Count - 1);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
private Image LoadImage(string url)
{
WebRequest request =
WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream responseStream =
response.GetResponseStream();
Bitmap bmp = new Bitmap(responseStream);
responseStream.Dispose();
return bmp;
}
private void LaunchReg(object sender, EventArgs e)
{
Process.Start("https://www.cloudsdale.org/register");
}
#region Visual changes
private void SetupUserMenu()
{
sp_user_avatar.Image = AvatarConverter.LoadImage((string) User["user"]["avatar"]["normal"]);
sp_user_name.Text = (string) User["user"]["name"];
sp_user_username.Text = (string) User["user"]["username"];
sp_user_akaList.Text = User["user"]["also_known_as"].ToString().MultiReplace("[", "]", Environment.NewLine,
"").Trim();
sp_user_skype.Text = UserModel.SkypeUsername(User["user"]["id"].ToString());
sp_user_cloudCount.Text = CloudList.Items.Count.ToString();
sp_user_joinDate.Text = User["user"]["member_since"].ToString().Replace("+0000", "");
sp_user_triesLeft.Text = UserModel.NameChangesAllowed().ToString();
if (sp_user_triesLeft.Text == "0")
{
sp_user_username.ReadOnly = true;
}
RoleModel.CreateRole(sp_user_role, (string) User["user"]["id"]);
sp_user_role.BackColor = RoleModel.Role_Color(UserModel.Role((string) User["user"]["id"]));
sp_user_email.Text = (string) User["user"]["email"];
}
private void ActivateMenuHover(object sender, EventArgs e)
{
if (SettingsPanel.Height != 55)
{
ViewTimer.Start();
}
else
{
SettingsPanel.Height = 0;
sp_user.Visible = false;
}
}
private void SettingsHover(object sender, EventArgs e)
{
SettingsVisible = true;
SettingsPanel.Height = 55;
}
private void ShowSettings(object sender, EventArgs e)
{
var SettingsNewSize = SettingsPanel.Height;
if (SettingsNewSize >= 55)
{
SettingsPanel.Height = 55;
ViewTimer.Stop();
}
else
{
SettingsNewSize += 1*((SettingsNewSize + 2)/2);
SettingsPanel.Height = SettingsNewSize;
}
}
private void LeaveSettings()
{
SettingsPanel.Height = 0;
sp_user.Visible = false;
sp_settings.Visible = false;
}
private void CloudList_SelectedIndexChanged(object sender, EventArgs e)
{
LeaveSettings();
if (CloudList.SelectedItems.Count > 0)
{
if (CloudList.FocusedItem.Index >= 0)
{
RedirectHome(false);
MessageGroup.Text = CloudList.FocusedItem.Text;
this.Text = CloudList.FocusedItem.Text;
CurrentCloud = CloudList.FocusedItem.Name;
if (CloudList.FocusedItem.Index == 1)
{
//messages = visible
}
else
{
//messages = not visible
}
}
else
{
RedirectHome(true);
}
}
}
private void button1_Click_1(object sender, EventArgs e)
{
MessageGroup.Text = "Welcome back, [:user]!".Replace("[:user]", (string) User["user"]["name"]);
RedirectHome(true);
}
private void RedirectHome(bool RedirectedHome)
{
if (RedirectedHome == true)
{
//add the component here to release all MessageViews
h_panel.Visible = true;
m_NewMessage.Visible = false;
m_SendMessage.Visible = false;
this.Text = "Home";
}
else
{
h_panel.Visible = false;
m_NewMessage.Visible = true;
m_SendMessage.Visible = true;
}
}
private void ResizeCheck(object sender, EventArgs e)
{
if (this.Width < 695)
{
h_about.Visible = false;
}
else
{
h_about.Visible = true;
}
}
#endregion
private void CloudContext_Opening(object sender, CancelEventArgs e)
{
//Add detection if user is the owner of the cloud.
}
private void menuItem_user_Click(object sender, EventArgs e)
{
if (sp_user.Visible)
{
sp_user.Visible = false;
}else
{
sp_user.Visible = true;
sp_settings.Visible = false;
}
}
private void sp_user_avatar_Click(object sender, EventArgs e)
{
var browser = new OpenFileDialog();
browser.Filter = "png image (*.png)|*.png| jpg image (*.jpg|*.jpg";
browser.Title = "Upload new avatar.";
browser.InitialDirectory = Environment.SpecialFolder.CommonPictures.ToString();
browser.ShowDialog();
if (DialogResult != DialogResult.Cancel)
{
//Stream selectedImage = new FileStream(browser.FileName, FileMode.Open);
//UserModel.UploadNewAvatar(selectedImage, "test");
//selectedImage.Dispose();
}
}
private void menuItem_Logout_Click(object sender, EventArgs e)
{
this.Controls.Clear();
InitializeComponent();
Email.Text = CloudsdaleSettings.Default.PreviousEmail;
Password.Text = CloudsdaleSettings.Default.PreviousPassword;
autologin.Checked = CloudsdaleSettings.Default.AutoLogin;
LoadAnimation.Visible = false;
ImageAnimator.Animate(CloudAnimation.Image, null);
LoggedIn = false;
this.Width = 695;
LoginPanel.BringToFront();
LoginPanel.Dock = DockStyle.Fill;
if (LoginPanel.Visible == true)
{
this.MaximizeBox = false;
}
SettingsPanel.Height = 0;
}
private void menuItem_Settings_Click(object sender, EventArgs e)
{
if (sp_settings.Visible)
{
sp_settings.Visible = false;
}
else
{
sp_settings.Visible = true;
sp_user.Visible = false;
}
}
}
}