Car widget: where the car is parked, from a Traccar server, on a map
A new widget of the launcher's own, drawn by the launcher like the picture and clock widgets. It shows a map of the streets around the car with the car in the middle, the street, and how long the car has stood there, or how fast it drives. A tap opens directions to the car in the maps app. - Traccar: the owner's own server, over HTTPS only, signed in with a token made in Traccar. The latest position comes from /api/positions, and how long the car has been parked from the stops report. Redirects are not followed, so the token goes nowhere else. - The token is kept encrypted with a key in Android's keystore, and is not in backups. One sign-in serves every car widget; each widget follows one device. - Asked for only while a widget can be seen: every two minutes at most while the car is parked, more often while it drives, and less often after a failure. A token Traccar refused is not tried again until the owner signs in anew. - The street comes from Traccar when it has one, else from the phone's own address lookup, kept while the car stays within 40 m. - The map: OpenStreetMap's tiles, kept for a week and then checked again, two at a time at most, with the credit on the map. The map turns dark with the dark theme. - Options sheet: server, token, then the car, with messages for a wrong token, a server that is not Traccar, no HTTPS, a bad certificate, and Android 17's local network permission (the server may be at home). - Shaped like the other widgets: icon-aligned edges and the icon shape's corners. Short and wide, the lines go beside the car; the car keeps clear of the credit. - WidgetSight: the picture widget's "can it be seen" check, now shared. - About: the privacy text names the RSS reader and the car widget among what goes online. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3d50a166ec
commit
093a9d03e5
19 files changed
+2972
-51
No files matched your search
@@ -3,9 +3,10 @@
|
||||
Flexera Launcher manifest overrides. Attached to the debug and release build types in build.gradle,
|
||||
which outrank Lawnchair's flavor manifests and every library manifest during the merge.
|
||||
|
||||
Network access: the INTERNET permission comes from Lawnchair's manifest and is kept for one purpose,
|
||||
the app's own update check (app.flexera.update.FlexeraUpdater). Lawnchair's online features stay
|
||||
switched off in code; see app.flexera.FlexeraNetwork.
|
||||
Network access: the INTERNET permission comes from Lawnchair's manifest and is kept for the
|
||||
launcher's own features: the update check (app.flexera.update.FlexeraUpdater), and what the owner
|
||||
sets up (the clock's weather, the RSS reader, the car widget's Traccar server and map).
|
||||
Lawnchair's online features stay switched off in code; see app.flexera.FlexeraNetwork.
|
||||
-->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
@@ -16,7 +17,8 @@
|
||||
<!--
|
||||
Since Android 17 an app needs this to reach a device on the network the phone itself is on.
|
||||
The update server can be such a device: at the owner's home its name leads to its address
|
||||
on the home network. Asked for only when a check for updates is stopped by it (About screen).
|
||||
on the home network. Asked for only when a check for updates is stopped by it (About screen),
|
||||
and likewise for an RSS feed or the car widget's Traccar server.
|
||||
-->
|
||||
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />
|
||||
|
||||
@@ -58,6 +60,27 @@
|
||||
android:exported="false"
|
||||
android:theme="@style/Theme.Transparent" />
|
||||
|
||||
<!-- The car widget that comes with the launcher: where the car is, from a Traccar server. -->
|
||||
<receiver
|
||||
android:name="app.flexera.widget.CarWidgetProvider"
|
||||
android:exported="false"
|
||||
android:label="@string/flexera_car_widget">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.appwidget.provider"
|
||||
android:resource="@xml/flexera_car_widget_info" />
|
||||
</receiver>
|
||||
|
||||
<!-- The car widget's options (Traccar sign-in, the car), a sheet over the home screen. -->
|
||||
<activity
|
||||
android:name="app.flexera.widget.CarWidgetConfigActivity"
|
||||
android:excludeFromRecents="true"
|
||||
android:exported="false"
|
||||
android:theme="@style/Theme.Transparent"
|
||||
android:windowSoftInputMode="adjustResize" />
|
||||
|
||||
<!-- Opens Android's photo picker for the picture widget; it has no screen of its own. -->
|
||||
<activity
|
||||
android:name="app.flexera.widget.PictureWidgetConfigActivity"
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Streets, a park and a car on a rounded plate: the stand-in for the car widget's map. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="120dp"
|
||||
android:height="120dp"
|
||||
android:viewportWidth="120"
|
||||
android:viewportHeight="120">
|
||||
<path
|
||||
android:fillColor="#FFEEF0F3"
|
||||
android:pathData="M28,0h64a28,28 0,0 1,28 28v64a28,28 0,0 1,-28 28h-64a28,28 0,0 1,-28 -28v-64a28,28 0,0 1,28 -28z" />
|
||||
<path
|
||||
android:fillColor="#FFCDE8CF"
|
||||
android:pathData="M76,8h34a10,10 0,0 1,10 10v28h-44z" />
|
||||
<path
|
||||
android:pathData="M0,68L120,54M24,0L36,120"
|
||||
android:strokeWidth="8"
|
||||
android:strokeColor="#FFFFFFFF" />
|
||||
<path
|
||||
android:fillColor="#FF5B6B95"
|
||||
android:pathData="M60,60m-14,0a14,14 0,1 1,28 0a14,14 0,1 1,-28 0" />
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M66.9,54.5C66.7,54 66.2,53.6 65.6,53.6h-11.2c-0.6,0 -1.1,0.4 -1.3,0.9L51.2,60v6.5c0,0.5 0.4,0.9 0.9,0.9h0.9c0.5,0 0.9,-0.4 0.9,-0.9v-0.9h12.2v0.9c0,0.5 0.4,0.9 0.9,0.9h0.9c0.5,0 0.9,-0.4 0.9,-0.9V60zM54.4,63.7c-0.7,0 -1.3,-0.6 -1.3,-1.3s0.6,-1.3 1.3,-1.3 1.3,0.6 1.3,1.3 -0.6,1.3 -1.3,1.3zM65.6,63.7c-0.7,0 -1.3,-0.6 -1.3,-1.3s0.6,-1.3 1.3,-1.3 1.3,0.6 1.3,1.3 -0.6,1.3 -1.3,1.3zM53.1,59.1l1.4,-4.1h11l1.4,4.1z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
A car, seen from the front: the mark of the car widget's car (app.flexera.widget.CarWidgetView),
|
||||
tinted there. Material Icons' "directions_car" (Apache License 2.0).
|
||||
-->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M18.92,6.01C18.72,5.42 18.16,5 17.5,5h-11c-0.66,0 -1.21,0.42 -1.42,1.01L3,12v8c0,0.55 0.45,1 1,1h1c0.55,0 1,-0.45 1,-1v-1h12v1c0,0.55 0.45,1 1,1h1c0.55,0 1,-0.45 1,-1v-8l-2.08,-5.99zM6.5,16c-0.83,0 -1.5,-0.67 -1.5,-1.5S5.67,13 6.5,13s1.5,0.67 1.5,1.5S7.33,16 6.5,16zM17.5,16c-0.83,0 -1.5,-0.67 -1.5,-1.5s0.67,-1.5 1.5,-1.5 1.5,0.67 1.5,1.5 -0.67,1.5 -1.5,1.5zM5,11l1.5,-4.5h11L19,11L5,11z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
What Android is told the car widget looks like before it has anything to show. Flexera
|
||||
Launcher never shows it: it draws the widget itself (app.flexera.widget.CarWidgetView).
|
||||
-->
|
||||
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<ImageView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:importantForAccessibility="no"
|
||||
android:scaleType="fitCenter"
|
||||
android:src="@drawable/flexera_car_widget_sample" />
|
||||
</FrameLayout>
|
||||
@@ -75,6 +75,10 @@
|
||||
<dimen name="flexera_picture_widget_hint_text_size">13sp</dimen>
|
||||
<dimen name="flexera_picture_widget_hint_margin">10dp</dimen>
|
||||
|
||||
<!-- The car widget's two lines: the street, and how the car stands (app.flexera.widget.CarWidgetView). -->
|
||||
<dimen name="flexera_car_widget_title_size">15sp</dimen>
|
||||
<dimen name="flexera_car_widget_detail_size">12sp</dimen>
|
||||
|
||||
<dimen name="flexera_drawer_header_height">34dp</dimen>
|
||||
<dimen name="flexera_drawer_header_padding_bottom">4dp</dimen>
|
||||
<dimen name="flexera_drawer_header_text_size">12sp</dimen>
|
||||
|
||||
@@ -84,7 +84,7 @@
|
||||
<string name="flexera_about_share_qr_description">QR code that downloads the latest version</string>
|
||||
<string name="flexera_about_privacy">Privacy</string>
|
||||
<string name="flexera_about_privacy_title">What goes online</string>
|
||||
<string name="flexera_about_privacy_body">Flexera Launcher goes online for two things. It asks its release page whether a newer version exists, about once a day, and downloads that version when you ask. And if you pick a place for the weather on a clock widget, it asks Open-Meteo, a weather service, for the weather there. Looking a place up sends the name you type and your phone\'s language; asking for its weather sends the place, to about a kilometre, and whether you use Celsius or Fahrenheit. Nothing else about you, your apps or your phone leaves it.</string>
|
||||
<string name="flexera_about_privacy_body">Flexera Launcher goes online only for these things. It asks its release page whether a newer version exists, about once a day, and downloads that version when you ask. If you pick a place for the weather on a clock widget, it asks Open-Meteo, a weather service, for the weather there. Looking a place up sends the name you type and your phone\'s language; asking for its weather sends the place, to about a kilometre, and whether you use Celsius or Fahrenheit. The RSS reader fetches the feeds you add, and the articles you open, from their own sites. A car widget asks your own Traccar server where the car is, while the widget is on screen, and fetches the map around the car from OpenStreetMap, which so sees which streets are shown; when Traccar gives no street name, your phone\'s own address lookup is asked for it. Nothing else about you, your apps or your phone leaves it.</string>
|
||||
|
||||
<!-- Lawnchair's wording promised web results and grid settings that this app does not have -->
|
||||
<string name="all_apps_device_search_hint">Search apps and more</string>
|
||||
@@ -225,6 +225,74 @@
|
||||
<string name="flexera_picture_widget_position">Picture %1$d of %2$d</string>
|
||||
<string name="flexera_picture_widget_unreadable">None of the chosen pictures could be read</string>
|
||||
|
||||
<!-- The car widget that comes with the launcher (app.flexera.widget.CarWidgetView): where the
|
||||
owner's car is, on a map, from their Traccar server -->
|
||||
<!-- Its name in the list of widgets -->
|
||||
<string name="flexera_car_widget">Car</string>
|
||||
<string name="flexera_car_widget_description">Where your car is parked, on a map, from your Traccar server</string>
|
||||
<!-- Stands for the car's name in the sample in the list of widgets, and where a car has no name -->
|
||||
<string name="flexera_car_widget_sample_name">Your car</string>
|
||||
<string name="flexera_car_widget_set_up">Tap to set up</string>
|
||||
<string name="flexera_car_widget_sign_in">Tap to sign in to Traccar again</string>
|
||||
<string name="flexera_car_widget_local_network">Tap to allow local network access</string>
|
||||
<string name="flexera_car_widget_looking">Looking for the car…</string>
|
||||
<string name="flexera_car_widget_no_position">Traccar has no position for it yet</string>
|
||||
<string name="flexera_car_widget_unreachable">Can\'t reach Traccar</string>
|
||||
<string name="flexera_car_widget_parked">Parked</string>
|
||||
<!-- %1$s is how long, such as "2 hr, 15 min" -->
|
||||
<string name="flexera_car_widget_parked_for">Parked for %1$s</string>
|
||||
<!-- %1$s is a day and time, such as "Mon 14:20", or a date -->
|
||||
<string name="flexera_car_widget_parked_since">Parked since %1$s</string>
|
||||
<string name="flexera_car_widget_parked_over_week">Parked for over a week</string>
|
||||
<string name="flexera_car_widget_driving">Driving</string>
|
||||
<!-- %1$s is the speed, such as "54 km/h" -->
|
||||
<string name="flexera_car_widget_driving_speed">Driving, %1$s</string>
|
||||
<!-- After the car's place, when Traccar has not been reached for a while. %1$s is a time -->
|
||||
<string name="flexera_car_widget_updated">updated %1$s</string>
|
||||
<!-- The map's credit, shown on it as OpenStreetMap asks -->
|
||||
<string name="flexera_car_widget_attribution" translatable="false">© OpenStreetMap</string>
|
||||
<!-- Read by screen readers as what a tap does. %1$s is the car's name -->
|
||||
<string name="flexera_car_widget_directions">Show the way to %1$s</string>
|
||||
<string name="flexera_car_widget_open_options">Open the car widget\'s options</string>
|
||||
<string name="flexera_car_widget_ask_again">Ask Traccar again</string>
|
||||
<string name="flexera_car_widget_no_map_app">No app here can show the way</string>
|
||||
|
||||
<!-- The car widget's options (app.flexera.widget.CarWidgetConfigActivity) -->
|
||||
<string name="flexera_car_config_server_heading">Traccar server</string>
|
||||
<string name="flexera_car_config_server">Server address</string>
|
||||
<string name="flexera_car_config_server_hint" translatable="false">traccar.example.com</string>
|
||||
<string name="flexera_car_config_token">Token</string>
|
||||
<string name="flexera_car_config_token_show">Show</string>
|
||||
<string name="flexera_car_config_token_hide">Hide</string>
|
||||
<string name="flexera_car_config_token_keep">Leave empty to keep the token you gave before</string>
|
||||
<string name="flexera_car_config_token_help">Make a token in Traccar, in your account\'s settings. Safest is a Traccar user of its own for this, one that can see only your car: the token can do no more than that user can.</string>
|
||||
<!-- Button -->
|
||||
<string name="flexera_car_config_connect">Connect</string>
|
||||
<string name="flexera_car_config_cancel">Cancel</string>
|
||||
<!-- %1$s is the server\'s name -->
|
||||
<string name="flexera_car_config_connected">Connected to %1$s</string>
|
||||
<string name="flexera_car_config_change">Change</string>
|
||||
<string name="flexera_car_config_car_heading">Car</string>
|
||||
<string name="flexera_car_config_online">Online</string>
|
||||
<string name="flexera_car_config_offline">Offline</string>
|
||||
<string name="flexera_car_config_no_devices">This Traccar user can\'t see any devices.</string>
|
||||
<!-- %1$s is the name of the car the widget followed -->
|
||||
<string name="flexera_car_config_car_missing">%1$s isn\'t in this list any more. Pick a car above.</string>
|
||||
<string name="flexera_car_config_done">Done</string>
|
||||
<string name="flexera_car_config_try_again">Try again</string>
|
||||
<string name="flexera_car_config_allow_local_network">Allow local network access</string>
|
||||
<string name="flexera_car_config_problem_address">That isn\'t a web address.</string>
|
||||
<string name="flexera_car_config_problem_no_token">Enter the token from Traccar.</string>
|
||||
<string name="flexera_car_config_problem_token">Traccar didn\'t accept the token. It may be wrong or expired, or its user disabled.</string>
|
||||
<string name="flexera_car_config_problem_not_traccar">Something answered at that address, but not Traccar.</string>
|
||||
<string name="flexera_car_config_problem_https">The address has to start with https. The token isn\'t sent over a connection that isn\'t encrypted.</string>
|
||||
<string name="flexera_car_config_problem_certificate">Android doesn\'t trust the server\'s certificate.</string>
|
||||
<string name="flexera_car_config_problem_local_network">The server is on the network your phone is on, and Android keeps the launcher off that network until you allow it.</string>
|
||||
<string name="flexera_car_config_problem_offline">Couldn\'t reach the server. Check the address and your connection.</string>
|
||||
<string name="flexera_car_config_problem_server">Traccar answered with an error.</string>
|
||||
<string name="flexera_car_config_problem_keystore">The token couldn\'t be stored safely on this phone, so it wasn\'t kept.</string>
|
||||
<string name="flexera_car_config_privacy">While a car widget is on screen, the launcher asks your Traccar server where the car is: every two minutes at most while it\'s parked, more often while it drives. The map comes from OpenStreetMap, which sees which streets are shown. When Traccar gives no street name, your phone\'s own address lookup is asked for it. The token is kept encrypted on this phone, and not in backups.</string>
|
||||
|
||||
<!-- Updates section of the About screen (app.flexera.update.FlexeraUpdater) -->
|
||||
<string name="flexera_update_heading">Updates</string>
|
||||
<!-- Button -->
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Flexera Launcher's car widget (app.flexera.widget.CarWidgetProvider). Two cells by two when
|
||||
first placed, resizable down to one cell and up to the whole screen. The launcher draws it
|
||||
itself, so the layouts named here are never shown on the home screen; previewLayout is what
|
||||
makes the widget list ask for a live preview, which the launcher also draws. It has to be set
|
||||
up when it is added (sign in to Traccar, pick the car); its edit button opens those options again.
|
||||
-->
|
||||
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:minWidth="110dp"
|
||||
android:minHeight="110dp"
|
||||
android:minResizeWidth="40dp"
|
||||
android:minResizeHeight="40dp"
|
||||
android:targetCellWidth="2"
|
||||
android:targetCellHeight="2"
|
||||
android:updatePeriodMillis="0"
|
||||
android:description="@string/flexera_car_widget_description"
|
||||
android:configure="app.flexera.widget.CarWidgetConfigActivity"
|
||||
android:initialLayout="@layout/flexera_car_widget_placeholder"
|
||||
android:previewLayout="@layout/flexera_car_widget_placeholder"
|
||||
android:resizeMode="horizontal|vertical"
|
||||
android:widgetCategory="home_screen"
|
||||
android:widgetFeatures="reconfigurable" />
|
||||
@@ -0,0 +1,359 @@
|
||||
package app.flexera.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.location.Address
|
||||
import android.location.Geocoder
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import androidx.annotation.WorkerThread
|
||||
import com.android.launcher3.util.Executors
|
||||
import java.io.IOException
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.CopyOnWriteArraySet
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Where each car of the car widgets is: its last position from the owner's Traccar server
|
||||
* ([Traccar]), the street it stands in, and since when it has stood there.
|
||||
*
|
||||
* The server is asked only while a car widget is in view, at most every [FRESH_PARKED_MS] while
|
||||
* the car stands still and every [FRESH_MOVING_MS] while it drives; after a request that failed,
|
||||
* at intervals that grow from [RETRY_MS] to [RETRY_MAX_MS]. The last answer is kept, so that the
|
||||
* car is on the map at once and stays there through a spell offline: a parked car's place does
|
||||
* not go out of date.
|
||||
*
|
||||
* The street comes from the server when it looks addresses up itself, else from the phone's own
|
||||
* address lookup ([Geocoder]), asked once for each place the car stops at. Since when the car
|
||||
* stands still comes from Traccar's stops report, asked once when the car stops and again now and
|
||||
* then ([STOP_RECHECK_MS]).
|
||||
*/
|
||||
internal object CarLocation {
|
||||
|
||||
/** What is known of a car. */
|
||||
data class Reading(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
/** When the tracker took the position, in milliseconds since 1970. */
|
||||
val fixTime: Long,
|
||||
val moving: Boolean,
|
||||
val speedKnots: Double,
|
||||
/** The street, as short as it can be said ("Ilica 42"); null when none is known. */
|
||||
val street: String?,
|
||||
/** Since when the car stands where it is; 0 while that is not known, or while it drives. */
|
||||
val parkedSince: Long,
|
||||
/** True when it already stood there at the start of the stops report ([STOP_WINDOW_MS]). */
|
||||
val parkedLonger: Boolean,
|
||||
/** When the server last answered, in milliseconds since 1970. */
|
||||
val readAt: Long,
|
||||
/** When the stops report was last asked; 0 for never. */
|
||||
val stopsAskedAt: Long,
|
||||
/** Where the [street] was found, so that it is not looked up again while the car stays. */
|
||||
val streetLatitude: Double,
|
||||
val streetLongitude: Double,
|
||||
)
|
||||
|
||||
/** How a car stands, for the widget: a reading, nothing yet, or a problem in the way. */
|
||||
class State(val reading: Reading?, val problem: Traccar.Problem?, val noPosition: Boolean, val asking: Boolean)
|
||||
|
||||
/** Told, on the main thread, that something new is known about a car. */
|
||||
fun interface Listener {
|
||||
fun onCarLocationChanged(deviceId: Long)
|
||||
}
|
||||
|
||||
private const val TAG = "CarLocation"
|
||||
private const val FILE = "flexera_car_location"
|
||||
|
||||
/** How old a reading may be before the server is asked again, while the car stands and while it drives. */
|
||||
private const val FRESH_PARKED_MS = 2 * 60 * 1000L
|
||||
private const val FRESH_MOVING_MS = 20 * 1000L
|
||||
|
||||
/** The first wait after a failed request, doubled for each failure in a row up to [RETRY_MAX_MS]. */
|
||||
private const val RETRY_MS = 60 * 1000L
|
||||
private const val RETRY_MAX_MS = 15 * 60 * 1000L
|
||||
|
||||
/** How far back the stops report looks. A car parked longer than this is "parked for over a week". */
|
||||
const val STOP_WINDOW_MS = 7 * 24 * 60 * 60 * 1000L
|
||||
|
||||
/**
|
||||
* How often the stops report is asked again while the car stands still: when the start of the
|
||||
* stop is not known yet (Traccar counts a stop only after some minutes), and when it is, in
|
||||
* case the car went and came back between two looks.
|
||||
*/
|
||||
private const val STOP_RETRY_MS = 4 * 60 * 1000L
|
||||
private const val STOP_RECHECK_MS = 30 * 60 * 1000L
|
||||
|
||||
/** How near the car must be to a stop of the report for it to be the stop it is in now. */
|
||||
private const val STOP_RADIUS_M = 150.0
|
||||
|
||||
/** How much earlier than the car's last position the stop may end and still be the one going on. */
|
||||
private const val STOP_END_SLACK_MS = 10 * 60 * 1000L
|
||||
|
||||
/** How near the start of the report a stop must start to have started before it. */
|
||||
private const val STOP_CLIPPED_MS = 60 * 1000L
|
||||
|
||||
/** How far the car may be from where its street was found for the street to stay. */
|
||||
private const val STREET_RADIUS_M = 40.0
|
||||
|
||||
private class Failure(val at: Long, val inARow: Int, val problem: Traccar.Problem)
|
||||
|
||||
private val listeners = CopyOnWriteArraySet<Listener>()
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
// Guarded by [asking]: which devices are being asked for, the last failure of each, and
|
||||
// those for which Traccar had no position, with when it said so (elapsedRealtime).
|
||||
private val asking = HashSet<Long>()
|
||||
private val failures = HashMap<Long, Failure>()
|
||||
private val empty = HashMap<Long, Long>()
|
||||
|
||||
fun addListener(listener: Listener) {
|
||||
listeners.add(listener)
|
||||
}
|
||||
|
||||
fun removeListener(listener: Listener) {
|
||||
listeners.remove(listener)
|
||||
}
|
||||
|
||||
/** What is known of a car now, for the widget. */
|
||||
fun state(context: Context, deviceId: Long): State = synchronized(asking) {
|
||||
State(
|
||||
reading = reading(context, deviceId),
|
||||
problem = failures[deviceId]?.problem,
|
||||
noPosition = deviceId in empty.keys,
|
||||
asking = deviceId in asking,
|
||||
)
|
||||
}
|
||||
|
||||
/** The last reading of a car from the account signed in now; null when there is none. */
|
||||
fun reading(context: Context, deviceId: Long): Reading? {
|
||||
val account = CarWidgetStore.account(context) ?: return null
|
||||
val stored = prefs(context).getString(key(deviceId), null) ?: return null
|
||||
return try {
|
||||
val json = JSONObject(stored)
|
||||
if (json.optString("server") != account.server) return null
|
||||
Reading(
|
||||
latitude = json.getDouble("lat"),
|
||||
longitude = json.getDouble("lon"),
|
||||
fixTime = json.optLong("fix"),
|
||||
moving = json.optBoolean("moving"),
|
||||
speedKnots = json.optDouble("speed", 0.0),
|
||||
street = if (json.isNull("street")) null else json.optString("street").ifEmpty { null },
|
||||
parkedSince = json.optLong("since"),
|
||||
parkedLonger = json.optBoolean("longer"),
|
||||
readAt = json.optLong("read"),
|
||||
stopsAskedAt = json.optLong("stops"),
|
||||
streetLatitude = json.optDouble("streetLat", Double.NaN),
|
||||
streetLongitude = json.optDouble("streetLon", Double.NaN),
|
||||
)
|
||||
} catch (e: JSONException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the server for a car's position in the background, unless the last answer is fresh, a
|
||||
* request is on its way, or the last one failed too recently to try again. [now] asks even
|
||||
* when the last answer is fresh, as for a tap on a widget waiting for its first one.
|
||||
*/
|
||||
fun refreshIfStale(context: Context, deviceId: Long, now: Boolean = false) {
|
||||
val app = context.applicationContext
|
||||
val account = CarWidgetStore.account(app) ?: return
|
||||
val last = reading(app, deviceId)
|
||||
val fresh = if (last?.moving == true) FRESH_MOVING_MS else FRESH_PARKED_MS
|
||||
if (!now && last != null && System.currentTimeMillis() - last.readAt in 0 until fresh) return
|
||||
synchronized(asking) {
|
||||
// "No position yet" is an answer too, as fresh as a position would be.
|
||||
val emptyAt = empty[deviceId]
|
||||
if (!now && emptyAt != null && SystemClock.elapsedRealtime() - emptyAt < FRESH_PARKED_MS) return
|
||||
val failure = failures[deviceId]
|
||||
if (failure != null) {
|
||||
// A token Traccar refused is not tried again until the owner signs in anew.
|
||||
if (failure.problem == Traccar.Problem.TOKEN) return
|
||||
if (SystemClock.elapsedRealtime() - failure.at < retryAfter(failure.inARow)) return
|
||||
}
|
||||
if (!asking.add(deviceId)) return
|
||||
}
|
||||
tell(deviceId)
|
||||
Executors.THREAD_POOL_EXECUTOR.execute {
|
||||
try {
|
||||
val position = Traccar.latestPosition(app, account, deviceId)
|
||||
synchronized(asking) {
|
||||
failures.remove(deviceId)
|
||||
if (position == null) empty[deviceId] = SystemClock.elapsedRealtime() else empty.remove(deviceId)
|
||||
}
|
||||
if (position != null) store(app, account, deviceId, read(app, account, deviceId, position, last))
|
||||
} catch (e: Traccar.TraccarException) {
|
||||
synchronized(asking) {
|
||||
failures[deviceId] = Failure(SystemClock.elapsedRealtime(), (failures[deviceId]?.inARow ?: 0) + 1, e.problem)
|
||||
}
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "No position this time", e)
|
||||
synchronized(asking) {
|
||||
failures[deviceId] = Failure(SystemClock.elapsedRealtime(), (failures[deviceId]?.inARow ?: 0) + 1, Traccar.Problem.SERVER)
|
||||
}
|
||||
} finally {
|
||||
synchronized(asking) { asking.remove(deviceId) }
|
||||
tell(deviceId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forgets every car's reading and failures, as when the owner signs in to another server or
|
||||
* with another token: that one may see other cars, or none.
|
||||
*/
|
||||
fun forget(context: Context) {
|
||||
prefs(context).edit().clear().apply()
|
||||
forgetFailures()
|
||||
}
|
||||
|
||||
/** Forgets the failures, so that every car is asked for at once: the owner has just signed in. */
|
||||
fun forgetFailures() {
|
||||
synchronized(asking) {
|
||||
failures.clear()
|
||||
empty.clear()
|
||||
}
|
||||
}
|
||||
|
||||
/** A new reading from [position], with what [last] knew that still holds. */
|
||||
@WorkerThread
|
||||
private fun read(context: Context, account: Traccar.Account, deviceId: Long, position: Traccar.Position, last: Reading?): Reading {
|
||||
val now = System.currentTimeMillis()
|
||||
|
||||
// The street: the server's, or the last one found while the car is still near where it
|
||||
// was found, or the phone's lookup.
|
||||
var streetLatitude = position.latitude
|
||||
var streetLongitude = position.longitude
|
||||
val street = position.address?.let(::streetOf)
|
||||
?: last?.takeIf {
|
||||
it.street != null && distance(it.streetLatitude, it.streetLongitude, position.latitude, position.longitude) <= STREET_RADIUS_M
|
||||
}?.let {
|
||||
streetLatitude = it.streetLatitude
|
||||
streetLongitude = it.streetLongitude
|
||||
it.street
|
||||
}
|
||||
?: lookUpStreet(context, position.latitude, position.longitude)
|
||||
|
||||
// Since when it stands here.
|
||||
var since = 0L
|
||||
var longer = false
|
||||
var stopsAskedAt = last?.stopsAskedAt ?: 0L
|
||||
if (!position.moving) {
|
||||
// Standing where it stood at the last look: what was known of the stop holds.
|
||||
val samePlace = last != null && !last.moving &&
|
||||
distance(last.latitude, last.longitude, position.latitude, position.longitude) <= STOP_RADIUS_M
|
||||
val stillThere = samePlace && last.parkedSince > 0
|
||||
if (stillThere) {
|
||||
since = last.parkedSince
|
||||
longer = last.parkedLonger
|
||||
}
|
||||
val due = if (stillThere) STOP_RECHECK_MS else STOP_RETRY_MS
|
||||
if (!samePlace || now - stopsAskedAt !in 0 until due) {
|
||||
stopsAskedAt = now
|
||||
try {
|
||||
val from = now - STOP_WINDOW_MS
|
||||
val stop = Traccar.lastStop(context, account, deviceId, from, now)
|
||||
val current = stop != null &&
|
||||
stop.end >= position.fixTime - STOP_END_SLACK_MS &&
|
||||
distance(stop.latitude, stop.longitude, position.latitude, position.longitude) <= STOP_RADIUS_M
|
||||
if (current) {
|
||||
since = stop.start
|
||||
longer = stop.start - from < STOP_CLIPPED_MS
|
||||
} else if (!stillThere) {
|
||||
since = 0L
|
||||
}
|
||||
} catch (e: Traccar.TraccarException) {
|
||||
// The report may be switched off for this user; the car is shown without it.
|
||||
Log.w(TAG, "No stops report: ${e.problem}")
|
||||
}
|
||||
}
|
||||
}
|
||||
return Reading(
|
||||
latitude = position.latitude,
|
||||
longitude = position.longitude,
|
||||
fixTime = position.fixTime,
|
||||
moving = position.moving,
|
||||
speedKnots = position.speedKnots,
|
||||
street = street,
|
||||
parkedSince = since,
|
||||
parkedLonger = longer,
|
||||
readAt = now,
|
||||
stopsAskedAt = stopsAskedAt,
|
||||
streetLatitude = if (street == null) Double.NaN else streetLatitude,
|
||||
streetLongitude = if (street == null) Double.NaN else streetLongitude,
|
||||
)
|
||||
}
|
||||
|
||||
private fun store(context: Context, account: Traccar.Account, deviceId: Long, reading: Reading) {
|
||||
val json = JSONObject()
|
||||
.put("server", account.server)
|
||||
.put("lat", reading.latitude)
|
||||
.put("lon", reading.longitude)
|
||||
.put("fix", reading.fixTime)
|
||||
.put("moving", reading.moving)
|
||||
.put("speed", reading.speedKnots)
|
||||
.put("street", reading.street ?: JSONObject.NULL)
|
||||
.put("since", reading.parkedSince)
|
||||
.put("longer", reading.parkedLonger)
|
||||
.put("read", reading.readAt)
|
||||
.put("stops", reading.stopsAskedAt)
|
||||
if (reading.streetLatitude.isFinite() && reading.streetLongitude.isFinite()) {
|
||||
json.put("streetLat", reading.streetLatitude).put("streetLon", reading.streetLongitude)
|
||||
}
|
||||
prefs(context).edit().putString(key(deviceId), json.toString()).apply()
|
||||
}
|
||||
|
||||
/** The first part of an address, where the street and the house number are: "Ilica 42". */
|
||||
private fun streetOf(address: String): String? = address.substringBefore(',').trim().ifEmpty { null }
|
||||
|
||||
/**
|
||||
* The street at a place, from the phone's own address lookup; null when the phone has none,
|
||||
* is offline, or knows no address there.
|
||||
*/
|
||||
@WorkerThread
|
||||
@Suppress("DEPRECATION")
|
||||
private fun lookUpStreet(context: Context, latitude: Double, longitude: Double): String? {
|
||||
if (!Geocoder.isPresent()) return null
|
||||
return try {
|
||||
val found: Address = Geocoder(context, Locale.getDefault())
|
||||
.getFromLocation(latitude, longitude, 1)?.firstOrNull() ?: return null
|
||||
found.getAddressLine(0)?.let(::streetOf) ?: found.thoroughfare
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "No street from the phone's address lookup: ${e.message}")
|
||||
null
|
||||
} catch (e: IllegalArgumentException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** The distance between two places in metres, along the earth's surface. */
|
||||
internal fun distance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
|
||||
if (!lat1.isFinite() || !lon1.isFinite() || !lat2.isFinite() || !lon2.isFinite()) return Double.MAX_VALUE
|
||||
val p1 = Math.toRadians(lat1)
|
||||
val p2 = Math.toRadians(lat2)
|
||||
val dp = p2 - p1
|
||||
val dl = Math.toRadians(lon2 - lon1)
|
||||
val a = sin(dp / 2) * sin(dp / 2) + cos(p1) * cos(p2) * sin(dl / 2) * sin(dl / 2)
|
||||
return EARTH_RADIUS_M * 2 * atan2(sqrt(a), sqrt(1 - a))
|
||||
}
|
||||
|
||||
private const val EARTH_RADIUS_M = 6_371_000.0
|
||||
|
||||
private fun retryAfter(inARow: Int): Long =
|
||||
(RETRY_MS shl (inARow - 1).coerceIn(0, 8)).coerceAtMost(RETRY_MAX_MS)
|
||||
|
||||
private fun tell(deviceId: Long) {
|
||||
main.post { listeners.forEach { it.onCarLocationChanged(deviceId) } }
|
||||
}
|
||||
|
||||
private fun key(deviceId: Long) = "car_$deviceId"
|
||||
|
||||
private fun prefs(context: Context) =
|
||||
context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
package app.flexera.widget
|
||||
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.selection.selectableGroup
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.LiveRegionMode
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.liveRegion
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import app.flexera.update.FlexeraUpdater
|
||||
import app.lawnchair.ui.theme.EdgeToEdge
|
||||
import app.lawnchair.ui.theme.LawnchairTheme
|
||||
import com.android.launcher3.R
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* The car widget's options: the Traccar server and the token the launcher signs in with, once for
|
||||
* all car widgets, and the car this widget follows, picked from the devices Traccar lists. A sheet
|
||||
* over the home screen, as the clock's options are.
|
||||
*
|
||||
* Android opens it when the widget is put on the home screen, and the widget's edit button opens
|
||||
* it again; the widget opens it itself when it is not set up, when Traccar refuses the token, and
|
||||
* when Android 17 keeps the launcher off the home network the server is on. A widget being added
|
||||
* stays on the home screen only once it has a car.
|
||||
*/
|
||||
class CarWidgetConfigActivity : ComponentActivity() {
|
||||
|
||||
private var widget = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
widget = intent?.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)
|
||||
?: AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
if (widget == AppWidgetManager.INVALID_APPWIDGET_ID) {
|
||||
setResult(RESULT_CANCELED)
|
||||
finish()
|
||||
return
|
||||
}
|
||||
updateResult()
|
||||
|
||||
setContent {
|
||||
LawnchairTheme {
|
||||
EdgeToEdge()
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = { finish() },
|
||||
sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
// No dimming: what shows of the home screen above the sheet stays as it is.
|
||||
scrimColor = Color.Transparent,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.imePadding()
|
||||
.padding(start = 24.dp, end = 24.dp, bottom = 32.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(id = R.string.flexera_car_widget),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
CarOptions(widget = widget, onChanged = ::updateResult, onDone = ::finish)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Leaving says yes once the widget has an account and a car; a widget being added without them is dropped. */
|
||||
private fun updateResult() {
|
||||
val ready = CarWidgetStore.account(this) != null && CarWidgetStore.car(this, widget) != null
|
||||
setResult(if (ready) RESULT_OK else RESULT_CANCELED, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widget))
|
||||
}
|
||||
}
|
||||
|
||||
/** How signing in went. */
|
||||
private sealed interface SignIn {
|
||||
data object Idle : SignIn
|
||||
data object Running : SignIn
|
||||
|
||||
/** [message] says what went wrong; [problem] is Traccar's, when it came that far. */
|
||||
data class Failed(@StringRes val message: Int, val problem: Traccar.Problem? = null) : SignIn
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CarOptions(widget: Int, onChanged: () -> Unit, onDone: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
val focus = LocalFocusManager.current
|
||||
|
||||
var account by remember { mutableStateOf(CarWidgetStore.account(context)) }
|
||||
var editing by rememberSaveable { mutableStateOf(account == null) }
|
||||
var server by rememberSaveable { mutableStateOf(account?.server?.removePrefix("https://").orEmpty()) }
|
||||
// Not kept with the screen's saved state, so that the token is not written out with it.
|
||||
var token by remember { mutableStateOf("") }
|
||||
var tokenShown by remember { mutableStateOf(false) }
|
||||
var signIn by remember { mutableStateOf<SignIn>(SignIn.Idle) }
|
||||
var attempts by remember { mutableIntStateOf(0) }
|
||||
|
||||
var devices by remember { mutableStateOf<List<Traccar.Device>?>(null) }
|
||||
var listing by remember { mutableStateOf(false) }
|
||||
var listProblem by remember { mutableStateOf<Traccar.Problem?>(null) }
|
||||
var chosen by remember { mutableStateOf(CarWidgetStore.car(context, widget)) }
|
||||
|
||||
val choose = { device: Traccar.Device ->
|
||||
val car = CarWidgetStore.Car(device.id, device.name)
|
||||
CarWidgetStore.setCar(context, widget, car)
|
||||
chosen = car
|
||||
onChanged()
|
||||
}
|
||||
|
||||
val list = { signedIn: Traccar.Account ->
|
||||
listing = true
|
||||
listProblem = null
|
||||
scope.launch {
|
||||
val result = withContext(Dispatchers.IO) { runCatching { Traccar.devices(context, signedIn) } }
|
||||
listing = false
|
||||
result.onSuccess { found ->
|
||||
devices = found
|
||||
if (chosen == null && found.size == 1) choose(found.first())
|
||||
}
|
||||
result.onFailure { error ->
|
||||
val problem = (error as? Traccar.TraccarException)?.problem ?: Traccar.Problem.SERVER
|
||||
if (problem == Traccar.Problem.TOKEN) {
|
||||
// The token no longer works: sign in again, here.
|
||||
editing = true
|
||||
signIn = SignIn.Failed(R.string.flexera_car_config_problem_token, problem)
|
||||
} else {
|
||||
listProblem = problem
|
||||
}
|
||||
}
|
||||
}
|
||||
Unit
|
||||
}
|
||||
|
||||
val connect = connect@{
|
||||
if (signIn == SignIn.Running) return@connect
|
||||
val address = Traccar.normalize(server)
|
||||
if (address == null) {
|
||||
signIn = SignIn.Failed(R.string.flexera_car_config_problem_address)
|
||||
return@connect
|
||||
}
|
||||
// An empty token field keeps the token given before, for the same server.
|
||||
val key = token.trim().ifEmpty { account?.takeIf { it.server == address }?.token.orEmpty() }
|
||||
if (key.isEmpty()) {
|
||||
signIn = SignIn.Failed(R.string.flexera_car_config_problem_no_token)
|
||||
return@connect
|
||||
}
|
||||
if (!address.startsWith("https://")) {
|
||||
signIn = SignIn.Failed(problemText(Traccar.Problem.NOT_SECURE), Traccar.Problem.NOT_SECURE)
|
||||
return@connect
|
||||
}
|
||||
keyboard?.hide()
|
||||
focus.clearFocus()
|
||||
signIn = SignIn.Running
|
||||
attempts++
|
||||
val candidate = Traccar.Account(address, key)
|
||||
scope.launch {
|
||||
val result = withContext(Dispatchers.IO) { runCatching { Traccar.devices(context, candidate) } }
|
||||
result.onSuccess { found ->
|
||||
CarWidgetStore.setAccount(context, candidate)
|
||||
val kept = CarWidgetStore.account(context)
|
||||
if (kept == null) {
|
||||
signIn = SignIn.Failed(R.string.flexera_car_config_problem_keystore)
|
||||
return@onSuccess
|
||||
}
|
||||
account = kept
|
||||
server = kept.server.removePrefix("https://")
|
||||
token = ""
|
||||
tokenShown = false
|
||||
editing = false
|
||||
signIn = SignIn.Idle
|
||||
listProblem = null
|
||||
devices = found
|
||||
if (chosen == null && found.size == 1) choose(found.first())
|
||||
onChanged()
|
||||
}
|
||||
result.onFailure { error ->
|
||||
val problem = (error as? Traccar.TraccarException)?.problem ?: Traccar.Problem.SERVER
|
||||
signIn = SignIn.Failed(problemText(problem), problem)
|
||||
}
|
||||
}
|
||||
Unit
|
||||
}
|
||||
|
||||
// Android 17 asks before an app may reach a device on the phone's own network.
|
||||
val allowLocalNetwork = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (!granted) return@rememberLauncherForActivityResult
|
||||
if (editing) connect() else account?.let(list)
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
account?.let(list)
|
||||
}
|
||||
|
||||
Heading(R.string.flexera_car_config_server_heading)
|
||||
if (editing) {
|
||||
OutlinedTextField(
|
||||
value = server,
|
||||
onValueChange = { server = it },
|
||||
label = { Text(text = stringResource(id = R.string.flexera_car_config_server)) },
|
||||
placeholder = { Text(text = stringResource(id = R.string.flexera_car_config_server_hint)) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Next),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
OutlinedTextField(
|
||||
value = token,
|
||||
onValueChange = { token = it },
|
||||
label = { Text(text = stringResource(id = R.string.flexera_car_config_token)) },
|
||||
singleLine = true,
|
||||
visualTransformation = if (tokenShown) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done),
|
||||
keyboardActions = KeyboardActions(onDone = { connect() }),
|
||||
trailingIcon = {
|
||||
TextButton(onClick = { tokenShown = !tokenShown }) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
id = if (tokenShown) R.string.flexera_car_config_token_hide else R.string.flexera_car_config_token_show,
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
supportingText = if (account != null) {
|
||||
{ Text(text = stringResource(id = R.string.flexera_car_config_token_keep)) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text = stringResource(id = R.string.flexera_car_config_token_help),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Button(onClick = { connect() }, enabled = signIn != SignIn.Running) {
|
||||
Text(text = stringResource(id = R.string.flexera_car_config_connect))
|
||||
}
|
||||
if (account != null) {
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
TextButton(
|
||||
onClick = {
|
||||
editing = false
|
||||
signIn = SignIn.Idle
|
||||
token = ""
|
||||
},
|
||||
) {
|
||||
Text(text = stringResource(id = R.string.flexera_car_config_cancel))
|
||||
}
|
||||
}
|
||||
}
|
||||
// Each try gets a new note, which TalkBack reads out, also when it says what the last one did.
|
||||
key(attempts) {
|
||||
when (val state = signIn) {
|
||||
SignIn.Running -> LinearProgressIndicator(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 16.dp),
|
||||
)
|
||||
|
||||
is SignIn.Failed -> {
|
||||
Note(stringResource(id = state.message))
|
||||
if (state.problem == Traccar.Problem.LOCAL_NETWORK) {
|
||||
TextButton(onClick = { allowLocalNetwork.launch(FlexeraUpdater.LOCAL_NETWORK_PERMISSION) }) {
|
||||
Text(text = stringResource(id = R.string.flexera_car_config_allow_local_network))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SignIn.Idle -> Unit
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
text = stringResource(id = R.string.flexera_car_config_connected, account?.host.orEmpty()),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(
|
||||
onClick = {
|
||||
editing = true
|
||||
signIn = SignIn.Idle
|
||||
},
|
||||
) {
|
||||
Text(text = stringResource(id = R.string.flexera_car_config_change))
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
Heading(R.string.flexera_car_config_car_heading)
|
||||
val found = devices
|
||||
when {
|
||||
listing && found == null -> LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
|
||||
listProblem != null -> {
|
||||
val problem = listProblem!!
|
||||
Note(stringResource(id = problemText(problem)))
|
||||
Row {
|
||||
if (problem == Traccar.Problem.LOCAL_NETWORK) {
|
||||
TextButton(onClick = { allowLocalNetwork.launch(FlexeraUpdater.LOCAL_NETWORK_PERMISSION) }) {
|
||||
Text(text = stringResource(id = R.string.flexera_car_config_allow_local_network))
|
||||
}
|
||||
}
|
||||
TextButton(onClick = { account?.let(list) }) {
|
||||
Text(text = stringResource(id = R.string.flexera_car_config_try_again))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
found != null && found.isEmpty() -> Note(stringResource(id = R.string.flexera_car_config_no_devices))
|
||||
|
||||
found != null -> Column(modifier = Modifier.selectableGroup()) {
|
||||
found.forEach { device ->
|
||||
val selected = device.id == chosen?.deviceId
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 56.dp)
|
||||
.selectable(selected = selected, onClick = { choose(device) }, role = Role.RadioButton),
|
||||
) {
|
||||
RadioButton(selected = selected, onClick = null)
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
Column {
|
||||
Text(text = device.name, style = MaterialTheme.typography.bodyLarge)
|
||||
Text(
|
||||
text = stringResource(
|
||||
id = if (device.online) R.string.flexera_car_config_online else R.string.flexera_car_config_offline,
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
val picked = chosen
|
||||
if (picked != null && found.none { it.id == picked.deviceId }) {
|
||||
Note(stringResource(id = R.string.flexera_car_config_car_missing, picked.name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (chosen != null) {
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
Button(onClick = onDone, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(text = stringResource(id = R.string.flexera_car_config_done))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
Text(
|
||||
text = stringResource(id = R.string.flexera_car_config_privacy),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
@StringRes
|
||||
private fun problemText(problem: Traccar.Problem): Int = when (problem) {
|
||||
Traccar.Problem.TOKEN -> R.string.flexera_car_config_problem_token
|
||||
Traccar.Problem.NOT_TRACCAR -> R.string.flexera_car_config_problem_not_traccar
|
||||
Traccar.Problem.NOT_SECURE -> R.string.flexera_car_config_problem_https
|
||||
Traccar.Problem.CERTIFICATE -> R.string.flexera_car_config_problem_certificate
|
||||
Traccar.Problem.LOCAL_NETWORK -> R.string.flexera_car_config_problem_local_network
|
||||
Traccar.Problem.OFFLINE -> R.string.flexera_car_config_problem_offline
|
||||
Traccar.Problem.SERVER -> R.string.flexera_car_config_problem_server
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Heading(@StringRes text: Int) {
|
||||
Text(
|
||||
text = stringResource(id = text),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
/** What a try did. TalkBack reads it out as it appears: nothing else would say that it is there. */
|
||||
@Composable
|
||||
private fun Note(text: String) {
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier
|
||||
.padding(top = 12.dp)
|
||||
.semantics { liveRegion = LiveRegionMode.Polite },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package app.flexera.widget
|
||||
|
||||
import android.appwidget.AppWidgetProvider
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.android.launcher3.BuildConfig
|
||||
import com.android.launcher3.model.data.LauncherAppWidgetInfo
|
||||
|
||||
/**
|
||||
* The launcher's own car widget: where the owner's car is, on a map, from their Traccar server.
|
||||
* Android knows it as an ordinary app widget; the launcher draws it itself with a
|
||||
* [CarWidgetView]. Setting it up means signing in to Traccar once and picking the car
|
||||
* ([CarWidgetConfigActivity]); which car a widget follows is kept in [CarWidgetStore], under the
|
||||
* widget's id, and goes with the widget when a restore gives it a new one. See [FlexeraWidgets].
|
||||
*/
|
||||
class CarWidgetProvider : AppWidgetProvider() {
|
||||
|
||||
override fun onDeleted(context: Context, appWidgetIds: IntArray) {
|
||||
appWidgetIds.forEach { CarWidgetStore.delete(context, it) }
|
||||
}
|
||||
|
||||
/** After Android's own restore. */
|
||||
override fun onRestored(context: Context, oldWidgetIds: IntArray, newWidgetIds: IntArray) {
|
||||
CarWidgetStore.move(context, oldWidgetIds, newWidgetIds)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "CarWidgetProvider"
|
||||
|
||||
@JvmField
|
||||
val componentName = ComponentName(BuildConfig.APPLICATION_ID, CarWidgetProvider::class.java.name)
|
||||
|
||||
/**
|
||||
* Told by Launcher3 (WidgetInflater) that a widget of the home screen got a new id
|
||||
* because the one it had is no longer valid, as after a restore of the launcher's
|
||||
* backup; [oldAppWidgetId] is the id it had. As for the clock (ClockWidgetProvider), the
|
||||
* car goes to the new id before Launcher3 deletes the old one.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun onNewAppWidgetId(context: Context, item: LauncherAppWidgetInfo, oldAppWidgetId: Int) {
|
||||
val newId = item.appWidgetId
|
||||
if (item.providerName != componentName || oldAppWidgetId <= 0 || newId <= 0) return
|
||||
try {
|
||||
CarWidgetStore.move(context, intArrayOf(oldAppWidgetId), intArrayOf(newId))
|
||||
} catch (e: RuntimeException) {
|
||||
// Never in the way of loading the home screens.
|
||||
Log.w(TAG, "Car not handed to widget $newId", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Told by Launcher3 (LauncherWidgetHolder) that it deleted a widget id, of any widget.
|
||||
* Android calls onDeleted only for an id that was bound; a car widget removed while it
|
||||
* waited for "tap to set up" may have its car under one that was not.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun onAppWidgetIdDeleted(context: Context, appWidgetId: Int) {
|
||||
if (appWidgetId <= 0) return
|
||||
try {
|
||||
CarWidgetStore.delete(context, appWidgetId)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Car of widget $appWidgetId not removed", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package app.flexera.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import java.security.KeyStore
|
||||
import java.util.concurrent.CopyOnWriteArraySet
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/**
|
||||
* What the car widget ([CarWidgetProvider]) keeps: the Traccar server it reads from and the token
|
||||
* it signs in with, once for all car widgets, and for each widget the device it follows.
|
||||
*
|
||||
* The token is kept encrypted with a key that lives in Android's keystore and never leaves it.
|
||||
* None of this is in a backup (the launcher's backup rules name other files), and a copy of the
|
||||
* file on another phone could not be read without that key: after a restore the owner signs in
|
||||
* again.
|
||||
*/
|
||||
object CarWidgetStore {
|
||||
|
||||
/** The device a widget follows, with its name as it was when picked. */
|
||||
data class Car(val deviceId: Long, val name: String)
|
||||
|
||||
/**
|
||||
* Told, on the main thread, that a widget's car changed ([appWidgetId]), or that the account
|
||||
* did ([ALL]).
|
||||
*/
|
||||
fun interface Listener {
|
||||
fun onCarWidgetChanged(appWidgetId: Int)
|
||||
}
|
||||
|
||||
/** The [Listener] id for a change that concerns every car widget. */
|
||||
const val ALL = 0
|
||||
|
||||
private const val TAG = "CarWidgetStore"
|
||||
private const val FILE = "flexera_car_widget"
|
||||
private const val SERVER = "server"
|
||||
private const val TOKEN = "token"
|
||||
private const val DEVICE = "device_"
|
||||
private const val NAME = "name_"
|
||||
private val KEYS = listOf(DEVICE, NAME)
|
||||
|
||||
private val listeners = CopyOnWriteArraySet<Listener>()
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
/** The account as last read or written, so that the keystore is asked once per run. */
|
||||
@Volatile
|
||||
private var cached: Pair<String, Traccar.Account?>? = null
|
||||
|
||||
fun addListener(listener: Listener) {
|
||||
listeners.add(listener)
|
||||
}
|
||||
|
||||
fun removeListener(listener: Listener) {
|
||||
listeners.remove(listener)
|
||||
}
|
||||
|
||||
/** The Traccar server and token, or null when the owner has not signed in, or the token can no longer be read. */
|
||||
internal fun account(context: Context): Traccar.Account? {
|
||||
val prefs = prefs(context)
|
||||
val server = prefs.getString(SERVER, null) ?: return null
|
||||
val sealed = prefs.getString(TOKEN, null) ?: return null
|
||||
cached?.let { (key, account) -> if (key == "$server|$sealed") return account }
|
||||
val account = TokenVault.open(sealed)?.let { Traccar.Account(server, it) }
|
||||
cached = "$server|$sealed" to account
|
||||
return account
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs the car widgets in to [account], or out with null. The positions known from another
|
||||
* account are forgotten.
|
||||
*/
|
||||
internal fun setAccount(context: Context, account: Traccar.Account?) {
|
||||
val before = account(context)
|
||||
val edit = prefs(context).edit()
|
||||
if (account == null) {
|
||||
edit.remove(SERVER).remove(TOKEN)
|
||||
cached = null
|
||||
} else {
|
||||
val sealed = TokenVault.seal(account.token)
|
||||
if (sealed == null) {
|
||||
// Without the keystore the token is not kept at all, rather than kept readable.
|
||||
Log.w(TAG, "The token could not be encrypted; not kept")
|
||||
edit.remove(SERVER).remove(TOKEN)
|
||||
cached = null
|
||||
} else {
|
||||
edit.putString(SERVER, account.server).putString(TOKEN, sealed)
|
||||
cached = "${account.server}|$sealed" to account
|
||||
}
|
||||
}
|
||||
edit.apply()
|
||||
if (before != account) {
|
||||
CarLocation.forget(context)
|
||||
} else {
|
||||
// The same sign-in again, as after Traccar refused it and the owner put it right there.
|
||||
CarLocation.forgetFailures()
|
||||
}
|
||||
tell(ALL)
|
||||
}
|
||||
|
||||
/** The car a widget follows; null for a widget not set up. */
|
||||
fun car(context: Context, appWidgetId: Int): Car? {
|
||||
val prefs = prefs(context)
|
||||
val id = prefs.getString(DEVICE + appWidgetId, null)?.toLongOrNull() ?: return null
|
||||
return Car(id, prefs.getString(NAME + appWidgetId, null).orEmpty())
|
||||
}
|
||||
|
||||
fun setCar(context: Context, appWidgetId: Int, car: Car) {
|
||||
prefs(context).edit()
|
||||
.putString(DEVICE + appWidgetId, car.deviceId.toString())
|
||||
.putString(NAME + appWidgetId, car.name)
|
||||
.apply()
|
||||
tell(appWidgetId)
|
||||
}
|
||||
|
||||
/** Forgets the car of a widget that left the home screen. The account stays for the others. */
|
||||
fun delete(context: Context, appWidgetId: Int) {
|
||||
val edit = prefs(context).edit()
|
||||
for (key in KEYS) edit.remove(key + appWidgetId)
|
||||
edit.apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the car of each widget in [from] to the widget at the same place in [to]: the ids that
|
||||
* a restore gave the widgets in place of the ones they had. May be called on any thread.
|
||||
*/
|
||||
fun move(context: Context, from: IntArray, to: IntArray) {
|
||||
val prefs = prefs(context)
|
||||
val before = prefs.all
|
||||
val edit = prefs.edit()
|
||||
// All old ids are cleared first, in one change, so that an id that is one widget's old id
|
||||
// and another's new one ends up with the right car.
|
||||
for (oldId in from) {
|
||||
for (key in KEYS) edit.remove(key + oldId)
|
||||
}
|
||||
val moved = ArrayList<Int>()
|
||||
for (i in from.indices) {
|
||||
val newId = to.getOrNull(i) ?: continue
|
||||
for (key in KEYS) {
|
||||
val value = before[key + from[i]] as? String
|
||||
if (value == null) edit.remove(key + newId) else edit.putString(key + newId, value)
|
||||
}
|
||||
moved.add(newId)
|
||||
}
|
||||
edit.apply()
|
||||
moved.forEach(::tell)
|
||||
}
|
||||
|
||||
private fun tell(appWidgetId: Int) {
|
||||
main.post { listeners.forEach { it.onCarWidgetChanged(appWidgetId) } }
|
||||
}
|
||||
|
||||
private fun prefs(context: Context): SharedPreferences =
|
||||
context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
|
||||
|
||||
/**
|
||||
* Encrypts the token with AES-GCM under a key of Android's keystore. What is kept is the
|
||||
* nonce followed by the sealed token, in Base64.
|
||||
*/
|
||||
private object TokenVault {
|
||||
private const val STORE = "AndroidKeyStore"
|
||||
private const val ALIAS = "flexera_traccar_token"
|
||||
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||
private const val NONCE_BYTES = 12
|
||||
private const val TAG_BITS = 128
|
||||
|
||||
fun seal(token: String): String? = try {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key(create = true))
|
||||
val nonce = cipher.iv
|
||||
check(nonce.size == NONCE_BYTES) { "Unexpected nonce size ${nonce.size}" }
|
||||
Base64.encodeToString(nonce + cipher.doFinal(token.toByteArray(Charsets.UTF_8)), Base64.NO_WRAP)
|
||||
} catch (e: Exception) {
|
||||
// The keystore can fail in many ways, some of them unchecked (ProviderException).
|
||||
Log.w(TAG, "Could not encrypt the token", e)
|
||||
null
|
||||
}
|
||||
|
||||
fun open(sealed: String): String? = try {
|
||||
val bytes = Base64.decode(sealed, Base64.NO_WRAP)
|
||||
val key = key(create = false)
|
||||
if (key == null || bytes.size <= NONCE_BYTES) {
|
||||
null
|
||||
} else {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, bytes, 0, NONCE_BYTES))
|
||||
String(cipher.doFinal(bytes, NONCE_BYTES, bytes.size - NONCE_BYTES), Charsets.UTF_8)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not read the token", e)
|
||||
null
|
||||
}
|
||||
|
||||
private fun key(create: Boolean): SecretKey? {
|
||||
val store = KeyStore.getInstance(STORE).apply { load(null) }
|
||||
(store.getKey(ALIAS, null) as? SecretKey)?.let { return it }
|
||||
if (!create) return null
|
||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, STORE)
|
||||
generator.init(
|
||||
KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(256)
|
||||
.build(),
|
||||
)
|
||||
return generator.generateKey()
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -14,8 +14,8 @@ import kotlin.math.max
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* The widgets that come with the launcher: Pictures ([PictureWidgetProvider]) and Clock
|
||||
* ([ClockWidgetProvider]).
|
||||
* The widgets that come with the launcher: Pictures ([PictureWidgetProvider]), Clock
|
||||
* ([ClockWidgetProvider]) and Car ([CarWidgetProvider]).
|
||||
*
|
||||
* Android knows each as an ordinary app widget, so they are added, moved, resized and removed
|
||||
* like any other. What they show is not sent through Android, though: the launcher draws them
|
||||
@@ -28,7 +28,9 @@ object FlexeraWidgets {
|
||||
private val noInset = Rect()
|
||||
|
||||
private fun isOwn(provider: ComponentName?): Boolean =
|
||||
provider == PictureWidgetProvider.componentName || provider == ClockWidgetProvider.componentName
|
||||
provider == PictureWidgetProvider.componentName ||
|
||||
provider == ClockWidgetProvider.componentName ||
|
||||
provider == CarWidgetProvider.componentName
|
||||
|
||||
/**
|
||||
* The room a widget's cells keep free around it, on each side; one cell is [cellWidth] by
|
||||
@@ -105,16 +107,23 @@ object FlexeraWidgets {
|
||||
if (!isOwn(provider)) return null
|
||||
// A widget that still waits to be set up draws its own "tap to set up".
|
||||
if (host is PendingAppWidgetHostView) return null
|
||||
val pictures = provider == PictureWidgetProvider.componentName
|
||||
val kind = when (provider) {
|
||||
PictureWidgetProvider.componentName -> PictureWidgetView::class.java
|
||||
CarWidgetProvider.componentName -> CarWidgetView::class.java
|
||||
else -> ClockWidgetView::class.java
|
||||
}
|
||||
|
||||
var view: View? = null
|
||||
for (i in host.childCount - 1 downTo 0) {
|
||||
val child = host.getChildAt(i)
|
||||
val wanted = if (pictures) child is PictureWidgetView else child is ClockWidgetView
|
||||
if (wanted && view == null) view = child else host.removeViewAt(i)
|
||||
if (kind.isInstance(child) && view == null) view = child else host.removeViewAt(i)
|
||||
}
|
||||
if (view == null) {
|
||||
view = if (pictures) PictureWidgetView(host.context) else ClockWidgetView(host.context)
|
||||
view = when (kind) {
|
||||
PictureWidgetView::class.java -> PictureWidgetView(host.context)
|
||||
CarWidgetView::class.java -> CarWidgetView(host.context)
|
||||
else -> ClockWidgetView(host.context)
|
||||
}
|
||||
host.addView(
|
||||
view,
|
||||
FrameLayout.LayoutParams(
|
||||
@@ -126,6 +135,7 @@ object FlexeraWidgets {
|
||||
when (view) {
|
||||
is PictureWidgetView -> view.bind(appWidgetId)
|
||||
is ClockWidgetView -> view.bind(appWidgetId)
|
||||
is CarWidgetView -> view.bind(appWidgetId)
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
package app.flexera.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.util.LruCache
|
||||
import androidx.annotation.MainThread
|
||||
import androidx.annotation.WorkerThread
|
||||
import com.android.launcher3.BuildConfig
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.concurrent.CopyOnWriteArraySet
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import java.util.concurrent.ThreadPoolExecutor
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* The map under the car widget: tiles of OpenStreetMap's standard map, 256 pixels square.
|
||||
*
|
||||
* They are asked of OpenStreetMap's own tile server, under its tile usage policy
|
||||
* (operations.osmfoundation.org/policies/tiles): only the tiles a widget shows, never ahead of
|
||||
* time, at most [CONNECTIONS] at once, with a User-Agent that names the app, and each kept on the
|
||||
* phone for at least [KEEP_MS] or as long as the server says, whichever is longer, then asked
|
||||
* again only if it has changed (by its ETag). The widget shows "© OpenStreetMap" on the map.
|
||||
*
|
||||
* Tiles live in the app's cache folder, which Android may empty when it needs room, and up to
|
||||
* [MAX_FILES] of them; the ones in use are kept in memory as well.
|
||||
*/
|
||||
internal object MapTiles {
|
||||
|
||||
/** Told, on the main thread, that a tile asked for with [get] has arrived. */
|
||||
fun interface Listener {
|
||||
fun onTileArrived()
|
||||
}
|
||||
|
||||
const val TILE_PX = 256
|
||||
|
||||
private const val TAG = "MapTiles"
|
||||
private const val SERVER = "https://tile.openstreetmap.org"
|
||||
private const val FOLDER = "flexera_map_tiles"
|
||||
private const val CONNECT_TIMEOUT_MS = 10_000
|
||||
private const val READ_TIMEOUT_MS = 15_000
|
||||
|
||||
/** The policy asks for at most two connections at a time. */
|
||||
private const val CONNECTIONS = 2
|
||||
|
||||
/** The least time a tile is kept before it is asked for again, as the policy asks. */
|
||||
private const val KEEP_MS = 7 * 24 * 60 * 60 * 1000L
|
||||
|
||||
/** How long a tile that failed waits before it is asked for again. */
|
||||
private const val RETRY_MS = 60 * 1000L
|
||||
|
||||
private const val MAX_FILES = 400
|
||||
private const val MAX_TILE_BYTES = 1024 * 1024
|
||||
|
||||
/** About forty tiles in memory: two widgets' worth at the largest, at two bytes a pixel. */
|
||||
private const val MEMORY_BYTES = 6 * 1024 * 1024
|
||||
|
||||
private val USER_AGENT = "FlexeraLauncher/${BuildConfig.VERSION_NAME} (Android; car widget)"
|
||||
|
||||
private val listeners = CopyOnWriteArraySet<Listener>()
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
private val memory = object : LruCache<String, Bitmap>(MEMORY_BYTES) {
|
||||
override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount
|
||||
}
|
||||
|
||||
// Used on the main thread only: the tiles on their way, and when each failed tile may be asked again.
|
||||
private val loading = HashSet<String>()
|
||||
private val failedAt = HashMap<String, Long>()
|
||||
|
||||
/** Tiles written since the launcher started, by both fetching threads. */
|
||||
private val writes = AtomicInteger()
|
||||
|
||||
private val executor = ThreadPoolExecutor(
|
||||
CONNECTIONS,
|
||||
CONNECTIONS,
|
||||
30,
|
||||
TimeUnit.SECONDS,
|
||||
LinkedBlockingQueue(),
|
||||
) { runnable ->
|
||||
Thread(runnable, "FlexeraMapTiles").apply {
|
||||
isDaemon = true
|
||||
priority = Thread.MIN_PRIORITY
|
||||
}
|
||||
}.apply { allowCoreThreadTimeOut(true) }
|
||||
|
||||
fun addListener(listener: Listener) {
|
||||
listeners.add(listener)
|
||||
}
|
||||
|
||||
fun removeListener(listener: Listener) {
|
||||
listeners.remove(listener)
|
||||
}
|
||||
|
||||
/** How many tiles there are along each side of the world at [zoom]. */
|
||||
fun tilesAcross(zoom: Int): Int = 1 shl zoom
|
||||
|
||||
/**
|
||||
* The tile at [zoom], [x], [y], if it is in memory. Otherwise null, and the tile is read from
|
||||
* the phone or fetched; listeners are told when it is there.
|
||||
*/
|
||||
@MainThread
|
||||
fun get(context: Context, zoom: Int, x: Int, y: Int): Bitmap? {
|
||||
val across = tilesAcross(zoom)
|
||||
if (y !in 0 until across) return null
|
||||
val wrappedX = Math.floorMod(x, across)
|
||||
val key = "$zoom/$wrappedX/$y"
|
||||
memory.get(key)?.let { return it }
|
||||
if (key in loading) return null
|
||||
val failed = failedAt[key]
|
||||
if (failed != null && SystemClock.elapsedRealtime() - failed < RETRY_MS) return null
|
||||
loading.add(key)
|
||||
val app = context.applicationContext
|
||||
executor.execute {
|
||||
val bitmap = try {
|
||||
load(app, zoom, wrappedX, y)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Tile $key: ${e.javaClass.simpleName}: ${e.message}")
|
||||
null
|
||||
} catch (e: OutOfMemoryError) {
|
||||
Log.w(TAG, "Tile $key did not fit in memory")
|
||||
null
|
||||
}
|
||||
main.post {
|
||||
loading.remove(key)
|
||||
if (bitmap == null) {
|
||||
failedAt[key] = SystemClock.elapsedRealtime()
|
||||
} else {
|
||||
failedAt.remove(key)
|
||||
memory.put(key, bitmap)
|
||||
listeners.forEach { it.onTileArrived() }
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The tile from the phone when it is fresh, else from the server; a stale copy when the server cannot be reached. */
|
||||
@WorkerThread
|
||||
private fun load(context: Context, zoom: Int, x: Int, y: Int): Bitmap? {
|
||||
val file = File(folder(context), "$zoom/$x/$y.png")
|
||||
val meta = File(file.path + ".meta")
|
||||
val kept = if (file.isFile) readMeta(meta) else null
|
||||
val now = System.currentTimeMillis()
|
||||
if (kept != null && now < kept.expires) decode(file)?.let { return it }
|
||||
|
||||
val connection = URL("$SERVER/$zoom/$x/$y.png").openConnection() as HttpURLConnection
|
||||
try {
|
||||
connection.connectTimeout = CONNECT_TIMEOUT_MS
|
||||
connection.readTimeout = READ_TIMEOUT_MS
|
||||
connection.setRequestProperty("User-Agent", USER_AGENT)
|
||||
if (kept != null) {
|
||||
kept.etag?.let { connection.setRequestProperty("If-None-Match", it) }
|
||||
kept.lastModified?.let { connection.setRequestProperty("If-Modified-Since", it) }
|
||||
}
|
||||
val code = try {
|
||||
connection.responseCode
|
||||
} catch (e: IOException) {
|
||||
// Offline: a tile kept past its time is better than a hole in the map.
|
||||
return if (file.isFile) decode(file) else throw e
|
||||
}
|
||||
when (code) {
|
||||
HttpURLConnection.HTTP_NOT_MODIFIED -> {
|
||||
writeMeta(meta, expiry(connection, now), kept?.etag, kept?.lastModified)
|
||||
return decode(file)
|
||||
}
|
||||
|
||||
HttpURLConnection.HTTP_OK -> {
|
||||
val bytes = connection.inputStream.use { input ->
|
||||
val out = ByteArrayOutputStream()
|
||||
val buffer = ByteArray(16 * 1024)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
if (out.size() > MAX_TILE_BYTES) throw IOException("Too large for a tile")
|
||||
}
|
||||
out.toByteArray()
|
||||
}
|
||||
val bitmap = decode(bytes) ?: throw IOException("Not a picture")
|
||||
save(file, bytes)
|
||||
writeMeta(
|
||||
meta,
|
||||
expiry(connection, now),
|
||||
connection.getHeaderField("ETag"),
|
||||
connection.getHeaderField("Last-Modified"),
|
||||
)
|
||||
prune(context)
|
||||
return bitmap
|
||||
}
|
||||
|
||||
else -> {
|
||||
Log.w(TAG, "Tile $zoom/$x/$y: HTTP $code")
|
||||
return if (file.isFile) decode(file) else null
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
/** When a tile fetched at [now] is due to be asked for again: what the server says, but no sooner than [KEEP_MS]. */
|
||||
private fun expiry(connection: HttpURLConnection, now: Long): Long {
|
||||
val maxAge = connection.getHeaderField("Cache-Control")
|
||||
?.split(',')
|
||||
?.map { it.trim() }
|
||||
?.firstOrNull { it.startsWith("max-age=", ignoreCase = true) }
|
||||
?.substringAfter('=')
|
||||
?.toLongOrNull()
|
||||
val byServer = when {
|
||||
maxAge != null -> now + maxAge * 1000
|
||||
connection.expiration > 0 -> connection.expiration
|
||||
else -> 0L
|
||||
}
|
||||
return maxOf(now + KEEP_MS, byServer)
|
||||
}
|
||||
|
||||
private class Meta(val expires: Long, val etag: String?, val lastModified: String?)
|
||||
|
||||
private fun readMeta(meta: File): Meta? = try {
|
||||
val lines = meta.readLines()
|
||||
Meta(
|
||||
expires = lines.getOrNull(0)?.toLongOrNull() ?: 0L,
|
||||
etag = lines.getOrNull(1)?.ifEmpty { null },
|
||||
lastModified = lines.getOrNull(2)?.ifEmpty { null },
|
||||
)
|
||||
} catch (e: IOException) {
|
||||
null
|
||||
}
|
||||
|
||||
private fun writeMeta(meta: File, expires: Long, etag: String?, lastModified: String?) {
|
||||
try {
|
||||
meta.parentFile?.mkdirs()
|
||||
// Header values never hold a line break; one that did would only spoil this tile's record.
|
||||
meta.writeText("$expires\n${etag.orEmpty().lines().first()}\n${lastModified.orEmpty().lines().first()}\n")
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "Could not keep a tile's record", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun save(file: File, bytes: ByteArray) {
|
||||
try {
|
||||
file.parentFile?.mkdirs()
|
||||
val partial = File(file.path + ".part")
|
||||
partial.writeBytes(bytes)
|
||||
if (!partial.renameTo(file)) {
|
||||
partial.delete()
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "Could not keep a tile", e)
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps the folder to [MAX_FILES] tiles, dropping those used least recently. Now and then, not at every write. */
|
||||
private fun prune(context: Context) {
|
||||
if (writes.incrementAndGet() % 25 != 0) return
|
||||
val tiles = folder(context).walkTopDown().filter { it.isFile && it.name.endsWith(".png") }.toList()
|
||||
if (tiles.size <= MAX_FILES) return
|
||||
tiles.sortedBy { it.lastModified() }.take(tiles.size - MAX_FILES).forEach { tile ->
|
||||
tile.delete()
|
||||
File(tile.path + ".meta").delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun decode(file: File): Bitmap? {
|
||||
// Marks the tile as used, for prune().
|
||||
file.setLastModified(System.currentTimeMillis())
|
||||
return BitmapFactory.decodeFile(file.path, decodeOptions())
|
||||
}
|
||||
|
||||
private fun decode(bytes: ByteArray): Bitmap? = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, decodeOptions())
|
||||
|
||||
/** The tiles have no see-through parts: two bytes a pixel are enough. */
|
||||
private fun decodeOptions() = BitmapFactory.Options().apply { inPreferredConfig = Bitmap.Config.RGB_565 }
|
||||
|
||||
private fun folder(context: Context): File = File(context.cacheDir, FOLDER)
|
||||
}
|
||||
@@ -26,20 +26,13 @@ import android.text.StaticLayout
|
||||
import android.text.TextPaint
|
||||
import android.util.AttributeSet
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import android.view.animation.LinearInterpolator
|
||||
import android.widget.FrameLayout
|
||||
import app.lawnchair.icons.shape.CornerShapeCompat
|
||||
import app.lawnchair.icons.shape.IconShape
|
||||
import app.lawnchair.preferences2.PreferenceManager2
|
||||
import app.lawnchair.preferences2.firstCached
|
||||
import com.android.launcher3.CellLayout
|
||||
import com.android.launcher3.Launcher
|
||||
import com.android.launcher3.LauncherState
|
||||
import com.android.launcher3.R
|
||||
import com.android.launcher3.ShortcutAndWidgetContainer
|
||||
import com.android.launcher3.Workspace
|
||||
import com.android.launcher3.folder.Folder
|
||||
import com.android.launcher3.util.Executors
|
||||
import java.io.File
|
||||
import java.text.BreakIterator
|
||||
@@ -389,38 +382,8 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
scheduleNext()
|
||||
}
|
||||
|
||||
/**
|
||||
* True while the widget can really be seen. Its window being on the screen is not enough:
|
||||
* Launcher3 leaves every home screen page shown, and covers them with the app drawer, Recents
|
||||
* or a folder without hiding them.
|
||||
*/
|
||||
private fun isSeen(): Boolean {
|
||||
if (!onScreen || !isShown) return false
|
||||
val launcher = launcher() ?: return true
|
||||
if (!launcher.isInState(LauncherState.NORMAL) &&
|
||||
!launcher.isInState(LauncherState.SPRING_LOADED) &&
|
||||
!launcher.isInState(LauncherState.EDIT_MODE)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
if (Folder.getOpen(launcher) != null) return false
|
||||
// On the home screen: the page the widget is on has to be one of those on the screen,
|
||||
// and not faded out.
|
||||
val cells = (parent as? View)?.parent as? ShortcutAndWidgetContainer ?: return true
|
||||
if (cells.alpha <= 0f) return false
|
||||
val page = cells.parent as? CellLayout ?: return true
|
||||
val pages = page.parent as? Workspace<*> ?: return true
|
||||
return pages.isVisible(page)
|
||||
}
|
||||
|
||||
private fun launcher(): Launcher? {
|
||||
var current: Context? = context
|
||||
while (current != null) {
|
||||
if (current is Launcher) return current
|
||||
current = (current as? ContextWrapper)?.baseContext
|
||||
}
|
||||
return null
|
||||
}
|
||||
/** True while the widget can really be seen ([WidgetSight]). */
|
||||
private fun isSeen(): Boolean = WidgetSight.isSeen(this, onScreen)
|
||||
|
||||
private fun onTap() {
|
||||
when {
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
package app.flexera.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.annotation.WorkerThread
|
||||
import app.flexera.update.FlexeraUpdater
|
||||
import com.android.launcher3.BuildConfig
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.net.ConnectException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.MalformedURLException
|
||||
import java.net.NoRouteToHostException
|
||||
import java.net.SocketTimeoutException
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
import java.net.UnknownServiceException
|
||||
import java.time.Instant
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.format.DateTimeParseException
|
||||
import java.time.temporal.ChronoUnit
|
||||
import java.util.Locale
|
||||
import javax.net.ssl.SSLException
|
||||
import javax.net.ssl.SSLHandshakeException
|
||||
import javax.net.ssl.SSLPeerUnverifiedException
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* The car widget's side of a Traccar server (traccar.org), the GPS tracking server the owner
|
||||
* runs: the devices a Traccar user can see, the last position of one, and since when it has
|
||||
* stood still. Read through Traccar's own REST API, signed in with a token the owner made in
|
||||
* Traccar for this purpose.
|
||||
*
|
||||
* Only over https: the token goes along with every request, and a connection that is not
|
||||
* encrypted would show it to anyone on the way. Redirects are not followed, for the same reason.
|
||||
*/
|
||||
internal object Traccar {
|
||||
|
||||
/**
|
||||
* A Traccar server, as an address without a trailing slash (`https://traccar.example.com`,
|
||||
* or with a path when Traccar sits under one), and the token of the user the launcher signs
|
||||
* in as.
|
||||
*/
|
||||
data class Account(val server: String, val token: String) {
|
||||
/** The server's name, as the options show it. */
|
||||
val host: String get() = runCatching { URL(server).host }.getOrNull() ?: server
|
||||
|
||||
override fun toString(): String = "Account($server)"
|
||||
}
|
||||
|
||||
/** A device the Traccar user can see: a tracker, usually in a car. */
|
||||
data class Device(val id: Long, val name: String, val online: Boolean)
|
||||
|
||||
/** Where a device last was, as Traccar knows it. */
|
||||
data class Position(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
/** When the tracker took this position, in milliseconds since 1970. */
|
||||
val fixTime: Long,
|
||||
/** Traccar's own judgement, from the speed or the ignition. */
|
||||
val moving: Boolean,
|
||||
/** In knots, as Traccar keeps it. */
|
||||
val speedKnots: Double,
|
||||
/** The address, when the server looks addresses up itself; null when it does not. */
|
||||
val address: String?,
|
||||
)
|
||||
|
||||
/** A stop from Traccar's stops report: where the device stood, from when to when. */
|
||||
data class Stop(val latitude: Double, val longitude: Double, val start: Long, val end: Long)
|
||||
|
||||
/** What went wrong, in words the options and the widget can say. */
|
||||
enum class Problem {
|
||||
/** Traccar said no to the token: wrong, expired, or of a user that is disabled. */
|
||||
TOKEN,
|
||||
|
||||
/** Something answered, but not Traccar's API. */
|
||||
NOT_TRACCAR,
|
||||
|
||||
/** The address is not https. */
|
||||
NOT_SECURE,
|
||||
|
||||
/** The server's certificate is not one Android trusts. */
|
||||
CERTIFICATE,
|
||||
|
||||
/** Android 17 keeps the launcher from the phone's own network, where the server is. */
|
||||
LOCAL_NETWORK,
|
||||
|
||||
/** No answer: offline, a wrong name, or the server is down. */
|
||||
OFFLINE,
|
||||
|
||||
/** Traccar answered with an error of its own. */
|
||||
SERVER,
|
||||
}
|
||||
|
||||
class TraccarException(val problem: Problem, message: String, cause: Throwable? = null) :
|
||||
IOException(message, cause)
|
||||
|
||||
private const val TAG = "Traccar"
|
||||
private const val CONNECT_TIMEOUT_MS = 10_000
|
||||
private const val READ_TIMEOUT_MS = 15_000
|
||||
|
||||
/** No answer the widget asks for is larger than this; a larger one is something else. */
|
||||
private const val MAX_BYTES = 4 * 1024 * 1024
|
||||
|
||||
// Android's own User-Agent would tell the server the phone's model and its exact Android
|
||||
// build. This one names only the app.
|
||||
private val USER_AGENT = "FlexeraLauncher/${BuildConfig.VERSION_NAME}"
|
||||
|
||||
/**
|
||||
* The server address the owner typed, made into the form [Account] keeps: https when no
|
||||
* scheme is given, no trailing slash, and without "/api" when the address of the API itself
|
||||
* was pasted. Null when it is not a web address.
|
||||
*/
|
||||
fun normalize(input: String): String? {
|
||||
var text = input.trim()
|
||||
if (text.isEmpty()) return null
|
||||
if (!text.contains("://")) text = "https://$text"
|
||||
val url = try {
|
||||
URL(text)
|
||||
} catch (e: MalformedURLException) {
|
||||
return null
|
||||
}
|
||||
val scheme = url.protocol.lowercase(Locale.ROOT)
|
||||
if (scheme != "https" && scheme != "http") return null
|
||||
val host = url.host?.lowercase(Locale.ROOT)
|
||||
if (host.isNullOrEmpty()) return null
|
||||
var path = url.path.orEmpty().trimEnd('/')
|
||||
if (path.endsWith("/api")) path = path.removeSuffix("/api")
|
||||
val port = if (url.port == -1 || url.port == url.defaultPort) "" else ":${url.port}"
|
||||
return "$scheme://$host$port$path"
|
||||
}
|
||||
|
||||
/** The devices the account's user can see, by name. Throws [TraccarException] when it cannot ask. */
|
||||
@WorkerThread
|
||||
@Throws(TraccarException::class)
|
||||
fun devices(context: Context, account: Account): List<Device> {
|
||||
val answer = array(get(context, account, "/api/devices"))
|
||||
return (0 until answer.length())
|
||||
.mapNotNull { answer.optJSONObject(it) }
|
||||
.filterNot { it.optBoolean("disabled", false) }
|
||||
.map { device ->
|
||||
Device(
|
||||
id = device.optLong("id"),
|
||||
name = text(device, "name") ?: text(device, "uniqueId").orEmpty(),
|
||||
online = device.optString("status") == "online",
|
||||
)
|
||||
}
|
||||
.filter { it.id > 0 }
|
||||
.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.name })
|
||||
}
|
||||
|
||||
/** The last position of a device, or null when Traccar has none yet. */
|
||||
@WorkerThread
|
||||
@Throws(TraccarException::class)
|
||||
fun latestPosition(context: Context, account: Account, deviceId: Long): Position? {
|
||||
// With a device and no time span Traccar answers with that device's latest position only.
|
||||
val answer = array(get(context, account, "/api/positions?deviceId=$deviceId"))
|
||||
val position = answer.optJSONObject(0) ?: return null
|
||||
if (!position.has("latitude") || !position.has("longitude")) return null
|
||||
val attributes = position.optJSONObject("attributes")
|
||||
return Position(
|
||||
latitude = position.optDouble("latitude"),
|
||||
longitude = position.optDouble("longitude"),
|
||||
fixTime = time(text(position, "fixTime")) ?: time(text(position, "deviceTime")) ?: 0L,
|
||||
moving = attributes?.optBoolean("motion", false) ?: false,
|
||||
speedKnots = position.optDouble("speed", 0.0).takeIf { it.isFinite() } ?: 0.0,
|
||||
address = text(position, "address"),
|
||||
).takeIf { it.latitude.isFinite() && it.longitude.isFinite() }
|
||||
}
|
||||
|
||||
/**
|
||||
* The last stop of a device between [from] and [to] (milliseconds since 1970), from Traccar's
|
||||
* stops report. The report includes a stop that is still going on at [to]; its end is then the
|
||||
* device's last position. Null when the report has no stop in that time.
|
||||
*/
|
||||
@WorkerThread
|
||||
@Throws(TraccarException::class)
|
||||
fun lastStop(context: Context, account: Account, deviceId: Long, from: Long, to: Long): Stop? {
|
||||
val span = "from=${query(from)}&to=${query(to)}"
|
||||
val answer = array(get(context, account, "/api/reports/stops?deviceId=$deviceId&$span"))
|
||||
return (0 until answer.length())
|
||||
.mapNotNull { answer.optJSONObject(it) }
|
||||
.mapNotNull { stop ->
|
||||
Stop(
|
||||
latitude = stop.optDouble("latitude"),
|
||||
longitude = stop.optDouble("longitude"),
|
||||
start = time(text(stop, "startTime")) ?: return@mapNotNull null,
|
||||
end = time(text(stop, "endTime")) ?: return@mapNotNull null,
|
||||
).takeIf { it.latitude.isFinite() && it.longitude.isFinite() }
|
||||
}
|
||||
.maxByOrNull { it.start }
|
||||
}
|
||||
|
||||
/** A time as Traccar's API takes it: ISO 8601 in UTC, to the second. */
|
||||
private fun query(time: Long): String =
|
||||
URLEncoder.encode(Instant.ofEpochMilli(time).truncatedTo(ChronoUnit.SECONDS).toString(), "UTF-8")
|
||||
|
||||
/**
|
||||
* A time as Traccar's API gives it, such as "2026-11-28T10:11:12.000+00:00", in milliseconds
|
||||
* since 1970; null when there is none or it cannot be read.
|
||||
*/
|
||||
internal fun time(text: String?): Long? {
|
||||
if (text.isNullOrEmpty()) return null
|
||||
return try {
|
||||
OffsetDateTime.parse(text).toInstant().toEpochMilli()
|
||||
} catch (e: DateTimeParseException) {
|
||||
// An offset written without its colon ("+0000"), as some Java date formats write it.
|
||||
val fixed = OFFSET_WITHOUT_COLON.replace(text) { "${it.groupValues[1]}:${it.groupValues[2]}" }
|
||||
runCatching { OffsetDateTime.parse(fixed).toInstant().toEpochMilli() }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
private val OFFSET_WITHOUT_COLON = Regex("""([+-]\d{2})(\d{2})$""")
|
||||
|
||||
/** A string field, or null when it is missing, null or empty. Android's optString says "null" for null. */
|
||||
private fun text(json: JSONObject, name: String): String? =
|
||||
if (json.isNull(name)) null else json.optString(name).trim().takeIf { it.isNotEmpty() }
|
||||
|
||||
private fun array(answer: String): JSONArray = try {
|
||||
JSONArray(answer)
|
||||
} catch (e: JSONException) {
|
||||
throw TraccarException(Problem.NOT_TRACCAR, "The answer is not a list", e)
|
||||
}
|
||||
|
||||
private fun get(context: Context, account: Account, path: String): String {
|
||||
if (!account.server.startsWith("https://")) {
|
||||
throw TraccarException(Problem.NOT_SECURE, "Not an https address")
|
||||
}
|
||||
val address = account.server + path
|
||||
val connection = try {
|
||||
URL(address).openConnection() as HttpURLConnection
|
||||
} catch (e: IOException) {
|
||||
throw problemOf(context, address, e)
|
||||
}
|
||||
try {
|
||||
connection.connectTimeout = CONNECT_TIMEOUT_MS
|
||||
connection.readTimeout = READ_TIMEOUT_MS
|
||||
// A redirect could take the token to another server.
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.useCaches = false
|
||||
connection.setRequestProperty("Accept", "application/json")
|
||||
connection.setRequestProperty("Authorization", "Bearer ${account.token}")
|
||||
connection.setRequestProperty("User-Agent", USER_AGENT)
|
||||
val code = connection.responseCode
|
||||
when {
|
||||
code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN ->
|
||||
throw TraccarException(Problem.TOKEN, "HTTP $code for $path")
|
||||
|
||||
code == HttpURLConnection.HTTP_NOT_FOUND || code in 300..399 ->
|
||||
throw TraccarException(Problem.NOT_TRACCAR, "HTTP $code for $path")
|
||||
|
||||
code != HttpURLConnection.HTTP_OK ->
|
||||
throw TraccarException(Problem.SERVER, "HTTP $code for $path")
|
||||
}
|
||||
val type = connection.contentType.orEmpty()
|
||||
if (!type.contains("json", ignoreCase = true)) {
|
||||
throw TraccarException(Problem.NOT_TRACCAR, "Answered with \"$type\" for $path")
|
||||
}
|
||||
return readCapped(connection.inputStream).toString(Charsets.UTF_8)
|
||||
} catch (e: TraccarException) {
|
||||
Log.w(TAG, "${account.host}: ${e.problem} (${e.message})")
|
||||
throw e
|
||||
} catch (e: IOException) {
|
||||
throw problemOf(context, address, e)
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun readCapped(input: InputStream): ByteArray = input.use {
|
||||
val out = ByteArrayOutputStream()
|
||||
val buffer = ByteArray(16 * 1024)
|
||||
while (true) {
|
||||
val read = it.read(buffer)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
if (out.size() > MAX_BYTES) throw TraccarException(Problem.NOT_TRACCAR, "Too large an answer")
|
||||
}
|
||||
out.toByteArray()
|
||||
}
|
||||
|
||||
private fun problemOf(context: Context, address: String, e: IOException): TraccarException {
|
||||
val host = runCatching { URL(address).host }.getOrNull()
|
||||
val problem = when {
|
||||
(e is SocketTimeoutException || e is ConnectException || e is NoRouteToHostException) &&
|
||||
host != null && FlexeraUpdater.blocksLocalNetwork(context, host) -> Problem.LOCAL_NETWORK
|
||||
e is SSLHandshakeException || e is SSLPeerUnverifiedException -> Problem.CERTIFICATE
|
||||
e is SSLException -> Problem.CERTIFICATE
|
||||
// Android refuses a connection that is not encrypted with this.
|
||||
e is UnknownServiceException -> Problem.NOT_SECURE
|
||||
else -> Problem.OFFLINE
|
||||
}
|
||||
Log.w(TAG, "$host: $problem (${e.javaClass.simpleName}: ${e.message})")
|
||||
return TraccarException(problem, e.message.orEmpty(), e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package app.flexera.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.view.View
|
||||
import com.android.launcher3.CellLayout
|
||||
import com.android.launcher3.Launcher
|
||||
import com.android.launcher3.LauncherState
|
||||
import com.android.launcher3.ShortcutAndWidgetContainer
|
||||
import com.android.launcher3.Workspace
|
||||
import com.android.launcher3.folder.Folder
|
||||
|
||||
/** Whether one of the launcher's own widgets can really be seen. */
|
||||
internal object WidgetSight {
|
||||
|
||||
/**
|
||||
* True while [view], the view inside a widget's host view, can be seen; [onScreen] is what
|
||||
* Android last told it (onVisibilityAggregated). That is not enough by itself: Launcher3 leaves
|
||||
* every home screen page shown, and covers them with the app drawer, Recents or a folder
|
||||
* without hiding them.
|
||||
*/
|
||||
fun isSeen(view: View, onScreen: Boolean): Boolean {
|
||||
if (!onScreen || !view.isShown) return false
|
||||
val launcher = launcher(view.context) ?: return true
|
||||
if (!launcher.isInState(LauncherState.NORMAL) &&
|
||||
!launcher.isInState(LauncherState.SPRING_LOADED) &&
|
||||
!launcher.isInState(LauncherState.EDIT_MODE)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
if (Folder.getOpen(launcher) != null) return false
|
||||
// On the home screen: the page the widget is on has to be one of those on the screen,
|
||||
// and not faded out.
|
||||
val cells = (view.parent as? View)?.parent as? ShortcutAndWidgetContainer ?: return true
|
||||
if (cells.alpha <= 0f) return false
|
||||
val page = cells.parent as? CellLayout ?: return true
|
||||
val pages = page.parent as? Workspace<*> ?: return true
|
||||
return pages.isVisible(page)
|
||||
}
|
||||
|
||||
fun launcher(context: Context): Launcher? {
|
||||
var current: Context? = context
|
||||
while (current != null) {
|
||||
if (current is Launcher) return current
|
||||
current = (current as? ContextWrapper)?.baseContext
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -199,6 +199,7 @@ public class LauncherWidgetHolder {
|
||||
// not, and the launcher's own widgets may already keep pictures or options under it.
|
||||
app.flexera.widget.PictureWidgetProvider.onAppWidgetIdDeleted(mContext, appWidgetId);
|
||||
app.flexera.widget.ClockWidgetProvider.onAppWidgetIdDeleted(mContext, appWidgetId);
|
||||
app.flexera.widget.CarWidgetProvider.onAppWidgetIdDeleted(mContext, appWidgetId);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -133,6 +133,7 @@ constructor(
|
||||
// loaded, which would delete those too, so they go to the new id first.
|
||||
app.flexera.widget.PictureWidgetProvider.onNewAppWidgetId(context, item, oldAppWidgetId)
|
||||
app.flexera.widget.ClockWidgetProvider.onNewAppWidgetId(context, item, oldAppWidgetId)
|
||||
app.flexera.widget.CarWidgetProvider.onNewAppWidgetId(context, item, oldAppWidgetId)
|
||||
item.restoreStatus =
|
||||
item.restoreStatus or LauncherAppWidgetInfo.FLAG_ID_ALLOCATED
|
||||
|
||||
|
||||
Reference in new issue
Block a user