-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bootstrapper.cs
254 lines (228 loc) · 9.79 KB
/
Bootstrapper.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
using System;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
using Anidow.Factories;
using Anidow.Helpers;
using Anidow.Pages;
using Anidow.Pages.Components.Status;
using Anidow.Properties;
using Anidow.Services;
using Anidow.Torrent_Clients;
using FluentScheduler;
using Hardcodet.Wpf.TaskbarNotification;
using Jot;
using Jot.Storage;
using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Stylet;
using StyletIoC;
#if RELEASE
using AdonisUI.Controls;
using System.IO;
using System.Windows.Threading;
using System.Linq;
using MessageBox = AdonisUI.Controls.MessageBox;
using MessageBoxButton = AdonisUI.Controls.MessageBoxButton;
using MessageBoxImage = AdonisUI.Controls.MessageBoxImage;
using MessageBoxResult = AdonisUI.Controls.MessageBoxResult;
#endif
namespace Anidow
{
public class Bootstrapper : Bootstrapper<ShellViewModel>
{
private HttpClient _httpClient;
private ILogger _logger;
private ShellView _shell;
private TaskbarIcon _taskBarIcon;
private UpdateManager _updateManager;
// Configure the IoC container in here
protected override void ConfigureIoC(IStyletIoCBuilder builder)
{
var assembly = Assembly.GetExecutingAssembly();
builder.Bind<Assembly>().ToInstance(assembly);
var tracker = InitTracker();
builder.Bind<Tracker>().ToInstance(tracker);
var logViewModel = new LogViewModel();
InitLogger(logViewModel);
builder.Bind<ILogger>().ToInstance(_logger);
builder.Bind<LogViewModel>().ToInstance(logViewModel);
// Services
builder.Bind<FeedStorageService>().ToSelf().InSingletonScope();
builder.Bind<NyaaService>().ToSelf().InSingletonScope();
builder.Bind<AnimeBytesService>().ToSelf().InSingletonScope();
builder.Bind<StoreService>().ToSelf();
builder.Bind<TorrentService>().ToSelf().InSingletonScope();
builder.Bind<SettingsService>().ToSelf().InSingletonScope();
builder.Bind<NotifyService>().ToSelf().InSingletonScope();
builder.Bind<AppService>().ToSelf().InSingletonScope();
builder.Bind<StatusViewModel>().ToSelf().InSingletonScope();
builder.Bind<QBitTorrent>().ToSelf();
builder.Bind<TorrentClientFactory>().ToSelf().InSingletonScope();
_httpClient = InitHttpClient();
builder.Bind<HttpClient>().ToInstance(_httpClient);
_updateManager = new UpdateManager(_httpClient);
builder.Bind<UpdateManager>().ToInstance(_updateManager);
_shell = new ShellView(tracker);
if (Args.Length > 0 && Args[0] == "/autostart")
{
_shell.WindowState = WindowState.Minimized;
}
_taskBarIcon = _shell.TaskbarIcon;
builder.Bind<TaskbarIcon>().ToInstance(_shell.TaskbarIcon);
builder.Bind<ShellView>().ToInstance(_shell);
//BindViewModels(builder);
}
//private void BindViewModels(IStyletIoCBuilder builder)
//{
// builder.Bind<ShellViewModel>().ToSelf();
// builder.Bind<AnimeBytesViewModel>().ToSelf().InSingletonScope();
// builder.Bind<AnimeBytesRssViewModel>().ToSelf().InSingletonScope();
// builder.Bind<AnimeBytesSearchViewModel>().ToSelf().InSingletonScope();
// builder.Bind<MainViewModel>().ToSelf().InSingletonScope();
// builder.Bind<NyaaViewModel>().ToSelf().InSingletonScope();
// builder.Bind<SettingsViewModel>().ToSelf().InSingletonScope();
// builder.Bind<TrackedViewModel>().ToSelf().InSingletonScope();
//}
private HttpClient InitHttpClient()
{
var clientHandler = new HttpClientHandler
{
AllowAutoRedirect = true,
AutomaticDecompression = DecompressionMethods.All,
UseCookies = true,
};
var httpClient = new HttpClient(clientHandler) { Timeout = TimeSpan.FromSeconds(60) };
httpClient.DefaultRequestHeaders.UserAgent.Clear();
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36");
httpClient.DefaultRequestHeaders.Add("dnt", "1");
httpClient.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache");
httpClient.DefaultRequestHeaders.Accept.ParseAdd("*/*");
httpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");
httpClient.DefaultRequestHeaders.Pragma.ParseAdd("no-cache");
return httpClient;
}
private Tracker InitTracker()
{
var tracker = new Tracker(new JsonFileStore(Environment.SpecialFolder.CommonApplicationData));
tracker.Configure<ShellView>()
.Id(_ =>
$"[Width={SystemParameters.VirtualScreenWidth},Height{SystemParameters.VirtualScreenHeight}]")
.Properties(w => new { w.Height, w.Width, w.Left, w.Top, w.WindowState })
.PersistOn(nameof(ShellView.Closing))
.StopTrackingOn(nameof(ShellView.Closing));
return tracker;
}
private void InitLogger(ILogEventSink logViewModel)
{
var logLevel = Debugger.IsAttached ? LogEventLevel.Debug : LogEventLevel.Information;
var logConfiguration = new LoggerConfiguration()
.MinimumLevel.Is(logLevel)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.Sink(logViewModel, logLevel)
.WriteTo.File(
"./logs/log-.txt",
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 7,
restrictedToMinimumLevel: LogEventLevel.Error);
_logger = logConfiguration.CreateLogger();
}
protected override void OnExit(ExitEventArgs e)
{
_taskBarIcon?.Dispose();
JobManager.RemoveAllJobs();
JobManager.Stop();
base.OnExit(e);
}
[DllImport("user32.dll")]
private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
protected override void Configure()
{
#if RELEASE
var processes = Process.GetProcessesByName(
Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly()?.Location));
if (processes.Length > 1)
{
var p = processes.FirstOrDefault();
if (p is not null)
{
ShowWindow(p.MainWindowHandle, 5);
SetForegroundWindow(p.MainWindowHandle);
}
Environment.Exit(0);
}
#endif
var secret = Resources.AppCenter_Secret;
if (!string.IsNullOrWhiteSpace(secret) && !AppCenter.Configured)
{
AppCenter.Start(secret, typeof(Crashes), typeof(Analytics));
}
else
{
_logger.Warning("AppCenter not configured, secret is empty");
}
if (Application.Current.MainWindow != null)
{
Application.Current.MainWindow.Language =
XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag);
}
// Initialize FluentScheduler
JobManager.Initialize();
JobManager.JobException += info =>
_logger.Error(info.Exception, "An error just happened with a scheduled job");
//JobManager.JobStart += info => _logger.Debug($"{info.Name}: started");
//JobManager.JobEnd += info =>_logger.Debug($"{info.Name}: ended ({info.Duration})");
#if SELF_CONTAINED && RELEASE
var selfContained = true;
#else
var selfContained = false;
#endif
_logger.Information(
$"Anidow v{Assembly.GetExecutingAssembly().GetName().Version} selfcontained: {selfContained}");
}
#if RELEASE
protected override void OnUnhandledException(DispatcherUnhandledExceptionEventArgs e)
{
_logger.Fatal(e.Exception, e.Exception.Message);
if (AppCenter.Configured)
{
var messageBox = new MessageBoxModel
{
Text = $"Would you like to report this crash?\n\nCrash message: '{e.Exception.Message}'",
Caption = "Anidow crashed!",
Icon = MessageBoxImage.Error,
Buttons = new[]
{
MessageBoxButtons.Yes("Yes!"),
MessageBoxButtons.No("No!"),
},
IsSoundEnabled = true,
};
var result = MessageBox.Show(messageBox);
if (result == MessageBoxResult.Yes)
{
Crashes.TrackError(e.Exception);
}
}
else
{
MessageBox.Show(e.Exception.Message, "Anidow crashed!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
#endif
}
}