-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathMaintenanceTask.cs
310 lines (269 loc) · 14.6 KB
/
MaintenanceTask.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
using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.Storage.Search;
using Windows.UI.StartScreen;
namespace MaintenanceTask
{
public sealed class MaintenanceTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral Deferral = taskInstance.GetDeferral();
try
{
using (CancellationTokenSource Cancellation = new CancellationTokenSource())
{
taskInstance.Canceled += (s, e) =>
{
Cancellation.Cancel();
};
await Task.WhenAll(UpdateSystemLaunchHelperAsync(Cancellation.Token),
UpdateSQLiteAsync(Cancellation.Token),
ClearTemporaryFolderAsync(Cancellation.Token),
RefreshJumpListAsync(Cancellation.Token));
}
}
catch (OperationCanceledException)
{
// No need to handle this exception
}
catch (Exception)
{
#if DEBUG
if (Debugger.IsAttached)
{
Debugger.Break();
}
else
{
Debugger.Launch();
}
#endif
}
finally
{
Deferral.Complete();
}
}
private async Task UpdateSystemLaunchHelperAsync(CancellationToken CancelToken = default)
{
if (Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["InterceptDesktopFolder"])
|| Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["InterceptWindowsE"]))
{
StorageFolder SourceFolder = await StorageFolder.GetFolderFromPathAsync(Path.Combine(Windows.ApplicationModel.Package.Current.InstalledPath, "SystemLaunchHelper"));
StorageFolder LocalAppDataFolder = await StorageFolder.GetFolderFromPathAsync(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
StorageFolder TargetFolder = await LocalAppDataFolder.CreateFolderAsync("RX-Explorer_Launch_Helper", CreationCollisionOption.ReplaceExisting);
if (!CancelToken.IsCancellationRequested)
{
await CopyFolderAsync(SourceFolder, TargetFolder, CancelToken);
StorageFile VersionLockFile = await TargetFolder.CreateFileAsync("Version.lock", CreationCollisionOption.ReplaceExisting);
using (Stream FileStream = await VersionLockFile.OpenStreamForWriteAsync())
using (StreamWriter Writer = new StreamWriter(FileStream, Encoding.UTF8, 128, true))
{
await Writer.WriteLineAsync($"{Windows.ApplicationModel.Package.Current.Id.Version.Major}.{Windows.ApplicationModel.Package.Current.Id.Version.Minor}.{Windows.ApplicationModel.Package.Current.Id.Version.Build}.{Windows.ApplicationModel.Package.Current.Id.Version.Revision}");
await Writer.FlushAsync();
}
}
}
}
private async Task CopyFolderAsync(StorageFolder From, StorageFolder To, CancellationToken CancelToken = default)
{
const uint FetchItemEachNum = 50;
StorageItemQueryResult Query = From.CreateItemQueryWithOptions(new QueryOptions
{
FolderDepth = FolderDepth.Shallow,
IndexerOption = IndexerOption.DoNotUseIndexer
});
for (uint Index = 0; !CancelToken.IsCancellationRequested; Index += FetchItemEachNum)
{
IReadOnlyList<IStorageItem> StorageItemList = await Query.GetItemsAsync(Index, FetchItemEachNum);
if (StorageItemList.Count == 0)
{
break;
}
foreach (IStorageItem Item in StorageItemList)
{
CancelToken.ThrowIfCancellationRequested();
switch (Item)
{
case StorageFolder SubFolder:
{
await CopyFolderAsync(SubFolder, await To.CreateFolderAsync(SubFolder.Name, CreationCollisionOption.ReplaceExisting));
break;
}
case StorageFile SubFile:
{
await SubFile.CopyAsync(To, SubFile.Name, NameCollisionOption.ReplaceExisting);
break;
}
}
}
}
}
private async Task ClearTemporaryFolderAsync(CancellationToken CancelToken = default)
{
try
{
await ApplicationData.Current.ClearAsync(ApplicationDataLocality.Temporary);
}
catch (Exception)
{
const uint FetchItemEachNum = 50;
StorageItemQueryResult Query = ApplicationData.Current.TemporaryFolder.CreateItemQueryWithOptions(new QueryOptions
{
IndexerOption = IndexerOption.DoNotUseIndexer,
FolderDepth = FolderDepth.Shallow
});
for (uint Index = 0; !CancelToken.IsCancellationRequested; Index += FetchItemEachNum)
{
IReadOnlyList<IStorageItem> StorageItemList = await Query.GetItemsAsync(Index, FetchItemEachNum);
if (StorageItemList.Count == 0)
{
break;
}
foreach (IStorageItem Item in StorageItemList)
{
CancelToken.ThrowIfCancellationRequested();
await Item.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
}
}
}
private async Task UpdateSQLiteAsync(CancellationToken CancelToken = default)
{
if (await ApplicationData.Current.LocalFolder.TryGetItemAsync("RX_Sqlite.db").AsTask().AsCancellable(CancelToken) is StorageFile DBFile)
{
await Task.Run(() =>
{
SqliteConnectionStringBuilder ConnectionBuilder = new SqliteConnectionStringBuilder
{
DataSource = DBFile.Path,
Mode = SqliteOpenMode.ReadWrite,
Cache = SqliteCacheMode.Private
};
using (SqliteConnection Connection = new SqliteConnection(ConnectionBuilder.ToString()))
{
Connection.Open();
using (SqliteTransaction Transaction = Connection.BeginTransaction())
{
StringBuilder QueryBuilder = new StringBuilder("Delete From ProgramPicker Where FileType = '.*';");
using (SqliteCommand Command = new SqliteCommand("Select Count(*) From sqlite_master Where type = \"table\" And name = \"FileColor\"", Connection, Transaction))
{
if (Convert.ToInt32(Command.ExecuteScalar()) > 0)
{
QueryBuilder.Append("Insert Or Ignore Into FileTag (Path, ColorTag) Select Path, Color From FileColor;")
.Append("Update FileTag Set ColorTag = 'Blue' Where ColorTag = '#FF42C5FF';")
.Append("Update FileTag Set ColorTag = 'Green' Where ColorTag = '#FF22B324';")
.Append("Update FileTag Set ColorTag = 'Orange' Where ColorTag = '#FFFFA500';")
.Append("Update FileTag Set ColorTag = 'Purple' Where ColorTag = '#FFCC6EFF';")
.Append("Drop Table FileColor;");
}
}
QueryBuilder.Append("Create Table If Not Exists PathTagMapping (Path Text Not Null Collate NoCase, Label Text Not Null, Primary Key (Path));");
QueryBuilder.Append("Update PathTagMapping Set Label = 'None' Where Label = 'Transparent';");
QueryBuilder.Append("Delete From PathTagMapping Where Label = 'None';");
using (SqliteCommand Command = new SqliteCommand("Select Count(*) From sqlite_master Where type = \"table\" And name = \"FileTag\"", Connection, Transaction))
{
if (Convert.ToInt32(Command.ExecuteScalar()) > 0)
{
QueryBuilder.Append("Insert Or Ignore Into PathTagMapping (Path, Label) Select Path, ColorTag From FileTag;")
.Append("Update PathTagMapping Set Label = 'None' Where Label = 'Transparent';")
.Append("Update PathTagMapping Set Label = 'PredefineLabel1' Where Label = 'Blue';")
.Append("Update PathTagMapping Set Label = 'PredefineLabel2' Where Label = 'Green';")
.Append("Update PathTagMapping Set Label = 'PredefineLabel3' Where Label = 'Orange';")
.Append("Update PathTagMapping Set Label = 'PredefineLabel4' Where Label = 'Purple';")
.Append("Drop Table FileTag;");
}
}
bool HasGroupColumnColumn = false;
bool HasGroupDirectionColumn = false;
using (SqliteCommand Command = new SqliteCommand("PRAGMA table_info('PathConfiguration')", Connection, Transaction))
using (SqliteDataReader Reader = Command.ExecuteReader())
{
while (Reader.Read())
{
switch (Convert.ToString(Reader[1]))
{
case "GroupColumn":
HasGroupColumnColumn = true;
break;
case "GroupDirection":
HasGroupDirectionColumn = true;
break;
}
}
}
if (!HasGroupColumnColumn)
{
QueryBuilder.Append("Alter Table PathConfiguration Add GroupColumn Text Default 'None' Check(GroupColumn In ('None','Name','ModifiedTime','Type','Size'));");
}
if (!HasGroupDirectionColumn)
{
QueryBuilder.Append("Alter Table PathConfiguration Add GroupDirection Text Default 'Ascending' Check(GroupDirection In ('Ascending','Descending'));");
}
bool HasIsDefaultColumn = false;
bool HasIsRecommandColumn = false;
using (SqliteCommand Command = new SqliteCommand("PRAGMA table_info('ProgramPicker')", Connection, Transaction))
using (SqliteDataReader Reader = Command.ExecuteReader())
{
while (Reader.Read())
{
switch (Convert.ToString(Reader[1]))
{
case "IsRecommanded":
HasIsRecommandColumn = true;
break;
case "IsDefault":
HasIsDefaultColumn = true;
break;
}
}
}
if (!HasIsDefaultColumn)
{
QueryBuilder.AppendLine("Alter Table ProgramPicker Add Column IsDefault Text Default 'False' Check(IsDefault In ('True','False'));");
}
if (!HasIsRecommandColumn)
{
QueryBuilder.AppendLine("Alter Table ProgramPicker Add Column IsRecommanded Text Default 'False' Check(IsDefault In ('True','False'));");
}
if (!CancelToken.IsCancellationRequested)
{
using (SqliteCommand Command = new SqliteCommand(QueryBuilder.ToString(), Connection, Transaction))
{
Command.ExecuteNonQuery();
}
Transaction.Commit();
}
}
}
});
}
}
private async Task RefreshJumpListAsync(CancellationToken CancelToken = default)
{
if (JumpList.IsSupported())
{
JumpList CurrentJumpList = await JumpList.LoadCurrentAsync().AsTask().AsCancellable(CancelToken);
foreach (JumpListItem OldItem in CurrentJumpList.Items.ToArray())
{
JumpListItem NewItem = JumpListItem.CreateWithArguments(OldItem.Arguments, OldItem.DisplayName);
NewItem.Description = OldItem.Arguments;
NewItem.GroupName = OldItem.GroupName;
NewItem.Logo = OldItem.Logo;
CurrentJumpList.Items[CurrentJumpList.Items.IndexOf(OldItem)] = NewItem;
}
await CurrentJumpList.SaveAsync().AsTask().AsCancellable(CancelToken);
}
}
}
}