Repository navigation
Expand file tree
/
Copy pathAndroidUpdates.cs
More file actions
244 lines (219 loc) · 10.7 KB
/
Copy pathAndroidUpdates.cs
File metadata and controls
244 lines (219 loc) · 10.7 KB
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
using Android.App;
using Android.Content;
using Android.Content.PM;
using System.Text.Json;
// The notification that tells a new version, asked for as the app opens (MainActivity.HandleUpdates).
[assembly: UsesPermission(Android.Manifest.Permission.PostNotifications)]
#if SELF_INSTALL
[assembly: UsesPermission(Android.Manifest.Permission.RequestInstallPackages)]
#endif
namespace Berpiztu.KeyPlus;
/// <summary>
/// The Android side of <see cref="Updates"/>, both products: the keyboard (or
/// the popup's service) asks once a day while Buscar actualizaciones
/// automáticamente is on, and a newer release is a notification that opens
/// the app; the app asks whether to update (also when it opens, and from
/// Buscar ahora), and a yes downloads the product's APK and hands it to
/// Android's installer, which asks the user too (and, the first time, to
/// allow installing from this app); in a build without the installer
/// (SELF_INSTALL, KeyPlusSelfInstall in the csproj) a yes opens the release's
/// page on GitHub in the browser, where its APK is downloaded and handed to
/// Android's installer.
/// </summary>
public static class AndroidUpdates
{
/// <summary>The app opened from the notification: it asks whether to update.</summary>
public const string AskExtra = "askUpdate";
#if SELF_INSTALL
/// <summary>The app opened by Android's installer with how the install went (PackageInstaller.ExtraStatus).</summary>
public const string InstallExtra = "installStatus";
#endif
private const string Channel = "updates";
private const int NotificationId = 7;
#if KEYBOARD
private const string File = Updates.KeyboardApk;
#else
private const string File = Updates.PopupApk;
#endif
private static bool checking;
/// <summary>The version installed, as Información shows it.</summary>
public static string Running(Context context) => context.PackageManager!.GetPackageInfo(context.PackageName!, 0)!.VersionName ?? "";
/// <summary>Buscar actualizaciones automáticamente on, and a day gone since GitHub was last asked.</summary>
public static bool Due(Context context) =>
KeyPlusPreferences.Global(context).GetBoolean(KeyPlusPreferences.UpdatesAutomaticKey, true) && Updates.Due(Checked(context));
/// <summary>From the keyboard or the service: GitHub asked when it is due, a newer release told in a notification; a failure only in the log.</summary>
public static async void CheckInBackground(Context context)
{
if (checking || !Due(context))
{
return;
}
checking = true;
try
{
var release = await Updates.LatestAsync(File);
KeepChecked(context);
if (Updates.IsNewer(release, Running(context)))
{
Log.Write($"Updates: {release.Version} is out, {Running(context)} installed");
Notify(context, release);
}
}
catch (Exception failed) when (Failed(failed))
{
Log.Write($"Updates: {failed.Message}");
}
finally
{
checking = false;
}
}
/// <summary>From Información's Check now: GitHub asked, its latest release given back for the page itself to show; none where it cannot be read, said in the log.</summary>
public static async Task<Updates.Release?> LatestAsync(Context context)
{
try
{
var release = await Updates.LatestAsync(File);
KeepChecked(context);
return release;
}
catch (Exception failed) when (Failed(failed))
{
Log.Write($"Updates: {failed.Message}");
return null;
}
}
/// <summary>From the app: GitHub asked, and a newer release offered in a dialog; asked by hand, an answer whatever it is.</summary>
public static async Task CheckAsync(Activity activity, bool asked)
{
if (checking)
{
return;
}
checking = true;
try
{
var release = await Updates.LatestAsync(File);
KeepChecked(activity);
if (!Updates.IsNewer(release, Running(activity)))
{
if (asked)
{
Tell(activity, Say(activity, Resource.String.update_current, Running(activity)));
}
return;
}
new AlertDialog.Builder(activity)
.SetTitle(Resource.String.update_title)!
.SetMessage(Say(activity, Resource.String.update_ask, release.Version.ToString(), Running(activity)))!
#if SELF_INSTALL
.SetPositiveButton(Resource.String.update_yes, async (_, _) => await InstallAsync(activity, release))!
#else
.SetPositiveButton(Resource.String.update_yes, (_, _) => Open(activity, release))!
#endif
.SetNegativeButton(Resource.String.update_no, (_, _) => { })!
.Show();
}
catch (Exception failed) when (Failed(failed))
{
Log.Write($"Updates: {failed.Message}");
if (asked)
{
Tell(activity, Say(activity, Resource.String.update_failed, failed.Message));
}
}
finally
{
checking = false;
}
}
#if SELF_INSTALL
/// <summary>
/// The installer's word on the install, brought back to the app: it needs
/// the user's yes (Android's own dialog, started here), or it failed.
/// </summary>
public static void Installed(Activity activity, Intent intent)
{
var status = (PackageInstallStatus)intent.GetIntExtra(PackageInstaller.ExtraStatus, (int)PackageInstallStatus.Failure);
if (status == PackageInstallStatus.PendingUserAction && intent.GetParcelableExtra(Intent.ExtraIntent, Java.Lang.Class.FromType(typeof(Intent))) is Intent confirm)
{
activity.StartActivity(confirm.AddFlags(ActivityFlags.NewTask));
}
else if (status != PackageInstallStatus.Success)
{
var message = intent.GetStringExtra(PackageInstaller.ExtraStatusMessage) ?? status.ToString();
Log.Write($"Updates: the install failed: {message}");
Tell(activity, Say(activity, Resource.String.update_failed, message));
}
}
/// <summary>The release's APK downloaded into the app's cache and written into an install session, which Android then asks the user to confirm.</summary>
private static async Task InstallAsync(Activity activity, Updates.Release release)
{
try
{
var apk = await Updates.DownloadAsync(release, activity.CacheDir!.AbsolutePath);
var installer = activity.PackageManager!.PackageInstaller;
var id = installer.CreateSession(new PackageInstaller.SessionParams(PackageInstallMode.FullInstall));
using var session = installer.OpenSession(id);
await using (var source = System.IO.File.OpenRead(apk))
using (var target = session.OpenWrite(File, 0, source.Length))
{
await source.CopyToAsync(target);
session.Fsync(target);
}
System.IO.File.Delete(apk);
var told = new Intent(activity, typeof(MainActivity)).PutExtra(InstallExtra, true).AddFlags(ActivityFlags.SingleTop);
// Mutable: the installer adds its status to it.
var status = PendingIntent.GetActivity(activity, id, told, PendingIntentFlags.Mutable | PendingIntentFlags.UpdateCurrent)!;
session.Commit(status.IntentSender!);
Log.Write($"Updates: {release.Version} handed to Android's installer");
}
catch (Exception failed) when (Failed(failed) || failed is Java.Lang.Exception)
{
Log.Write($"Updates: {failed.Message}");
Tell(activity, Say(activity, Resource.String.update_failed, failed.Message));
}
}
#else
/// <summary>The release's page on GitHub opened in the browser: what it brings, and its APK to download and install.</summary>
public static void Open(Activity activity, Updates.Release release)
{
try
{
activity.StartActivity(new Intent(Intent.ActionView, Android.Net.Uri.Parse(release.Page)));
Log.Write($"Updates: {release.Version} opened in the browser");
}
catch (ActivityNotFoundException failed)
{
Log.Write($"Updates: {failed.Message}");
Tell(activity, Say(activity, Resource.String.update_failed, failed.Message ?? failed.GetType().Name));
}
}
#endif
private static void Notify(Context context, Updates.Release release)
{
var notifications = (NotificationManager)context.GetSystemService(Context.NotificationService)!;
notifications.CreateNotificationChannel(new NotificationChannel(Channel, context.GetString(Resource.String.update_title), NotificationImportance.Default));
var open = new Intent(context, typeof(MainActivity)).PutExtra(AskExtra, true).AddFlags(ActivityFlags.NewTask | ActivityFlags.SingleTop);
var text = Say(context, Resource.String.update_ask, release.Version.ToString(), Running(context));
notifications.Notify(NotificationId, new Notification.Builder(context, Channel)
.SetSmallIcon(Resource.Drawable.ic_keyplus)!
.SetContentTitle(context.GetString(Resource.String.update_title))!
.SetContentText(text)!
.SetStyle(new Notification.BigTextStyle().BigText(text))!
.SetContentIntent(PendingIntent.GetActivity(context, NotificationId, open, PendingIntentFlags.Immutable | PendingIntentFlags.UpdateCurrent))!
.SetAutoCancel(true)!
.Build()!);
}
/// <summary>A text with its %1$s and on filled in.</summary>
private static string Say(Context context, int text, params string[] values) =>
context.GetString(text, [.. values.Select(value => new Java.Lang.String(value))]);
private static void Tell(Activity activity, string message) =>
new AlertDialog.Builder(activity).SetTitle(Resource.String.update_title)!.SetMessage(message)!.SetPositiveButton(Android.Resource.String.Ok, (_, _) => { })!.Show();
private static DateTime? Checked(Context context) =>
KeyPlusPreferences.Global(context).GetLong(KeyPlusPreferences.UpdatesCheckedKey, 0) is > 0 and var at ? DateTimeOffset.FromUnixTimeMilliseconds(at).UtcDateTime : null;
private static void KeepChecked(Context context) =>
KeyPlusPreferences.Global(context).Edit()!.PutLong(KeyPlusPreferences.UpdatesCheckedKey, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!.Apply();
private static bool Failed(Exception failed) => failed is HttpRequestException or TaskCanceledException or IOException or JsonException
or KeyNotFoundException or InvalidOperationException or FormatException;
}