-
Notifications
You must be signed in to change notification settings - Fork 820
/
ServerModel.cs
320 lines (272 loc) · 9.18 KB
/
ServerModel.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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Browser;
using Raven.Abstractions.Data;
using Raven.Client;
using Raven.Client.Connection;
using Raven.Client.Document;
using Raven.Json.Linq;
using Raven.Studio.Commands;
using Raven.Studio.Impl;
using Raven.Studio.Infrastructure;
using Raven.Studio.Messages;
using Raven.Abstractions.Extensions;
namespace Raven.Studio.Models
{
public class ServerModel : Model, IDisposable
{
public readonly string Url;
private DocumentStore documentStore;
private string[] defaultDatabase;
private string buildNumber;
private Observable<bool> isConnected;
public UserInfo UserInfo { get; set; }
private bool UserInfoSet = false;
private string rawUrl;
public string RawUrl
{
get { return rawUrl; }
set
{
if (string.IsNullOrWhiteSpace(value))
rawUrl = null;
else
{
if (Url.EndsWith("/"))
rawUrl = Url + value;
else
rawUrl = Url + "/" + value;
}
OnPropertyChanged(() => RawUrl);
}
}
public DocumentConvention Conventions
{
get { return documentStore.Conventions; }
}
public string BuildNumber
{
get { return buildNumber; }
private set { buildNumber = value; OnPropertyChanged(() => BuildNumber); }
}
public ServerModel()
: this(DetermineUri())
{
RefreshRate = TimeSpan.FromMinutes(2);
}
private ServerModel(string url)
{
Url = url;
Databases = new BindableCollection<string>(name => name);
RecentDocuments = new Dictionary<string, QueueModel<string>>();
SelectedDatabase = new Observable<DatabaseModel>();
License = new Observable<LicensingStatus>();
IsConnected = new Observable<bool> { Value = true };
UserInfo = new UserInfo();
Initialize();
}
private void Initialize()
{
if (DesignerProperties.IsInDesignTool)
return;
documentStore = new DocumentStore
{
Url = Url
};
var urlParser = new UrlParser(UrlUtil.Url);
var apiKey = urlParser.GetQueryParam("api-key");
if (string.IsNullOrEmpty(apiKey) == false)
documentStore.ApiKey = apiKey;
documentStore.Initialize();
// We explicitly enable this for the Studio, we rely on SL to actually get us the credentials, and that
// already gives the user a clear warning about the dangers of sending passwords in the clear. I think that
// this is sufficient warning and we don't require an additional step, so we can disable this check safely.
documentStore.JsonRequestFactory.
EnableBasicAuthenticationOverUnsecuredHttpEvenThoughPasswordsWouldBeSentOverTheWireInClearTextToBeStolenByHackers
=
true;
UpdateUserInfo();
documentStore.JsonRequestFactory.ConfigureRequest += (o, eventArgs) =>
{
if (onWebRequest != null)
onWebRequest(eventArgs.Request);
};
defaultDatabase = new[] { Constants.SystemDatabase };
Databases.Set(defaultDatabase);
SetCurrentDatabase(new UrlParser(UrlUtil.Url));
//DisplayRawUrl();
DisplayBuildNumber();
DisplayLicenseStatus();
TimerTickedAsync();
}
private void UpdateUserInfo()
{
if (SelectedDatabase.Value == null)
return;
SelectedDatabase.Value
.AsyncDatabaseCommands
.CreateRequest(string.Format("/debug/user-info").NoCache(), "GET")
.ReadResponseJsonAsync()
.ContinueOnSuccessInTheUIThread(doc =>
{
UserInfoSet = true;
UserInfo = DocumentStore.Conventions.CreateSerializer()
.Deserialize<UserInfo>(new RavenJTokenReader(doc));
});
}
public bool CreateNewDatabase { get; set; }
private static bool firstTick = true;
public override Task TimerTickedAsync()
{
return documentStore.AsyncDatabaseCommands.GetDatabaseNamesAsync(1024)
.ContinueOnSuccess(names =>
{
Databases.Match(defaultDatabase.Concat(names).ToArray());
if (firstTick == false)
return;
firstTick = false;
if (UserInfoSet == false)
UpdateUserInfo();
if (UserInfo != null && UserInfo.IsAdminGlobal)
{
ApplicationModel.Current.Server.Value.DocumentStore
.AsyncDatabaseCommands
.ForSystemDatabase()
.GetAsync("Raven/StudioConfig")
.ContinueOnSuccessInTheUIThread(doc =>
{
if (doc != null && doc.DataAsJson.ContainsKey("WarnWhenUsingSystemDatabase"))
{
if (doc.DataAsJson.Value<bool>("WarnWhenUsingSystemDatabase") == false)
UrlUtil.Navigate("/documents");
}
});
}
var url = new UrlParser(UrlUtil.Url);
if (url.QueryParams.ContainsKey("database") == false && (names.Length == 0 || (names.Length == 1 && names[0] == Constants.SystemDatabase)))
CreateNewDatabase = true;
if (string.IsNullOrEmpty(Settings.Instance.SelectedDatabase))
return;
if (Settings.Instance.SelectedDatabase != null && names.Contains(Settings.Instance.SelectedDatabase))
{
if (url.QueryParams.ContainsKey("database") == false)
{
url.SetQueryParam("database", Settings.Instance.SelectedDatabase);
SetCurrentDatabase(url);
}
if (string.IsNullOrWhiteSpace(url.Path))
UrlUtil.Navigate(Settings.Instance.LastUrl);
}
})
.Catch();
}
public IDocumentStore DocumentStore
{
get { return documentStore; }
}
public Observable<DatabaseModel> SelectedDatabase { get; private set; }
public BindableCollection<string> Databases { get; private set; }
public void Dispose()
{
documentStore.Dispose();
}
private static string DetermineUri()
{
if (DesignerProperties.IsInDesignTool)
return string.Empty;
if (HtmlPage.Document.DocumentUri.Scheme == "file")
{
if (HtmlPage.Document.DocumentUri.Query.Contains("fiddler"))
return "http://localhost.fiddler:8080";
return "http://localhost:8080";
}
var localPath = HtmlPage.Document.DocumentUri.LocalPath;
var lastIndexOfRaven = localPath.LastIndexOf("/raven/", StringComparison.Ordinal);
if (lastIndexOfRaven != -1)
localPath = localPath.Substring(0, lastIndexOfRaven);
return new UriBuilder(HtmlPage.Document.DocumentUri)
{
Path = localPath,
Fragment = ""
}.Uri.ToString();
}
public void SetCurrentDatabase(UrlParser urlParser)
{
var databaseName = urlParser.GetQueryParam("database");
if (SelectedDatabase.Value != null
&& (SelectedDatabase.Value.Name == databaseName || (SelectedDatabase.Value.Name == Constants.SystemDatabase && databaseName == null)))
return;
if (SelectedDatabase.Value != null)
SelectedDatabase.Value.Dispose();
SelectedDatabase.Value = databaseName == null
? new DatabaseModel(Constants.SystemDatabase, documentStore) : new DatabaseModel(databaseName, documentStore);
SelectedDatabase.Value.AsyncDatabaseCommands
.EnsureSilverlightStartUpAsync()
.ContinueOnSuccess(() =>
{
if (databaseName != null && databaseName != Constants.SystemDatabase)
Settings.Instance.SelectedDatabase = databaseName;
})
.Catch(exception =>
{
var webException = exception.ExtractSingleInnerException() as WebException;
if (webException == null)
return false;
var httpWebResponse = webException.Response as HttpWebResponse;
if (httpWebResponse == null)
return false;
if (httpWebResponse.StatusCode != HttpStatusCode.ServiceUnavailable)
return false;
ApplicationModel.Current.Notifications.Add(new Notification("Database " + databaseName + " does not exist.", NotificationLevel.Error, webException));
return true;
});
}
private void DisplayBuildNumber()
{
SelectedDatabase.Value.AsyncDatabaseCommands.GetBuildNumberAsync()
.ContinueOnSuccessInTheUIThread(x => BuildNumber = x.BuildVersion)
.Catch();
}
private void DisplayLicenseStatus()
{
SelectedDatabase.Value.AsyncDatabaseCommands.GetLicenseStatusAsync()
.ContinueOnSuccessInTheUIThread(x =>
{
License.Value = x;
if (x.Error == false)
return;
new ShowLicensingStatusCommand().Execute(x);
})
.Catch();
}
//private void DisplayRawUrl()
//{
// if (SelectedDatabase != null && SelectedDatabase.Value != null && SelectedDatabase.Value.Name != null)
// RawUrl = Path.Combine(Url, "databases", SelectedDatabase.Value.Name);
// else
// RawUrl = Url;
//}
public Dictionary<string, QueueModel<string>> RecentDocuments { get; set; }
public Observable<LicensingStatus> License { get; private set; }
public Observable<bool> IsConnected
{
get { return isConnected; }
set
{
isConnected = value;
OnPropertyChanged(() => IsConnected);
}
}
public void SetConnected(bool isConnected)
{
IsConnected.Value = isConnected;
OnPropertyChanged(() => IsConnected);
}
}
}