176 Commits
Author SHA1 Message Date
Marcus Handte f641f5749c Upgrade android gradle to 9.6.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2026-11-12 17:23:23 +01:00
Marcus Handte a0458b963c Added code optimizations to android app. 2026-11-12 13:29:25 +01:00
Marcus Handte 3403907775 Increase heap size for linting.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2026-11-11 17:12:06 +01:00
Marcus Handte 768bb996d9 Upgrade android app to modern requirements.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2026-11-11 17:02:21 +01:00
Marcus Handte a008d3612b Fix bugfix.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2026-09-15 16:27:35 +02:00
Marcus Handte 6bb9330a20 Add workaround for broken data.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2026-09-15 16:05:46 +02:00
Marcus Handte ec384792fa Handle new grib2 packaging format.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2026-07-30 19:06:43 +02:00
Marcus Handte a954034c72 Upgrade grib library to support new files from dwd.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2026-07-29 12:19:53 +02:00
Marcus Handte 832ce77f74 Bump android target sdk.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2026-07-23 14:21:54 +02:00
Marcus Handte 9ea731af06 Bump app version and version code.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2025-03-29 06:45:14 +01:00
Marcus Handte 6763e2eefd Update dependencies, gradle and android plugin.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2025-03-29 06:41:40 +01:00
Marcus Handte 7786e594f2 Removed in-app temperature measurements.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2025-03-29 06:04:17 +01:00
Marcus Handte a5c4ff33aa Bump version code of android app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2025-01-03 13:10:55 +01:00
Marcus Handte 9e38572e8e Fix bugs in widget handling, opt out of android edge to edge.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2025-01-03 12:58:28 +01:00
Marcus Handte 015fdf713c Fix layout issues and api parameter ordering bugs.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2025-01-02 21:30:59 +01:00
Marcus Handte 0d67b29189 Add missing dependency.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2025-01-02 20:41:41 +01:00
Marcus Handte 886b175084 Copy android outputs to production server.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2025-01-02 20:36:44 +01:00
Marcus Handte 799ad2c5b8 Submitted ios app update to app store.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2025-01-02 20:20:47 +01:00
Marcus Handte 471bfa3c34 Fix gradient rendering of ios app, update minimum to ios 15.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2025-01-02 20:03:53 +01:00
Marcus Handte 4fd35d8a8d Add missing dependency declaration.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2025-01-02 16:54:18 +01:00
Marcus Handte 0d3bf7a991 Update gradle, update android app dependencies, support for Android 15.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2025-01-02 16:15:51 +01:00
heil 9b7360752d manage system duplicate if clause removed
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-10-01 15:33:07 +02:00
Marcus Handte ae3483761c Update to 1.1.3-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-10-01 15:16:17 +02:00
Marcus Handte 1854752d92 Release 1.1.2
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-10-01 15:15:34 +02:00
Marcus Handte 7b85810c29 Add missing access control annotation to system statistic.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-10-01 15:13:11 +02:00
heil 5ff779aee4 Stations component scss update
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-10-01 15:01:06 +02:00
heil a7c4480464 Manage System Component SVG update
loadCPU not fully working because of GET 500 Error
memoryusage fully working
2024-10-01 15:00:55 +02:00
heil 96a266c728 Manuell theme -> mw3 theme
LocationBasedServices/mowesta/pipeline/head This commit looks good
Code base cleanup in styles.scss
cityview icon display order
map & log encapsulation
2024-09-24 16:40:56 +02:00
heil 99e4b284bb Hot fix theme for elements
LocationBasedServices/mowesta/pipeline/head This commit looks good
-First part of mat theme fix
-forecast & search standalone darkmode disable option
2024-09-19 18:08:04 +02:00
Marcus Handte 25a810df05 Update to 1.1.2-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-09-19 17:34:11 +02:00
Marcus Handte 66bed8c89f Release 1.1.1
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-09-19 17:23:21 +02:00
heil 07e85b6f32 footer 2nd scroll bar bug fix
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-09-19 16:50:09 +02:00
Marcus Handte 50c17ab504 Update to 1.1.1-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-09-19 16:45:42 +02:00
Marcus Handte 735fc4191a Release 1.1.0
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-09-19 16:36:02 +02:00
heil 1a8d471b3f search budget fix
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-09-19 16:29:37 +02:00
heil 3885c13007 forecast budget fix
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-09-19 16:25:00 +02:00
heil d01cbd2d81 code base clean up
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-09-19 16:22:03 +02:00
heil 096d960c76 Forcast color m3 update 2024-09-19 16:16:10 +02:00
heil b681b0fa11 user settings mat-tab-group size fix
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-09-19 15:33:01 +02:00
heil 42a1e4b530 City view grid update
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
footer update
Video bar fix
small UI update
2024-09-19 14:19:43 +02:00
heil 1eec320528 m3 Theme Color Update
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
Color Design Update
Dark mode Update
Respopnsive Design Update
Small clean base clean up
2024-09-17 12:25:38 +02:00
heil 3efa42facb Removed m2 theme
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
Added m3 theme
-not fully applied

Adjusting styles to m3 theme
2024-08-22 15:29:41 +02:00
heil f2ba86687a gradle adjustments
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-08-06 15:31:17 +02:00
heil 92873bed80 app -> mowesta-app reset
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-08-06 14:18:25 +02:00
heil cfaab5263e angular material update
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-08-06 13:40:44 +02:00
heil b083863b08 typescript update
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-08-06 13:39:00 +02:00
heil 9e5b70fe70 Angular 18 update
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-08-06 13:34:47 +02:00
heil 5d5f1b7f1c mowesta-app -> app
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-08-06 13:25:34 +02:00
heil aae820834b darkmode start
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-08-06 13:24:18 +02:00
heil 2635ee890d Test Colors removed 2024-08-06 11:37:59 +02:00
heil 136b969add city component viewbar
LocationBasedServices/mowesta/pipeline/head This commit looks good
mat card
footer
2024-07-09 18:25:59 +02:00
heil 54a455ea24 city component large city names small pixel devices fix 2024-07-04 16:34:53 +02:00
heil 9f938ef016 city view weather wallpapers 2024-07-04 15:37:45 +02:00
heil 8a924840dd City component mobile update
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-07-02 17:08:47 +02:00
heil a5cfabbfd2 Adjustsments City update
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-07-02 12:57:26 +02:00
heil 89487dd6ec Updating city component to Grid CSS. In Progress
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-06-25 16:23:34 +02:00
Marcus Handte fb8518fcb0 Update to Angular 18.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-06-14 19:35:04 +02:00
Marcus Handte 31e7af3097 Remove es suffixes from scripts.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-06-14 18:32:09 +02:00
Marcus Handte 373748cb9c Set font to montserrat.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-06-14 16:43:26 +02:00
Marcus Handte 1827b964ed Change output hashing to fix font loading issues, remove old font types.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-06-14 16:30:04 +02:00
Marcus Handte b1e144df73 Fix server location.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-06-14 13:23:52 +02:00
Marcus Handte 6bdc8fe3ea Improve query performance, try fix concat.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-06-14 13:13:37 +02:00
heil 018287ee6b unnecessary
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-06-11 13:50:09 +02:00
heil 49d6925da8 declined data share
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-06-11 12:58:18 +02:00
Marcus Handte 0932fdd0b8 Deploy migrated version to wildfly 31 and fix webapp. 2024-06-10 23:18:22 +02:00
heil 094f98b46b icon hover + text adjustments
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-04-18 09:54:12 +02:00
heil 968d827fc2 adjustments
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-04-18 08:16:04 +02:00
heil 82bd2fc466 weather shadows
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-04-18 08:12:17 +02:00
heil 9ca8a38360 forecast box shadow
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-04-18 08:05:47 +02:00
heil ddef7184b8 mowesta-forecast missing right margin
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-04-16 13:49:10 +02:00
heil 91238440f7 mowesta-search
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-04-16 13:12:03 +02:00
heil 9cb8bfe2f0 Adjustments for Style and local language
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-04-11 17:09:55 +02:00
heil 5f8cca15fa Adjustments
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-04-09 13:55:30 +02:00
heil 128c01e68d Search Field
LocationBasedServices/mowesta/pipeline/head This commit looks good
UI 1:1 adjustments
2024-04-04 17:43:11 +02:00
Marcus Handte 0f42047f50 Log timings for condition.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-03-28 19:28:22 +01:00
Marcus Handte 2f58a3d287 Mark coordinates as sortable.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-03-28 17:53:56 +01:00
Marcus Handte b0252b1676 Add missing dependencies.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-03-28 17:44:32 +01:00
Marcus Handte da424dc70b Migrate to standalone components.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-28 17:20:49 +01:00
Marcus Handte 348462a10c Fix sorting operation. 2024-03-28 17:16:25 +01:00
heil b4cc029716 Fixes
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-03-28 15:49:17 +01:00
Marcus Handte 9fef73eb7a Fix typo in galleon descriptor, finalize explicit db mapping.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-03-28 09:47:46 +01:00
Marcus Handte cc0f95af91 Add explicit length.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-03-27 09:55:09 +01:00
Marcus Handte 1d6e0cc64c Fix column definitions for locations.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-03-27 09:44:29 +01:00
Marcus Handte bd838657e4 Skip tests for now.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2024-03-27 09:08:22 +01:00
Marcus Handte af9f3f63fe Switch build to Java 17.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-27 08:54:19 +01:00
Marcus Handte 9b5ee375b9 Add deployment to beta server.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-27 08:49:47 +01:00
heil 149de17617 TEst
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-19 12:37:01 +01:00
heil fc9c0e7b55 Adjustment Fixes 2024-03-19 12:36:41 +01:00
heil 9094db9df9 Design & Functional updates
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-14 16:25:05 +01:00
Marcus Handte 1ce515ed9f Finalize backend migration.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-14 14:31:28 +01:00
Marcus Handte ee26a8180b Use system properties to simplify backend configuration.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-13 18:16:13 +01:00
Marcus Handte 85a250bcf4 Replace custom auth with locoslab library.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-13 12:09:24 +01:00
Marcus Handte 6bfc0c8de0 Migrate to external grib2 library.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-13 11:07:27 +01:00
Marcus Handte ef5ea9391d Remove unused modules.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-13 08:50:35 +01:00
Marcus Handte ee5435ae3d Finish service migration with ffmpeg, mapdb and lucene.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-13 08:23:08 +01:00
heil c5c711a28a Migration updates
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-12 12:37:26 +01:00
heil 0087b6263c Migration updates 2024-03-12 12:37:26 +01:00
Marcus Handte 0c8607112c Fix imports and tests.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-12 11:45:41 +01:00
Marcus Handte 073bc0bb94 Fix most failing tests.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-08 19:48:52 +01:00
Marcus Handte 002589e54d Continue migration.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-08 17:20:52 +01:00
Marcus Handte 11ee74fa2e Refactor project structure. 2024-03-08 17:20:52 +01:00
heil 6f9a22c517 ng-template bugs after @if transition
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-07 15:54:51 +01:00
heil de7da597a4 ngSwitch -> @Switch
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
bug fixes
2024-03-07 12:29:44 +01:00
heil 2e8871d22e ngFor -> @For finished
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-07 11:41:25 +01:00
heil eb60289066 ngIf -> @If finished
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-07 11:00:58 +01:00
heil 687eb76d4f ngIf ->@If
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-07 10:03:26 +01:00
Marcus Handte 57ee5e1748 Remove thorntail module.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-05 17:52:27 +01:00
Marcus Handte 8f7d88bcdd Fix ios and android app compilation.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-05 17:09:36 +01:00
heil 3544e31198 ngIf -> @if Part I
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-05 16:20:51 +01:00
heil 9ee69a56ac fxLayout -> flex boxes 2024-03-05 16:18:58 +01:00
Marcus Handte 63b23ef902 Update angular.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2024-03-05 07:04:40 +01:00
Marcus Handte fa88d592cb Start migrating angular. 2024-02-29 19:09:47 +01:00
Marcus Handte 9a06bb2630 Refactored api. 2024-02-29 17:45:59 +01:00
Marcus Handte f18dbb57bd Improve ios app for macos and ipad.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2023-01-08 22:29:01 +01:00
Marcus Handte d3e56e9e0f Add minimalist pictures and pcb. Cleanup code.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-13 21:11:57 +01:00
Marcus Handte 2e5d06d9af Update to 1.0.30-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-11 11:47:44 +01:00
Marcus Handte 4d21dea4cd Release 1.0.29
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-11 11:46:36 +01:00
Marcus Handte e4603a231e Add obfuscator for data release.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-08 08:30:51 +01:00
Marcus Handte 316df58af6 Added docs for data release.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-08 08:28:33 +01:00
Marcus Handte 35516af52b Update to 1.0.29-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-03 17:35:44 +01:00
Marcus Handte 3bded2af7a Release 1.0.28
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-03 17:12:48 +01:00
Marcus Handte 2c788e3329 Add weather station configuration to ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-03 16:47:26 +01:00
Marcus Handte af2409a16d Improve handling of intent.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-01 18:25:01 +01:00
Marcus Handte 7e390ed56f Fix navigation graph issues.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-01 17:41:25 +01:00
Marcus Handte 756a816abb Add app updates and paper evaluation.
LocationBasedServices/mowesta/pipeline/head This commit looks good
Add fix for iOS app contained in release 1.1.
Add support for Android 13 to Android app.
Add tools for PerCom paper evaluation.
2022-11-01 17:11:21 +01:00
handte 1e174f77f7 Upgrade to 1.0.28-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-08-03 14:21:27 +02:00
handte ae8e1ddb82 Release 1.0.27
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 19:03:10 +02:00
handte 9381065cf2 Fix touch bug in android, resubmit ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 16:20:30 +02:00
handte 98b4ee71ae Reduce debug output, fix ordering of favorites.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 14:05:05 +02:00
handte 1b84c6fc15 Finish gradient view and prepare app store submission.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 12:27:20 +02:00
handte ad9fb99205 Fix bugs and optimize (somewhat) for tablets.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-23 17:48:09 +02:00
handte 4fdbf10054 Add 2-way (background) synchronization and favorites.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-23 16:58:25 +02:00
handte 3505c379cf Finish ios ui.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-22 17:37:02 +02:00
handte 6322022f47 Backup ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-21 22:46:49 +02:00
handte adf60f289b Backup ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-20 23:34:43 +02:00
handte 27ccac205b Fix bug in android timezone, backup ios.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-17 19:28:10 +02:00
handte 664a7d4cea Update to 1.0.27-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-06-10 22:00:04 +02:00
handte 49137e111b Release 1.0.26
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-06-10 21:56:38 +02:00
handte c834551c52 Improve layouts for tablets.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-06-10 21:52:11 +02:00
handte 91d5a7be50 Fix android app, logging and add export tool.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-06-10 21:00:23 +02:00
braun 552c2215c3 Changed recycler item width on tablets for cities and stations list fragments.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-06-01 12:05:23 +02:00
handte 2e9597f34d Continue iOS implementation.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-29 23:01:56 +02:00
handte ec6f25e11b Started implementation of iOS app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-28 23:33:05 +02:00
handte f871761e48 Increase debug level for file sync.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-25 14:08:00 +02:00
Marcus Handte 60bbfceb7e Update to 1.0.26-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 17:10:24 +02:00
Marcus Handte 0ce1657c0a Release 1.0.25
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 16:58:04 +02:00
Marcus Handte 035aebe741 Update to 1.0.25-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 15:53:49 +02:00
Marcus Handte a829aa01df Release 1.0.24
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 15:52:17 +02:00
Marcus Handte 76315eedc3 Remove deployment to beta.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 15:18:34 +02:00
handte 108df0d614 Remove unused robolectric tests.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-23 15:00:34 +02:00
Marcus Handte 449e128373 Prepare android app for upgrade.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-23 14:47:37 +02:00
handte be53bc8cfa Upgrade Android libraries and Swagger generators.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-22 19:32:37 +02:00
handte 70f8c27341 Upgrade project and dependencies.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-22 13:26:49 +02:00
handte f27c43bf92 Add monitoring script for experiments.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-16 11:53:43 +01:00
handte 5a9e73b72f Update to 1.0.24-SNAPSHOT.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-14 11:36:12 +01:00
handte f2c98815ff Release 1.0.23
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-14 11:21:13 +01:00
handte 99abe5e86e Change library for Sepehr, change widget for Bijan.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-10 16:31:52 +01:00
handte 55a8c55aba Upgrade Android plugin. 2021-12-10 12:25:37 +01:00
handte 16c31df0bf Add workaround for design issue. 2021-12-10 12:01:52 +01:00
handte 10feb5d6aa Update to 1.0.23-SNAPSHOT.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-01 15:14:11 +01:00
handte f8371a4b0a Release 1.0.22
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-01 14:50:22 +01:00
handte f8ed7dfac4 Generate android bundle during releases.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-01 14:45:56 +01:00
handte 5b0f0bef32 Add ad for Eiszeit, add model builder, add esp schematics.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-01 13:38:44 +01:00
handte c207f5470a Properly model build step dependencies.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-10-09 08:16:55 +02:00
handte 1002351f2d Fix missing generation of swagger api docs.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-10-08 10:39:16 +02:00
handte dd4cc41740 Update to 1.0.22-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-09-20 16:24:51 +02:00
handte 3f43df52e9 Release 1.0.21
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-09-20 16:11:20 +02:00
handte de8ad98f8d Improve robustness of SDK service on lower Android version.
LocationBasedServices/mowesta/pipeline/head This commit looks good
Move buffer and upload task to serial queue.
Increase GPS timeout to 90 seconds on pre-24 devices.
Schedule restart of SDK service, if service is shutdown by Android.
Update Android Gradle plugin.
2021-09-20 15:47:07 +02:00
handte 0fc0605a85 Update to 1.0.21-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-30 19:13:14 +02:00
handte 326e56a24c Release 1.0.20
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-30 19:10:44 +02:00
handte 6f388520f5 Add advertisement, fix permissions and bugs.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-30 17:39:16 +02:00
handte c8a52eec58 Fix crash due to to nested nav graph.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-16 13:39:35 +02:00
handte e568f43dd7 Add Arduino code for BME and BMP.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-08 21:07:16 +02:00
handte 22ccdd21ac Update to 1.0.20-SNAPSHOT.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-08 12:45:11 +02:00
handte 6137fface2 Release 1.0.19
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-08 12:33:53 +02:00
handte 4588941a40 Update to 1.0.19-SNAPSHOT.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-08 12:11:58 +02:00
1231 changed files with 66314 additions and 62675 deletions
-485
View File
@@ -1,485 +0,0 @@
<code_scheme name="DefaultIntelliJCodeStyleCST" version="173">
<option name="OTHER_INDENT_OPTIONS">
<value>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</value>
</option>
<option name="LINE_SEPARATOR" value="&#xA;" />
<option name="GENERATE_FINAL_PARAMETERS" value="true" />
<option name="RIGHT_MARGIN" value="200" />
<option name="HTML_KEEP_LINE_BREAKS" value="false" />
<option name="HTML_KEEP_LINE_BREAKS_IN_TEXT" value="false" />
<option name="HTML_INLINE_ELEMENTS" value="a,abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,kbd,label,q,s,samp,select,span,strike,strong,sub,sup,textarea,tt,u,var" />
<AndroidXmlCodeStyleSettings>
<option name="USE_CUSTOM_SETTINGS" value="true" />
</AndroidXmlCodeStyleSettings>
<CssCodeStyleSettings>
<option name="HEX_COLOR_LOWER_CASE" value="true" />
<option name="HEX_COLOR_LONG_FORMAT" value="true" />
</CssCodeStyleSettings>
<HTMLCodeStyleSettings>
<option name="HTML_KEEP_LINE_BREAKS" value="false" />
<option name="HTML_KEEP_LINE_BREAKS_IN_TEXT" value="false" />
<option name="HTML_INLINE_ELEMENTS" value="abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,kbd,q,s,samp,span,strike,strong,sub,sup,textarea,tt,u,var" />
</HTMLCodeStyleSettings>
<JavaeeCodeStyleSettings>
<option name="ENTITY_VO_SUFFIX" value="DTO" />
</JavaeeCodeStyleSettings>
<Objective-C-extensions>
<file>
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Import" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Macro" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Typedef" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Enum" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Constant" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Global" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Struct" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="FunctionPredecl" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Function" />
</file>
<class>
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Property" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Synthesize" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InitMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="StaticMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InstanceMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="DeallocMethod" />
</class>
<extensions>
<pair source="cpp" header="hpp" fileNamingConvention="LOWERCASE" />
<pair source="c" header="h" fileNamingConvention="NONE" />
</extensions>
</Objective-C-extensions>
<Properties>
<option name="KEEP_BLANK_LINES" value="true" />
</Properties>
<TypeScriptCodeStyleSettings version="0">
<option name="FORCE_SEMICOLON_STYLE" value="true" />
<option name="ENFORCE_TRAILING_COMMA" value="WhenMultiline" />
<option name="OBJECT_LITERAL_WRAP" value="1" />
</TypeScriptCodeStyleSettings>
<XML>
<option name="XML_TEXT_WRAP" value="0" />
<option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
</XML>
<codeStyleSettings language="CFML">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="CMake">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="CSS">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="CoffeeScript">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="CONTINUATION_INDENT_SIZE" value="8" />
<option name="TAB_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="DB2">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Derby">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="ECMA Script Level 4">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="GSP">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Gherkin">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Groovy">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="H2">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="HAML">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="HSQLDB">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="HTML">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Haml">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_CHAINED_METHODS" value="true" />
<option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
<option name="METHOD_CALL_CHAIN_WRAP" value="5" />
<option name="WRAP_COMMENTS" value="true" />
<option name="ENUM_CONSTANTS_WRAP" value="1" />
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
<arrangement>
<groups>
<group>
<type>GETTERS_AND_SETTERS</type>
<order>KEEP</order>
</group>
<group>
<type>OVERRIDDEN_METHODS</type>
<order>KEEP</order>
</group>
<group>
<type>DEPENDENT_METHODS</type>
<order>DEPTH_FIRST</order>
</group>
</groups>
<rules>
<section>
<rule>
<match>
<AND>
<FIELD>true</FIELD>
<FINAL>true</FINAL>
<STATIC>true</STATIC>
<visibility />
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<FIELD>true</FIELD>
<STATIC>true</STATIC>
<visibility />
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<FIELD>true</FIELD>
<FINAL>true</FINAL>
<visibility />
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<FIELD>true</FIELD>
<visibility />
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<INITIALIZER_BLOCK>true</INITIALIZER_BLOCK>
<STATIC>true</STATIC>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<INITIALIZER_BLOCK>true</INITIALIZER_BLOCK>
</match>
</rule>
</section>
<section>
<rule>
<match>
<CONSTRUCTOR>true</CONSTRUCTOR>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<METHOD>true</METHOD>
<NAME>main</NAME>
<PUBLIC>true</PUBLIC>
<STATIC>true</STATIC>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<ABSTRACT>true</ABSTRACT>
<METHOD>true</METHOD>
<visibility />
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<ABSTRACT>false</ABSTRACT>
<METHOD>true</METHOD>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<METHOD>true</METHOD>
<STATIC>true</STATIC>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<ENUM>true</ENUM>
</match>
</rule>
</section>
<section>
<rule>
<match>
<INTERFACE>true</INTERFACE>
</match>
</rule>
</section>
<section>
<rule>
<match>
<CLASS>true</CLASS>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<CLASS>true</CLASS>
<STATIC>true</STATIC>
</AND>
</match>
</rule>
</section>
</rules>
</arrangement>
</codeStyleSettings>
<codeStyleSettings language="JSON">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JSP">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JSPX">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JavaScript">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="LESS">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="MySQL">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="ObjectiveC">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Oracle">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="PostgreSQL">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Puppet">
<indentOptions>
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="RHTML">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="CONTINUATION_INDENT_SIZE" value="8" />
<option name="TAB_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="SASS">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="SCSS">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="SQL">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="SQLite">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Stylus">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Sybase">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="TSQL">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="TypeScript">
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="TERNARY_OPERATION_WRAP" value="1" />
<option name="ARRAY_INITIALIZER_WRAP" value="1" />
<option name="IF_BRACE_FORCE" value="1" />
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="XML">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="kotlin">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="ruby">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="CONTINUATION_INDENT_SIZE" value="8" />
<option name="TAB_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
</code_scheme>
Vendored
+21 -7
View File
@@ -5,7 +5,7 @@ node {
// set environment variables
env.ANDROID_SDK_ROOT = '/var/lib/android-sdk'
env.JAVA_HOME = '/opt/openjdk-bin-11'
env.JAVA_HOME = '/opt/openjdk-bin-21'
env.PATH = "${env.JAVA_HOME}/bin:${env.PATH}"
// checkout code from scm
@@ -26,7 +26,7 @@ node {
// build the source code with gradle
stage('Build') {
withCredentials([string(credentialsId: 'mowesta-keystore-password', variable: 'PASSWD')]) {
sh(script: './gradlew -Djenkins.build.number=' + env.BUILD_NUMBER + ' -Dandroid.keystore.password=$PASSWD clean build', label: "Building project.")
sh(script: './gradlew -Djenkins.build.number=' + env.BUILD_NUMBER + ' -Dandroid.keystore.password=$PASSWD clean build -x test', label: "Building project.")
}
}
@@ -45,17 +45,31 @@ node {
// deploy the build output on the server
stage ('Deploy') {
// release = true; // uncomment to temporary enable snapshot deployments
// release = true; // uncomment to temporary enable snapshot deployments
// copy android bundles to apps pro
if (env.BRANCH_NAME == "master") {
echo "Copying android bundles to production server ..."
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
sh 'scp -i $KEYFILE android-app/build/outputs/apk/prod/release/*.apk wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
sh 'scp -i $KEYFILE android-app/build/outputs/bundle/prodRelease/*.aab wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
}
} else {
echo "Skip copying of android bundles for non-master branch."
}
// deploy service to apps pro or apps dev
if (env.BRANCH_NAME == "master" && release) {
echo "Deploying to production server ..."
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
sh 'scp -i $KEYFILE android-app/build/outputs/apk/prod/release/*.apk wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
sh 'scp -i $KEYFILE service-war/build/libs/service-war-' + version + '.war wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-31-mowesta/standalone/deployments/service-war.war'
sh 'scp -i $KEYFILE web-war/build/libs/web-war-' + version + '.war wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-31-mowesta/standalone/deployments/web-war.war'
}
} else if (env.BRANCH_NAME == "master" || env.BRANCH_NAME == "feat/auth") {
} else if (env.BRANCH_NAME == "master") {
echo "Deploying to beta server ..."
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-dev.nes.uni-due.de:/opt/wildfly-21-beta/standalone/deployments/mowesta.ear'
sh 'scp -i $KEYFILE service-war/build/libs/service-war-' + version + '.war mowesta@apps-dev.nes.uni-due.de:/home/mowesta/wildfly/standalone/deployments/service-war.war'
sh 'scp -i $KEYFILE web-war/build/libs/web-war-' + version + '.war mowesta@apps-dev.nes.uni-due.de:/home/mowesta/wildfly/standalone/deployments/web-war.war'
}
} else {
echo "Skipping deployment for non-master branch."
+7
View File
@@ -14,3 +14,10 @@ To build the project, you will have to install [Java](http://www.oracle.com/tech
Pull requests and new commits to any branch are automatically built by a Jenkins service. A Gitea webhook informs the service about changes to the repository. In addition, the service will automatically scan the lbs Gitea organization for new repositories every hour. Successful builds of new commits are indicated by a green tick on the commit page. The build status of pull requests is currently not shown in Gitea. However, you can go to the [Jenkins](https://project.nes.uni-due.de/jenkins/job/LocationBasedServices/job/mowesta/) service to view the result of builds including the console output. To modify the build process, you can change the Jenkinsfile groovy script in the root of the repository, if necessary.
# Configuration
The MoWeSta backend uses a number of system properties to configure the location of input and output folders, the base url of videos and the forecast downlods. You can set them when starting wildfly by passing a ```-DpropretyName=propertyValue``` switch to the standalone.sh. The configurations are:
- *baseDirectory*: Defines where the input and output folders are placed. Default is working directory.
- *limitedMode*: Defines whether to limit the forecast download to cosmo europe. Default is false.
- *videoUrl*: Define the url to prefix the file names with. Default is https://www.mowesta.com/data/video.
+67
View File
@@ -0,0 +1,67 @@
plugins {
id 'org.openapi.generator' version '6.0.0'
}
description = "MoWeSta Android Api"
ext {
swagger_annotations_version = "1.5.24"
jackson_version = "2.10.3"
jackson_databind_version = "2.10.3"
jackson_databind_nullable_version = "0.2.2"
jakarta_annotation_version = "1.3.5"
feign_version = "10.11"
feign_form_version = "3.8.0"
junit_version = "5.7.0"
scribejava_version = "8.0.0"
}
dependencies {
implementation "io.swagger:swagger-annotations:$swagger_annotations_version"
implementation "com.google.code.findbugs:jsr305:3.0.2"
api "io.github.openfeign:feign-core:$feign_version"
implementation "io.github.openfeign:feign-jackson:$feign_version"
implementation "io.github.openfeign:feign-slf4j:$feign_version"
implementation "io.github.openfeign:feign-okhttp:$feign_version"
implementation "io.github.openfeign.form:feign-form:$feign_form_version"
api "com.fasterxml.jackson.core:jackson-core:$jackson_version"
api "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
api "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
implementation "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
implementation "com.github.scribejava:scribejava-core:$scribejava_version"
implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version"
api "de.grundid.opendatalab:geojson-jackson:${versionGeojson}"
}
sourceSets.main.java.srcDirs = ['src/main/java', 'build/swagger/src/main/java']
compileJava {
dependsOn 'generateClient'
}
sourcesJar {
dependsOn 'generateClient'
}
task generateClient(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
dependsOn ':service-api:resolve'
generatorName = "java"
inputSpec = "$projectDir/../service-api/build/swagger/mowesta.json"
outputDir = "$projectDir/build/swagger/"
typeMappings.putAll(["Geometry":"org.geojson.Geometry"])
generateModelTests = false
generateModelDocumentation = false
generateApiTests = false
generateApiDocumentation = false
configOptions = [
invokerPackage: 'com.mowesta.android.feign',
modelPackage: 'com.mowesta.android.feign.model',
apiPackage: 'com.mowesta.android.feign.api',
library: "feign",
dateLibrary: "java8",
importMappings: 'Geometry=org.geojson.Geometry',
annotationLibrary: "none"
]
}
+70 -55
View File
@@ -2,7 +2,31 @@ apply plugin: 'org.handte.gradle-android-eclipse'
apply plugin: 'com.android.application'
apply plugin: 'com.google.android.gms.oss-licenses-plugin'
description = "Mowesta Android App"
description = "MoWeSta Android App"
ext {
// android app dependencies
versionPlay = '17.3.0'
versionAndroidXCore = '1.3.1'
versionAndroidXCoreTest = '2.2.0'
versionAndroidXRecycler = '1.4.0'
versionAndroidXPaging = '2.1.2'
versionAndroidXCard = '1.0.0'
versionAndroidXCoordinator = '1.3.0'
versionAndroidXConstraint = '2.2.2'
versionAndroidXNavigation = '2.10.1'
versionAndroidXLifecycle = '2.10.0'
versionAndroidXSecurity = '1.0.0'
versionAndroidXViewpager = '1.1.0'
versionAndroidXWork = '2.10.5'
versionGoogleMaterial = '1.14.0'
versionAndroidXSwipeRefresh = '1.2.0'
versionAndroidXWebkit = '1.17.0'
versionExoPlayer = '1.6.0'
versionAndroidXProfileInstaller = '1.4.1'
versionApp = '1.4.2'
}
// remove project version to workaround bugs in
// oss-license-plugin that detects local libraries
@@ -11,35 +35,13 @@ description = "Mowesta Android App"
// https://github.com/google/play-services-plugins
project.version = "unspecified"
ext {
// android app dependencies
versionPlay = '17.0.0'
versionAndroidXCore = '1.3.1'
versionAndroidXCoreTest = '2.1.0'
versionAndroidXRecycler = '1.2.1'
versionAndroidXPaging = '2.1.2'
versionAndroidXCard = '1.0.0'
versionAndroidXCoordinator = '1.1.0'
versionAndroidXConstraint = '2.1.0'
versionAndroidXNavigation = '2.3.5'
versionAndroidXLifecycle = '2.3.1'
versionAndroidXSecurity = '1.1.0-alpha03'
versionAndroidXViewpager = '1.0.0'
versionGoogleMaterial = '1.4.0'
versionAndroidXSwipeRefresh = '1.1.0'
versionAndroidXWebkit = '1.4.0'
versionExoPlayer = '2.14.2'
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation project(":android-sdk")
implementation "javax.xml.bind:jaxb-api:${versionJaxb}"
implementation project(":android-api")
implementation "jakarta.xml.bind:jakarta.xml.bind-api:${versionJaxb}"
implementation "androidx.appcompat:appcompat:${versionAndroidXAppcompat}"
implementation "androidx.work:work-runtime:${versionAndroidXWork}"
implementation "com.google.android.material:material:${versionGoogleMaterial}"
implementation "androidx.preference:preference:${versionAndroidXPreference}"
implementation "androidx.cardview:cardview:${versionAndroidXCard}"
@@ -61,9 +63,9 @@ dependencies {
implementation "androidx.webkit:webkit:${versionAndroidXWebkit}"
implementation "com.google.android.exoplayer:exoplayer-core:${versionExoPlayer}"
implementation "com.google.android.exoplayer:exoplayer-ui:${versionExoPlayer}"
implementation "androidx.media3:media3-exoplayer:${versionExoPlayer}"
implementation "androidx.media3:media3-exoplayer-dash:${versionExoPlayer}"
implementation "androidx.media3:media3-ui:${versionExoPlayer}"
implementation "androidx.room:room-runtime:${versionAndroidXRoom}"
annotationProcessor "androidx.room:room-compiler:${versionAndroidXRoom}"
@@ -77,29 +79,29 @@ dependencies {
androidTestImplementation "androidx.navigation:navigation-testing:${versionAndroidXNavigation}"
implementation "com.google.android.gms:play-services-oss-licenses:${versionPlay}"
implementation "androidx.profileinstaller:profileinstaller:${versionAndroidXProfileInstaller}"
testImplementation "junit:junit:${versionJunit}"
testImplementation "androidx.test:core:${versionAndroidXTest}"
testImplementation "androidx.arch.core:core-testing:${versionAndroidXCoreTest}"
testImplementation "org.robolectric:robolectric:${versionRobolectric}"
}
configurations {
all {
exclude group: 'com.google.auto.service', module: 'auto-service'
}
all {
exclude group: 'com.google.auto.service', module: 'auto-service'
exclude group: 'androidx.lifecycle', module: 'lifecycle-viewmodel-ktx'
}
}
android {
compileSdkVersion 30
defaultConfig {
applicationId "com.mowesta.android.app"
minSdkVersion 19
targetSdkVersion 30
versionCode 18
versionName "${version}"
minSdkVersion 24
compileSdk 36
targetSdkVersion 36
versionCode 33
versionName "${versionApp}"
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
resValue "string", "application_long", "MoWeSta"
@@ -123,10 +125,16 @@ android {
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
// add signing config if key is provided via system property
if (System.properties['android.keystore.password'] != null) signingConfig signingConfigs.release
}
@@ -141,7 +149,8 @@ android {
beta {
dimension "backend"
applicationIdSuffix ".beta"
resValue "string", "mowesta_url_default", "https://beta.mowesta.com/api"
resValue "string", "mowesta_url_default", "https://www.mowesta.com/api"
// resValue "string", "mowesta_url_default", "https://beta.mowesta.com/api"
resValue "string", "application_long", "B-MoWeSta"
}
prod {
@@ -152,6 +161,7 @@ android {
buildFeatures {
dataBinding = true
buildConfig = true
}
testOptions {
@@ -159,22 +169,21 @@ android {
includeAndroidResources = true
}
}
lintOptions {
// FragmentTagUsage: replacing fragment with FragmentContainerView breaks Navigation library
// RelativeOverlayp: occurs in video frame which is what we want
// VectorPath: our map and logo representations are very long vectors (consider compressing)
disable 'RelativeOverlap', 'FragmentTagUsage', 'VectorPath'
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lint {
abortOnError false
disable 'RelativeOverlap', 'FragmentTagUsage', 'VectorPath'
}
namespace 'com.mowesta.android.app'
packagingOptions {
resources {
excludes += "META-INF/*.md"
}
}
}
// enable unchecked and deprecation warning during compilation
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
@@ -198,4 +207,10 @@ eclipse {
}
}
tasks.withType(Test).configureEach {
failOnNoDiscoveredTests = false
}
if (System.properties['android.keystore.password'] != null) {
build.dependsOn "bundle"
}
+30 -15
View File
@@ -1,21 +1,36 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Disable symbol and name obfuscation while preserving R8 code shrinking and bytecode optimization
-dontobfuscate
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# Preserve stack traces and line numbers for debugging
-keepattributes SourceFile,LineNumberTable
-keepattributes *Annotation*,Signature,InnerClasses,EnclosingMethod
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
# Keep Jackson annotations and reflection targets
-dontwarn com.fasterxml.jackson.**
-dontwarn feign.**
# Keep API interfaces and model classes used for serialization/reflection
-keep class com.mowesta.android.feign.model.** { *; }
-keep interface com.mowesta.android.feign.api.** { *; }
-keep class org.geojson.** { *; }
# Keep app data classes serialized with Jackson
-keep class com.mowesta.android.app.repository.UserCredentials { *; }
-keep class com.mowesta.android.app.arduino.ArduinoConfig { *; }
-keepclassmembers class * {
@com.fasterxml.jackson.annotation.* <fields>;
@com.fasterxml.jackson.annotation.* <methods>;
}
# Suppress warnings for optional/runtime dependencies
-dontwarn javax.validation.**
-dontwarn javax.xml.bind.**
-dontwarn org.bouncycastle.**
-dontwarn org.conscrypt.**
-dontwarn org.openjsse.**
-dontwarn org.slf4j.**
+5 -25
View File
@@ -1,22 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.mowesta.android.app">
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-sdk tools:overrideLibrary="androidx.security" />
<application android:name=".MowestaApp"
tools:targetApi="24"
android:networkSecurityConfig="@xml/network"
@@ -28,11 +25,10 @@
android:supportsRtl="true"
android:fullBackupContent="@xml/backup">
<activity
android:launchMode="singleTask"
android:launchMode="singleTop"
android:name=".MowestaActivity"
android:windowSoftInputMode="adjustResize"
android:exported="true"
android:label="@string/application_long">
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -52,14 +48,6 @@
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>
<receiver android:name=".MowestaReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
</intent-filter>
</receiver>
<receiver
android:name=".widget.ForecastWidgetProvider"
android:exported="true"
@@ -80,13 +68,5 @@
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/widget_measure" />
</receiver>
<receiver
android:name=".widget.WidgetReceiver"
android:exported="true"/>
<service android:name=".MowestaService" />
<service
android:name=".widget.WidgetService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"/>
</application>
</manifest>
Binary file not shown.
@@ -2,7 +2,9 @@ package com.mowesta.android.app;
import android.content.Context;
import com.google.android.exoplayer2.upstream.cache.Cache;
import androidx.annotation.OptIn;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.datasource.cache.Cache;
import com.mowesta.android.app.repository.ClientFactory;
import com.mowesta.android.app.repository.DeviceRepository;
import com.mowesta.android.app.repository.FavoriteRepository;
@@ -64,6 +66,7 @@ public interface IApp {
*
* @return The cache to store videos.
*/
@OptIn(markerClass = UnstableApi.class)
Cache getMediaCache();
/**
@@ -1,10 +1,13 @@
package com.mowesta.android.app;
import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.HttpResponseCache;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
@@ -14,8 +17,9 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.navigation.Navigation;
import androidx.fragment.app.DialogFragment;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.snackbar.Snackbar;
import com.mowesta.android.app.database.FavoriteDatabase;
import com.mowesta.android.app.repository.UserCredentials;
@@ -48,9 +52,19 @@ public class MowestaActivity extends AppCompatActivity {
private static final int DELAY_REFRESH = 15 * 60 * 1000;
/**
* The code used to request the permissions.
* Requests the permission to issue notifications.
*/
private static final int CODE_REQUEST_PERMISSIONS = 3334;
public static final int CODE_REQUEST_POST_NOTIFICATION = 3333;
/**
* The code used to request the permission for localizing in the foreground.
*/
public static final int CODE_REQUEST_FOREGROUND_PERMISSIONS = 3334;
/**
* The code used to request the permission for localizing in the background.
*/
private static final int CODE_REQUEST_BACKGROUND_PERMISSIONS = 3335;
/**
* The preferences.
@@ -88,22 +102,6 @@ public class MowestaActivity extends AppCompatActivity {
);
/**
* The listener that observes the activation of the mowesta sdk service
* and checks for the permissions.
*/
private OnSharedPreferenceChangeListener preferenceListener = (prefs, key) -> {
if (MowestaSettings.PRIVACY_MEASURE.equals(key)) {
if (settings.isPrivacyMeasure()) {
if (!PermissionUtil.hasBackgroundPermissions(this)) requestPermissions();
else MowestaService.startService(this);
} else {
MowestaService.stopService(this);
}
}
};
public MowestaActivity() {
super(R.layout.activity_app);
}
@@ -121,22 +119,9 @@ public class MowestaActivity extends AppCompatActivity {
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// got to navigation drawer when user presses notification
setIntent(intent);
Navigation.findNavController(this, R.id.navigation_app).navigate(R.id.action_drawer);
}
@Override
protected void onResume() {
super.onResume();
settings.getPreferences().registerOnSharedPreferenceChangeListener(preferenceListener);
}
@Override
protected void onPause() {
super.onPause();
settings.getPreferences().unregisterOnSharedPreferenceChangeListener(preferenceListener);
}
@Override
protected void onStop() {
@@ -172,18 +157,15 @@ public class MowestaActivity extends AppCompatActivity {
/**
* Method to request location permission for the app.
*/
public void requestPermissions() {
public void requestPermissions(boolean skipNotification) {
Log.d(TAG, "Requesting permissions.");
requestPermissions(PermissionUtil.getNonGrantedBackgroundPermissions(this));
}
/**
* Requests the permissions.
*
* @param permissions The permissions to request.
*/
public void requestPermissions(String[] permissions) {
ActivityCompat.requestPermissions(this, permissions, CODE_REQUEST_PERMISSIONS);
if (!skipNotification && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !PermissionUtil.hasNotificationPermission(this)) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, CODE_REQUEST_POST_NOTIFICATION);
} else if (!PermissionUtil.hasPermissions(this, PermissionUtil.getForegroundPermissions(this))) {
ActivityCompat.requestPermissions(this, PermissionUtil.getForegroundPermissions(this), CODE_REQUEST_BACKGROUND_PERMISSIONS);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_BACKGROUND_LOCATION }, CODE_REQUEST_BACKGROUND_PERMISSIONS);
}
}
/**
@@ -197,7 +179,13 @@ public class MowestaActivity extends AppCompatActivity {
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CODE_REQUEST_PERMISSIONS: {
case CODE_REQUEST_POST_NOTIFICATION: {
if (!PermissionUtil.hasBackgroundPermissions(this))
requestPermissions(true);
break;
}
case CODE_REQUEST_BACKGROUND_PERMISSIONS:
case CODE_REQUEST_FOREGROUND_PERMISSIONS: {
boolean granted = true;
StringBuilder b = new StringBuilder();
for (int i = 0, s = Math.min(permissions.length, grantResults.length); i < s; i++) {
@@ -207,10 +195,7 @@ public class MowestaActivity extends AppCompatActivity {
}
Log.d(TAG, "Permission result: " + b.toString());
if (!granted) {
settings.setPrivacyMeasure(false);
showMissingPermission();
} else {
MowestaService.startService(this);
showMissingPermission(requestCode == CODE_REQUEST_FOREGROUND_PERMISSIONS);
}
break;
}
@@ -222,22 +207,59 @@ public class MowestaActivity extends AppCompatActivity {
/**
* Shows a snackbar indicating a missing permission.
*/
public void showMissingPermission() {
View coordinator = findViewById(R.id.layout_coordinator);
Snackbar.make(coordinator, R.string.message_no_permission, Snackbar.LENGTH_LONG )
.setAction(R.string.button_configure, (view) -> {
// go to app settings
public void showMissingPermission(boolean foreground) {
PermissionDialogFragment pdf = PermissionDialogFragment.newInstance(foreground);
pdf.show(getSupportFragmentManager(), "permissions");
}
/**
* A dialog fragment to explain the need for permissions.
*
* @author Marcus
*/
public static class PermissionDialogFragment extends DialogFragment {
private static final String KEY_FOREGROUND = "foreground";
public static PermissionDialogFragment newInstance(boolean foreground) {
PermissionDialogFragment f = new PermissionDialogFragment();
Bundle b = new Bundle();
b.putBoolean(KEY_FOREGROUND, foreground);
f.setArguments(b);
return f;
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
MaterialAlertDialogBuilder b = new MaterialAlertDialogBuilder(getActivity());
b.setTitle(R.string.message_permission_title);
b.setMessage(isForeground()?R.string.message_permission_foreground:R.string.message_permission_background);
b.setIcon(R.drawable.ic_gps_off_normal_24);
b.setNeutralButton(R.string.button_configure, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", getPackageName(), null);
Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
try {
startActivity(intent);
} catch (Exception e) {
View coordinator = getActivity().findViewById(R.id.layout_coordinator);
Snackbar.make(coordinator, R.string.message_configure_failed,
Snackbar.LENGTH_SHORT).show();
}
}).show();
}
});
return b.show();
}
private boolean isForeground() {
Bundle b = getArguments();
return b.getBoolean(KEY_FOREGROUND, false);
}
}
}
@@ -4,16 +4,16 @@ import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.StrictMode;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.media3.common.util.UnstableApi;
import androidx.preference.PreferenceManager;
import com.google.android.exoplayer2.database.ExoDatabaseProvider;
import com.google.android.exoplayer2.upstream.cache.Cache;
import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.mowesta.android.app.database.Widget;
import androidx.media3.database.StandaloneDatabaseProvider;
import androidx.media3.datasource.cache.Cache;
import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor;
import androidx.media3.datasource.cache.SimpleCache;
import com.mowesta.android.app.repository.ClientFactory;
import com.mowesta.android.app.repository.DeviceRepository;
import com.mowesta.android.app.repository.FavoriteRepository;
@@ -22,7 +22,7 @@ import com.mowesta.android.app.repository.WidgetRepository;
import com.mowesta.android.app.widget.AbstractWidgetProvider;
import com.mowesta.android.app.widget.ForecastWidgetProvider;
import com.mowesta.android.app.widget.MeasureWidgetProvider;
import com.mowesta.android.app.widget.WidgetReceiver;
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
import java.io.File;
@@ -32,8 +32,12 @@ import java.io.File;
*
* @author Marcus
*/
@UnstableApi
public class MowestaApp extends Application implements IApp {
/** The log tag. */
public static final String TAG = "MowestaApp";
/**
* The widget providers of the app.
*/
@@ -81,9 +85,8 @@ public class MowestaApp extends Application implements IApp {
deviceRepository = new DeviceRepository.Builder().setTrace(false).build(this);
favoriteRepository = new FavoriteRepository(this);
widgetRepository = new WidgetRepository(this);
MowestaService.startService(this);
WidgetReceiver.updateWidgets(this);
WidgetReceiver.scheduleUpdates(this);
PeriodicWidgetWorker.updateWidgets(this);
PeriodicWidgetWorker.scheduleUpdates(this);
//if(BuildConfig.DEBUG)
// StrictMode.enableDefaults();
}
@@ -91,8 +94,9 @@ public class MowestaApp extends Application implements IApp {
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "Configuration change detected.");
for (int i = widgetProviders.length - 1; i >= 0; i--) {
widgetProviders[i].triggerUpdates(this, false);
widgetProviders[i].triggerUpdates(MowestaApp.this, false);
}
}
@@ -135,7 +139,7 @@ public class MowestaApp extends Application implements IApp {
if (mediaCache == null) {
mediaCache = new SimpleCache(new File(this.getCacheDir(), "videos"),
new LeastRecentlyUsedCacheEvictor(25 * 1000 * 1000),
new ExoDatabaseProvider(getContext()));
new StandaloneDatabaseProvider(getContext()));
}
return mediaCache;
}
@@ -1,34 +0,0 @@
package com.mowesta.android.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* A broadcast receiver that starts the background service after
* a reboot and when the package is updated.
*
* @author Marcus
*/
public class MowestaReceiver extends BroadcastReceiver {
/**
* The log tag of the receiver.
*/
private static final String TAG = "MowestaBootReceiver";
@Override
public void onReceive(Context context, Intent intent) {
// should not happen but nobody likes crashing apps in background
if (intent == null || context == null) return;
Log.d(TAG, "Received an intent with action " + intent.getAction() + ".");
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) ||
Intent.ACTION_MY_PACKAGE_REPLACED.equals(intent.getAction())) {
MowestaService.startService(context);
}
}
}
@@ -1,61 +0,0 @@
package com.mowesta.android.app;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import com.mowesta.android.app.util.PermissionUtil;
import com.mowesta.android.feign.api.DefaultApi;
import com.mowesta.android.sdk.SdkService;
/**
* A service to perform background measurements.
*
* @author Marcus, Katharina, Arman
*/
public class MowestaService extends SdkService {
@Override
protected boolean isEnabled() {
IApp app = (IApp)getApplication();
MowestaSettings settings = app.getSettings();
return settings.isPrivacyMeasure() && app.getDeviceRepository().getHandle().getValue() != null;
}
@Override
protected DefaultApi createApiClient() {
IApp app = (IApp)getApplication();
String handle = app.getDeviceRepository().getHandle().getValue();
return app.getClientFactory().createClient(handle);
}
/**
* Starts the service.
*
* @param context A context object.
*/
public static void startService(Context context) {
if (!PermissionUtil.hasBackgroundPermissions(context)) return;
IApp app = (IApp)context.getApplicationContext();
MowestaSettings settings = app.getSettings();
if (!settings.isPrivacyMeasure() || app.getDeviceRepository().getHandle().getValue() == null) return;
Intent intent = new Intent();
intent.setClass(context, MowestaService.class);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
context.startService(intent);
} else {
context.startForegroundService(intent);
}
}
/**
* Stops the running service.
*
* @param context A context object.
*/
public static void stopService(Context context) {
Intent intent = new Intent();
intent.setClass(context, MowestaService.class);
context.stopService(intent);
}
}
@@ -6,16 +6,13 @@ import android.content.SharedPreferences;
import android.content.res.Resources;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import androidx.preference.Preference;
import androidx.preference.PreferenceManager;
import com.mowesta.android.sdk.SdkSettings;
/**
* A utility class to manage the settings.
*/
public class MowestaSettings extends SdkSettings {
public class MowestaSettings {
/**
* An enumeration with the unit system used throughout
@@ -99,14 +96,53 @@ public class MowestaSettings extends SdkSettings {
public static final String TEMPERATURE_UNIT = "temperature_unit";
/**
* Creates the settings with the context.
* The shared preferences for the application.
*/
protected @NonNull SharedPreferences preferences;
/**
* The application context.
*/
protected @NonNull Application application;
/**
* Creates a new settings object to query and modify the
* settings.
*
* @param application The context.
* @param application The application.
*/
public MowestaSettings(@NonNull Application application) {
super(application);
this.application = application;
this.preferences = PreferenceManager.getDefaultSharedPreferences(application);
}
/**
* Returns the underlying shared preferences.
*
* @return The preferences.
*/
public @NonNull SharedPreferences getPreferences() {
return preferences;
}
/**
* Returns the application context.
*
* @return The application context
*/
public @NonNull
Context getContext() { return application.getApplicationContext(); }
/**
* Returns the application resources.
*
* @return The application resources.
*/
public @NonNull
Resources getResources() { return getContext().getResources(); }
/**
* Determines whether the current terms are accepted.
*
@@ -10,7 +10,7 @@ import android.util.Log;
import androidx.annotation.NonNull;
import com.mowesta.android.sdk.task.AbstractTask;
import com.mowesta.android.app.task.AbstractTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
@@ -235,7 +235,7 @@ public class BindingAdapters {
res = R.string.city_type_village;
break;
}
if (city.isCapital()) {
if (city.getCapital()) {
res = R.string.city_type_capital;
}
}
@@ -858,6 +858,7 @@ public class BindingAdapters {
if (valueText != null) {
if (text == null) {
text = valueText;
break; // only use first value (since it looks bad otherwise)
} else {
text = view.getResources().getString(R.string.format_two_lines, text, valueText);
}
@@ -5,9 +5,11 @@ import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.recyclerview.widget.RecyclerView;
import com.mowesta.android.app.IApp;
@@ -41,7 +43,6 @@ public abstract class AbstractDiagramFragment extends AbstractNetworkFragment {
public void onCreate(@Nullable Bundle savedInstanceState) {
settings = ((IApp)getContext().getApplicationContext()).getSettings();
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
@@ -64,25 +65,29 @@ public abstract class AbstractDiagramFragment extends AbstractNetworkFragment {
public abstract void onRefreshDiagram();
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_unit, menu);
}
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_unit, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_unit_system) {
UnitSystemDialogFragment system = new UnitSystemDialogFragment();
system.show(getChildFragmentManager(), "system");
return true;
} else if (itemId == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
return true;
}
return super.onOptionsItemSelected(item);
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_unit_system) {
UnitSystemDialogFragment system = new UnitSystemDialogFragment();
system.show(getChildFragmentManager(), "system");
return true;
} else if (itemId == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
return true;
}
return false;
}
}, getViewLifecycleOwner());
}
}
@@ -11,6 +11,7 @@ import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.fragment.app.Fragment;
import com.mowesta.android.app.R;
@@ -44,12 +45,6 @@ public abstract class AbstractPlaceFragment extends AbstractNetworkFragment {
*/
protected abstract AbstractPlaceViewModel getPlaceViewModel();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
@@ -58,45 +53,46 @@ public abstract class AbstractPlaceFragment extends AbstractNetworkFragment {
model.getCoordinate().observe(getViewLifecycleOwner(), (v) -> getActivity().invalidateOptionsMenu());
model.getFavorite().observe(getViewLifecycleOwner(), (v) -> getActivity().invalidateOptionsMenu());
model.getWikipedia().observe(getViewLifecycleOwner() ,(v) -> getActivity().invalidateOptionsMenu());
}
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_place, menu);
AbstractPlaceViewModel model = getPlaceViewModel();
Boolean favorite = model.getFavorite().getValue();
if (favorite == null || favorite) {
menu.removeItem(R.id.action_favorite_add);
}
if (favorite == null || !favorite) {
menu.removeItem(R.id.action_favorite_remove);
}
if (model.getWikipedia().getValue() == null) {
menu.removeItem(R.id.action_wikipedia);
}
if (model.getCoordinate().getValue() == null) {
menu.removeItem(R.id.action_google_maps);
}
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_place, menu);
AbstractPlaceViewModel model = getPlaceViewModel();
Boolean favorite = model.getFavorite().getValue();
if (favorite == null || favorite) {
menu.removeItem(R.id.action_favorite_add);
}
if (favorite == null || !favorite) {
menu.removeItem(R.id.action_favorite_remove);
}
if (model.getWikipedia().getValue() == null) {
menu.removeItem(R.id.action_wikipedia);
}
if (model.getCoordinate().getValue() == null) {
menu.removeItem(R.id.action_google_maps);
}
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_favorite_add) {
getPlaceViewModel().addFavorite();
return true;
} else if (itemId == R.id.action_favorite_remove) {
getPlaceViewModel().removeFavorite();
return true;
} else if (itemId == R.id.action_wikipedia) {
openWikipedia();
return true;
} else if (itemId == R.id.action_google_maps) {
openGoogleMaps();
return true;
}
return false;
}
}, getViewLifecycleOwner());
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_favorite_add) {
getPlaceViewModel().addFavorite();
return true;
} else if (itemId == R.id.action_favorite_remove) {
getPlaceViewModel().removeFavorite();
return true;
} else if (itemId == R.id.action_wikipedia) {
openWikipedia();
return true;
} else if (itemId == R.id.action_google_maps) {
openGoogleMaps();
return true;
}
return false;
}
/**
@@ -0,0 +1,97 @@
package com.mowesta.android.app.fragment;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.preference.PreferenceManager;
import androidx.media3.ui.AspectRatioFrameLayout;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.snackbar.Snackbar;
import com.mowesta.android.app.R;
import com.mowesta.android.app.databinding.DialogAdvertiseBinding;
import com.mowesta.android.app.model.AdvertiseViewModel;
public class AdvertiseDialogFragment extends BottomSheetDialogFragment {
public static final String KEY_ADVERTISEMENT = "advertisement";
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
BottomSheetDialog d = (BottomSheetDialog) dialog;
FrameLayout bottomSheet = (FrameLayout) d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);
}
});
return dialog;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
DialogAdvertiseBinding binding = DataBindingUtil.inflate(inflater, R.layout.dialog_advertise, container, false);
AdvertiseViewModel model = new ViewModelProvider(this).get(AdvertiseViewModel.class);
binding.setModel(model);
binding.setLifecycleOwner(getViewLifecycleOwner());
binding.videoView.setPlayer(model.getExoPlayer());
binding.videoView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
model.getClose().observe(getViewLifecycleOwner(), (v) -> { if (v) this.dismiss(); } );
model.getOpen().observe(getViewLifecycleOwner(), (v) -> {
if (v) {
String url = "https://www.mowesta.com/2022/05/23/fair-experiment-bei-das-fest-in-karlsruhe/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Snackbar.make(getView(), R.string.message_no_browser, Snackbar.LENGTH_SHORT).show();
}
model.getOpen().setValue(Boolean.FALSE);
}
});
return binding.getRoot();
}
public boolean shouldShow(Context context) {
long time = System.currentTimeMillis();
if (time > 1658700000000l) return false;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
long last = prefs.getLong(KEY_ADVERTISEMENT, 0);
return (time - last > 7 * 24* 60 * 60 * 1000);
}
@Override
public void onDismiss(@NonNull DialogInterface dialog) {
super.onDismiss(dialog);
Context context = getActivity();
if (context != null) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor e = prefs.edit();
e.putLong(KEY_ADVERTISEMENT, System.currentTimeMillis());
e.apply();
}
}
}
@@ -1,5 +1,6 @@
package com.mowesta.android.app.fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
@@ -18,6 +19,9 @@ import com.mowesta.android.app.adapter.CityEntryPagedListAdapter;
import com.mowesta.android.app.model.AbstractNetworkViewModel;
import com.mowesta.android.app.model.CitiesViewModel;
import com.mowesta.android.app.model.StateViewModel;
import com.mowesta.android.app.util.TabletUtil;
import org.jetbrains.annotations.NotNull;
/**
@@ -26,6 +30,7 @@ import com.mowesta.android.app.model.StateViewModel;
* @author Marcus
*/
public class CitiesFragment extends AbstractNetworkFragment {
private RecyclerView recyclerView;
@Override
protected AbstractNetworkViewModel getNetworkViewModel() {
@@ -38,10 +43,27 @@ public class CitiesFragment extends AbstractNetworkFragment {
return inflater.inflate(R.layout.fragment_cities, container, false);
}
private void applyGridWidth() {
if (!TabletUtil.isTablet(requireContext())) {
return;
}
int width = requireContext().getResources().getInteger(R.integer.RecyclerWidth);
TabletUtil.setGridLayout(recyclerView, width);
}
@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
applyGridWidth();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = view.findViewById(R.id.recycler);
recyclerView = view.findViewById(R.id.recycler);
applyGridWidth();
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
CityEntryPagedListAdapter adapter = new CityEntryPagedListAdapter(getViewLifecycleOwner(), (city) -> {
if (city != null) {
@@ -12,6 +12,7 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.MenuProvider;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
@@ -71,30 +72,6 @@ public class CityFragment extends AbstractPlaceFragment {
return getView().findViewById(R.id.bottom_navigation);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_customize, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_customize) {
getChildFragmentManager()
.beginTransaction()
.add(new CustomizeDialogFragment(), "customize")
.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
@@ -121,10 +98,31 @@ public class CityFragment extends AbstractPlaceFragment {
NavController controller = Navigation.findNavController(root.findViewById(R.id.navigation_city));
NavigationUI.setupWithNavController(binding.bottomNavigation, controller);
AppBarConfiguration.Builder builder = new AppBarConfiguration.Builder(R.id.destination_drawer);
builder.setFallbackOnNavigateUpListener(() -> { getActivity().onBackPressed(); return true; });
builder.setFallbackOnNavigateUpListener(() -> { getActivity().getOnBackPressedDispatcher().onBackPressed(); return true; });
NavigationUI.setupWithNavController(layout, toolbar, controller, builder.build());
return root;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_customize, menu);
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_customize) {
getChildFragmentManager()
.beginTransaction()
.add(new CustomizeDialogFragment(), "customize")
.commit();
return true;
}
return false;
}
}, getViewLifecycleOwner());
}
}
@@ -55,11 +55,6 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
*/
private TimeUtils timeUtils = new TimeUtils(System.currentTimeMillis(), null);
/**
* The view pager of the parent.
*/
private ViewPager2 pager;
/**
* The date formatter.
*/
@@ -94,8 +89,6 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
dateFormatter = new DateFormatter(getContext());
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_gradient, container, false);
// this is quite ugly, but we need to disable the view pager and collapse the toolbar
pager = getActivity().findViewById(R.id.pager);
AppBarLayout layout = getActivity().findViewById(R.id.layout_appbar);
binding.gradientProgress1.setMax(TIMEOUT_REMOVER);
binding.gradientProgress2.setMax(TIMEOUT_REMOVER);
animator = ValueAnimator.ofInt(TIMEOUT_REMOVER, 0);
@@ -110,34 +103,7 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
binding.gradientText.setAlpha(Math.min(1, Math.max(0, value / 1000f)));
}
});
binding.gradientScroll.setOnTouchListener(binding.gradientTouch.createOnTouchListener(new TimeView.OnSlideListener() {
@Override
public void onSlide(float relative) {
if (!hasData()) return;
animator.cancel();
binding.gradientProgress1.setProgress(TIMEOUT_REMOVER);
binding.gradientProgress2.setProgress(TIMEOUT_REMOVER);
binding.gradientText.setAlpha(1);
handler.removeCallbacks(remover);
if (!closed) {
layout.setExpanded(false, true);
closed = true;
}
pager.setUserInputEnabled(false);
updateSelection(relative);
updateCondition(relative);
binding.gradientText.setVisibility(View.VISIBLE);
updateGuide(relative);
}
@Override
public void onSlideEnd() {
pager.setUserInputEnabled(true);
closed = false;
animator.start();
handler.postDelayed(remover, TIMEOUT_REMOVER);
}
}));
binding.setLifecycleOwner(getViewLifecycleOwner());
binding.gradientText.setVisibility(View.GONE);
@@ -278,7 +244,53 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
public void onPause() {
handler.removeCallbacks(remover);
remover.run();
binding.gradientScroll.setOnTouchListener(null);
super.onPause();
}
@Override
public void onResume() {
super.onResume();
AppBarLayout layout = getActivity().findViewById(R.id.layout_appbar);
ViewPager2 pager = getActivity().findViewById(R.id.pager);
binding.gradientScroll.setOnTouchListener(binding.gradientTouch.createOnTouchListener(new TimeView.OnSlideListener() {
@Override
public void onSlide(float relative) {
if (!hasData()) return;
animator.cancel();
binding.gradientProgress1.setProgress(TIMEOUT_REMOVER);
binding.gradientProgress2.setProgress(TIMEOUT_REMOVER);
binding.gradientText.setAlpha(1);
handler.removeCallbacks(remover);
if (!closed) {
if (layout != null)
layout.setExpanded(false, true);
closed = true;
}
if (pager != null)
pager.setUserInputEnabled(false);
updateSelection(relative);
updateCondition(relative);
binding.gradientText.setVisibility(View.VISIBLE);
updateGuide(relative);
}
@Override
public void onSlideEnd() {
if (pager != null)
pager.setUserInputEnabled(true);
closed = false;
animator.start();
handler.postDelayed(remover, TIMEOUT_REMOVER);
}
}));
}
@Override
public void onDestroyView() {
binding.gradientTouch.setOnTouchListener(null);
super.onDestroyView();
}
}
@@ -1,146 +0,0 @@
package com.mowesta.android.app.fragment;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.CompoundButton;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import com.google.android.material.snackbar.Snackbar;
import com.mowesta.android.app.IApp;
import com.mowesta.android.app.MowestaSettings;
import com.mowesta.android.app.R;
import com.mowesta.android.app.databinding.FragmentCollectionBinding;
import com.mowesta.android.app.util.DisplayUtils;
import java.util.ArrayList;
import java.util.List;
/**
* The fragment to onboard the user with data collection.
*
* @author Marcus
*/
public class CollectionFragment extends Fragment {
/**
* The settings.
*/
private MowestaSettings settings;
/**
* The view binding.
*/
private FragmentCollectionBinding binding;
/**
* Keeps track of preference and updates the state of the switch.
*/
private OnSharedPreferenceChangeListener preferenceListener = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
binding.privacyMeasureSwitch.setChecked(settings.isPrivacyMeasure());
}
};
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.settings = ((IApp)getContext().getApplicationContext()).getSettings();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_collection, container, false);
binding.buttonContinue.setOnClickListener((v) -> {
Navigation.findNavController(binding.getRoot()).navigate(R.id.action_collection_drawer);
settings.setCollectionShown(true);
}
);
binding.privacyMeasureSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
boolean current = settings.isPrivacyMeasure();
if (current != isChecked) {
settings.setPrivacyMeasure(isChecked);
}
}
});
binding.logoFair.setOnClickListener((v) -> openBrowser(R.string.fair_url));
binding.logoUde.setOnClickListener((v) -> openBrowser(R.string.ude_url));
// add a funky animation
if (savedInstanceState == null) {
List<View> views = new ArrayList<>();
views.add(binding.collectionNoteLocation);
views.add(binding.collectionNoteData);
views.add(binding.collectionNoteEnable);
views.add(binding.privacyMeasureSwitch);
views.add(binding.collectionNotePermission);
views.add(binding.buttonContinue);
AnimatorSet set = new AnimatorSet();
ObjectAnimator first = ObjectAnimator.ofFloat(binding.logoSun, "translationY", DisplayUtils.dpToPixels(getContext(), 90), 0f);
first.setDuration(1000);
first.setInterpolator(new OvershootInterpolator());
ObjectAnimator last = ObjectAnimator.ofFloat(binding.logoSun, "translationX", DisplayUtils.dpToPixels(getContext(), 90), 0f);
last.setInterpolator(new AccelerateDecelerateInterpolator());
last.setDuration(1000);
set.playTogether(first, last);
for (View view: views) {
view.setAlpha(0);
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "alpha", 0, 1);
objectAnimator.setInterpolator(new LinearInterpolator());
objectAnimator.setDuration(100);
set.play(objectAnimator).after(last);
last = objectAnimator;
}
set.start();
}
return binding.getRoot();
}
/**
* Opens the url to which the resource string is pointing in a browser.
*
* @param res The resource pointing to a string representing the url.
*/
private void openBrowser(int res) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(getResources().getString(res)));
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Snackbar.make(getView(), R.string.message_no_browser, Snackbar.LENGTH_SHORT).show();
}
}
@Override
public void onResume() {
super.onResume();
settings.getPreferences().registerOnSharedPreferenceChangeListener(preferenceListener);
binding.privacyMeasureSwitch.setChecked(settings.isPrivacyMeasure());
}
@Override
public void onPause() {
super.onPause();
settings.getPreferences().unregisterOnSharedPreferenceChangeListener(preferenceListener);
}
}
@@ -218,7 +218,7 @@ public class ConnectFragment extends Fragment {
});
Args args = Args.fromBundle(getArguments());
if (args == null) {
getActivity().onBackPressed();
getActivity().getOnBackPressedDispatcher().onBackPressed();
} else {
model.init(args);
}
@@ -293,7 +293,7 @@ public class ConnectFragment extends Fragment {
if (binding != null) {
binding.connectSun.setAlpha(0f);
TypedValue typedValue = new TypedValue();
getActivity().getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
getActivity().getTheme().resolveAttribute(androidx.appcompat.R.attr.colorControlNormal, typedValue, true);
int color = ContextCompat.getColor(getActivity(), typedValue.resourceId);
ImageViewCompat.setImageTintList(binding.connectConfigure, ColorStateList.valueOf(color));
ImageViewCompat.setImageTintList(binding.connectDevice, ColorStateList.valueOf(color));
@@ -83,7 +83,7 @@ public class CountryFragment extends AbstractPlaceFragment {
binding.setModel(model);
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
AppBarConfiguration.Builder builder = new AppBarConfiguration.Builder();
builder.setFallbackOnNavigateUpListener(() -> { getActivity().onBackPressed(); return true; });
builder.setFallbackOnNavigateUpListener(() -> { getActivity().getOnBackPressedDispatcher().onBackPressed(); return true; });
NavigationUI.setupWithNavController(layout, toolbar, controller, builder.build());
return root;
}
@@ -71,7 +71,7 @@ public class DeviceFragment extends AbstractDiagramFragment {
binding.setModel(model);
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
AppBarConfiguration.Builder builder = new AppBarConfiguration.Builder();
builder.setFallbackOnNavigateUpListener(() -> { getActivity().onBackPressed(); return true; });
builder.setFallbackOnNavigateUpListener(() -> { getActivity().getOnBackPressedDispatcher().onBackPressed(); return true; });
NavigationUI.setupWithNavController(layout, toolbar, controller, builder.build());
IApp app = (IApp)getContext().getApplicationContext();
app.getUserRepository().getCredentials().observe(getViewLifecycleOwner(), (c) -> model.setUserCredentials(c));
@@ -10,6 +10,7 @@ import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
@@ -39,12 +40,6 @@ public class DevicesFragment extends AbstractNetworkFragment {
return new ViewModelProvider(this).get(DevicesViewModel.class);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
@@ -55,6 +50,22 @@ public class DevicesFragment extends AbstractNetworkFragment {
Bundle bundle = new Bundle();
controller.navigate(R.id.destination_setup, bundle, opts.build());
});
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_refresh, menu);
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
DevicesViewModel model = new ViewModelProvider(DevicesFragment.this).get(DevicesViewModel.class);
model.reload();
return true;
}
return false;
}
}, getViewLifecycleOwner());
return binding.getRoot();
}
@@ -84,21 +95,6 @@ public class DevicesFragment extends AbstractNetworkFragment {
swipeRefreshLayout.setOnRefreshListener(() -> model.reload());
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_refresh, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
DevicesViewModel model = new ViewModelProvider(this).get(DevicesViewModel.class);
model.reload();
return true;
}
return false;
}
}
@@ -9,6 +9,8 @@ import android.database.AbstractCursor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
@@ -26,6 +28,7 @@ import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.MenuProvider;
import androidx.cursoradapter.widget.CursorAdapter;
import androidx.customview.widget.Openable;
import androidx.databinding.DataBindingUtil;
@@ -76,44 +79,6 @@ public class DrawerFragment extends AbstractNetworkFragment {
return new ViewModelProvider(this).get(DrawerViewModel.class);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onResume() {
super.onResume();
preventSplashScreen();
handleNotificationIntent();
}
/**
* Prevent going back to the splash screen if opened through deep link.
*/
private void preventSplashScreen() {
NavController nav = Navigation.findNavController(getActivity().findViewById(R.id.navigation_app));
if (nav.getGraph().getId() != R.id.navigation_core) {
nav.setGraph(R.navigation.navigation_core);
}
}
/**
* Checks if the intent was generated by the background service and
* opens the settings screen, if this is the case
*/
private void handleNotificationIntent() {
Intent intent = getActivity().getIntent();
if (intent.hasExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name))) {
String value = intent.getStringExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name));
if (value != null && value.equals(getString(R.string.mowesta_sdk_notification_activity_extra_value))) {
Navigation.findNavController(getView().findViewById(R.id.navigation_drawer)).navigate(R.id.destination_settings);
getActivity().setIntent(new Intent());
}
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
@@ -121,48 +86,52 @@ public class DrawerFragment extends AbstractNetworkFragment {
Toolbar toolbar = view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
loadingProgressBar = view.findViewById(R.id.progress_bar);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
menuInflater.inflate(R.menu.menu_search, menu);
SearchView search = (SearchView)menu.findItem(R.id.action_search).getActionView();
search.setQueryHint(getString(R.string.action_search));
SearchView.SearchAutoComplete complete = search.findViewById(androidx.appcompat.R.id.search_src_text);
complete.setDropDownBackgroundResource(R.color.bg_search);
final DrawerViewModel model = new ViewModelProvider(DrawerFragment.this).get(DrawerViewModel.class);
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
model.setTerm(newText);
return true;
}
});
search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int position) {
showLocation(model, position);
return true;
}
@Override
public boolean onSuggestionClick(int position) {
showLocation(model, position);
return true;
}
});
search.setSuggestionsAdapter(new LocationCursorAdapter(getContext(), model.getResults()));
AppBarLayout appbar = getView().findViewById(R.id.layout_appbar);
search.setOnSearchClickListener((v)->appbar.setExpanded(false, true));
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
return false;
}
}, getViewLifecycleOwner());
return view;
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_search, menu);
SearchView search = (SearchView)menu.findItem(R.id.action_search).getActionView();
search.setQueryHint(getString(R.string.action_search));
SearchView.SearchAutoComplete complete = search.findViewById(androidx.appcompat.R.id.search_src_text);
complete.setDropDownBackgroundResource(R.color.bg_search);
final DrawerViewModel model = new ViewModelProvider(this).get(DrawerViewModel.class);
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
model.setTerm(newText);
return true;
}
});
search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int position) {
showLocation(model, position);
return true;
}
@Override
public boolean onSuggestionClick(int position) {
showLocation(model, position);
return true;
}
});
search.setSuggestionsAdapter(new LocationCursorAdapter(getContext(), model.getResults()));
AppBarLayout appbar = getView().findViewById(R.id.layout_appbar);
search.setOnSearchClickListener((v)->appbar.setExpanded(false, true));
}
private void showLocation(DrawerViewModel model, int position) {
LocationHierarchyPage page = model.getResults().getValue();
LocationHierarchy dest = page.getElements().get(position);
@@ -10,6 +10,7 @@ import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
@@ -40,23 +41,53 @@ import java.util.List;
*/
public class FavoritesFragment extends Fragment {
private static final String TAG_ADVERTISEMENT = "ad";
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// possibly show the ad for eiszeit
AdvertiseDialogFragment adf = new AdvertiseDialogFragment();
if (adf.shouldShow(getContext()) && getChildFragmentManager().findFragmentByTag(TAG_ADVERTISEMENT) == null) {
adf.show(getChildFragmentManager(), TAG_ADVERTISEMENT);
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_favorites, container, false);
View view = inflater.inflate(R.layout.fragment_favorites, container, false);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_unit, menu);
inflater.inflate(R.menu.menu_refresh, menu);
// remove this item, since it would not have an effect here
MenuItem item = menu.findItem(R.id.action_unit_system);
if (item != null) item.setVisible(false);
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
FavoritesViewModel model = new ViewModelProvider(getActivity()).get(FavoritesViewModel.class);
model.refresh();
return true;
} else if (item.getItemId() == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
}
return false;
}
}, getViewLifecycleOwner());
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = view.findViewById(R.id.recycler);
TabletUtil.setGridLayout(recyclerView, 300);
TabletUtil.setGridLayout(recyclerView, 350);
SwipeRefreshLayout swipeRefreshLayout = view.findViewById(R.id.swipe_refresh);
FavoritesViewModel model = new ViewModelProvider(getActivity()).get(FavoritesViewModel.class);
model.getRefreshing().observe(getViewLifecycleOwner(), (refreshing) -> {
@@ -140,29 +171,6 @@ public class FavoritesFragment extends Fragment {
});
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_unit, menu);
inflater.inflate(R.menu.menu_refresh, menu);
// remove this item, since it would not have an effect here
MenuItem item = menu.findItem(R.id.action_unit_system);
if (item != null) item.setVisible(false);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
FavoritesViewModel model = new ViewModelProvider(getActivity()).get(FavoritesViewModel.class);
model.refresh();
return true;
} else if (item.getItemId() == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
}
return false;
}
/**
* The view holder for favorites.
*
@@ -4,9 +4,8 @@ import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.renderscript.ScriptGroup;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -27,9 +26,9 @@ import com.mowesta.android.app.model.AbstractNetworkViewModel;
import com.mowesta.android.app.model.ColorViewModel;
import com.mowesta.android.app.model.ForecastWidgetViewModel;
import com.mowesta.android.app.task.DatabaseTask;
import com.mowesta.android.app.widget.AbstractWidgetProvider;
import com.mowesta.android.app.widget.ForecastWidgetProvider;
import com.mowesta.android.app.widget.WidgetReceiver;
import com.mowesta.android.app.widget.WidgetService;
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
import com.mowesta.android.feign.model.City;
/**
@@ -39,6 +38,11 @@ import com.mowesta.android.feign.model.City;
*/
public class ForecastWidgetFragment extends AbstractNetworkFragment {
/**
* The log tag.
*/
private static final String TAG = "ForecastWidgetFragment";
/**
* The bundle extra to store the widget id.
*/
@@ -108,7 +112,14 @@ public class ForecastWidgetFragment extends AbstractNetworkFragment {
model.getCities(),
model.getSelection()));
model.getFinished().observe(getViewLifecycleOwner(), (c) -> {
if (c != null) finish(c, model.getCelsius().getValue(), model.getColor().getValue());
Activity activity = getActivity();
if (c != null) {
try {
finish(activity, c, model.getCelsius().getValue(), model.getColor().getValue());
} catch (Exception e) {
Log.e(TAG, "Failed to finish.", e);
}
}
});
model.getDialog().observe(getViewLifecycleOwner(), (d) -> {
if (d) {
@@ -128,36 +139,41 @@ public class ForecastWidgetFragment extends AbstractNetworkFragment {
* @param color The color.
* @param celsius A flag to indicate whether the widget uses celsius or fahrenheit.
*/
public void finish(City city, boolean celsius, int color) {
Activity activity = getActivity();
public void finish(Activity activity, City city, boolean celsius, int color) {
Context app = activity.getApplicationContext();
DatabaseTask<WidgetDatabase, Integer, Widget> task = new DatabaseTask<>((input, database)-> {
long now = System.currentTimeMillis();
Widget w = new Widget();
w.setReference(input);
w.setType(Widget.TYPE_FORECAST);
w.setCelsius(celsius);
w.setDataId(city.getId());
w.setData(city);
w.setDataTime(now);
w.setColor(color);
database.getAccessor().add(w);
return w;
long now = System.currentTimeMillis();
Widget w = new Widget();
w.setReference(input);
w.setType(Widget.TYPE_FORECAST);
w.setCelsius(celsius);
w.setDataId(city.getId());
w.setData(city);
w.setDataTime(now);
w.setColor(color);
database.runInTransaction(() -> {
Log.d(TAG, "Added widget of type " + Widget.TYPE_FORECAST + " with id " + input + ".");
database.getAccessor().delete(Widget.TYPE_FORECAST, input);
database.getAccessor().add(w);
});
return w;
}, (input, result) -> {
ForecastWidgetProvider provider = new ForecastWidgetProvider();
provider.triggerUpdate(app, input, true);
if (!activity.isDestroyed()) {
activity.finish();
try {
if (!activity.isDestroyed()) {
ForecastWidgetProvider provider = new ForecastWidgetProvider();
provider.loadWidget(app, input);
provider.triggerUpdate(app, input, true);
PeriodicWidgetWorker.scheduleUpdates(app);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, input);
activity.setResult(Activity.RESULT_OK, resultValue);
activity.finish();
}
} catch (Throwable e) {
Log.e(TAG, "Failed to update widget.", e);
}
});
WidgetReceiver.scheduleUpdates(app);
int id = getWidgetId();
task.execute(id, ((IApp)activity.getApplicationContext()).getWidgetRepository().getDatabase());
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id);
activity.setResult(Activity.RESULT_OK, resultValue);
task.execute(getWidgetId(), ((IApp)activity.getApplicationContext()).getWidgetRepository().getDatabase());
}
}
@@ -51,16 +51,16 @@ public class LoginFragment extends Fragment {
NavOptions.Builder b = new NavOptions.Builder().setPopUpTo(R.id.destination_favorites, false);
Navigation.findNavController(binding.getRoot()).navigate(R.id.destination_devices, null, b.build());
break;
case COLLECTION:
case DRAWER:
try {
Navigation.findNavController(binding.getRoot()).navigate(R.id.action_login_collection);
Navigation.findNavController(binding.getRoot()).navigate(R.id.action_login_drawer);
} catch (IllegalArgumentException e) {
// this is most likely bug in the navigation library, since it cannot find the
// node in the xml file which is technically impossible (probably a race during loading)
NavOptions.Builder builder = new NavOptions.Builder().setPopUpTo(R.id.destination_login, true);
builder.setEnterAnim(R.anim.slide_in_right);
builder.setExitAnim(R.anim.slide_out_left);
Navigation.findNavController(binding.getRoot()).navigate(R.id.destination_collection, null, builder.build());
Navigation.findNavController(binding.getRoot()).navigate(R.id.action_login_drawer, null, builder.build());
}
break;
@@ -1,9 +1,7 @@
package com.mowesta.android.app.fragment;
import android.app.Activity;
import android.app.Application;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
@@ -17,13 +15,11 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavDeepLinkBuilder;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.mowesta.android.app.IApp;
import com.mowesta.android.app.MowestaActivity;
import com.mowesta.android.app.MowestaSettings;
import com.mowesta.android.app.R;
import com.mowesta.android.app.adapter.DeviceEntryPagedListAdapter;
import com.mowesta.android.app.database.Widget;
@@ -34,7 +30,7 @@ import com.mowesta.android.app.model.ColorViewModel;
import com.mowesta.android.app.model.MeasureWidgetViewModel;
import com.mowesta.android.app.task.DatabaseTask;
import com.mowesta.android.app.widget.MeasureWidgetProvider;
import com.mowesta.android.app.widget.WidgetReceiver;
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
import com.mowesta.android.feign.model.Device;
import java.util.ArrayList;
@@ -47,6 +43,11 @@ import java.util.List;
*/
public class MeasureWidgetFragment extends AbstractNetworkFragment {
/**
* The log tag.
*/
private static final String TAG = "MeasureWidgetFragment";
/**
* The bundle extra to store the widget id.
*/
@@ -139,7 +140,14 @@ public class MeasureWidgetFragment extends AbstractNetworkFragment {
recyclerView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(() -> model.reload());
model.getFinished().observe(getViewLifecycleOwner(), (c) -> {
if (c != null) finish(c, model.getCelsius().getValue(), model.getSi().getValue(), model.getColor().getValue());
Activity activity = getActivity();
if (c != null) {
try {
finish(activity, c, model.getCelsius().getValue(), model.getSi().getValue(), model.getColor().getValue());
} catch (Exception e) {
Log.e(TAG, "Failed to finish.", e);
}
}
});
model.getLogin().observe(getViewLifecycleOwner(), (v) -> {
if (v) {
@@ -195,13 +203,13 @@ public class MeasureWidgetFragment extends AbstractNetworkFragment {
/**
* Finishes the the configuration and stores the widget configuration in the database.
*
* @param activity The activity.
* @param device The device.
* @param celsius A flag to indicate whether the widget uses celsius or fahrenheit.
* @param color The widget color.
* @param si A flag to indicate which measurement unit system.
*/
public void finish(Device device, boolean celsius, boolean si, int color) {
Activity activity = getActivity();
public void finish(Activity activity, Device device, boolean celsius, boolean si, int color) {
Context app = activity.getApplicationContext();
DatabaseTask<WidgetDatabase, Integer, Widget> task = new DatabaseTask<>((input, database)-> {
long now = System.currentTimeMillis();
@@ -214,21 +222,25 @@ public class MeasureWidgetFragment extends AbstractNetworkFragment {
w.setDataId(device.getId());
w.setData(device);
w.setDataTime(now);
database.getAccessor().add(w);
database.runInTransaction(() -> {
database.getAccessor().delete(Widget.TYPE_MEASURE, input);
database.getAccessor().add(w);
Log.d(TAG, "Added widget of type " + Widget.TYPE_MEASURE + " with id " + input + ".");
});
return w;
}, (input, result) -> {
MeasureWidgetProvider provider = new MeasureWidgetProvider();
provider.triggerUpdate(app, input, true);
if (!activity.isDestroyed()) {
MeasureWidgetProvider provider = new MeasureWidgetProvider();
provider.loadWidget(app, input);
provider.triggerUpdate(app, input, true);
PeriodicWidgetWorker.scheduleUpdates(app);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, input);
activity.setResult(Activity.RESULT_OK, resultValue);
activity.finish();
}
});
WidgetReceiver.scheduleUpdates(app);
int id = getWidgetId();
task.execute(id, ((IApp)activity.getApplicationContext()).getWidgetRepository().getDatabase());
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id);
activity.setResult(Activity.RESULT_OK, resultValue);
task.execute(getWidgetId(), ((IApp)activity.getApplicationContext()).getWidgetRepository().getDatabase());
}
@@ -8,14 +8,9 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.mowesta.android.app.BuildConfig;
import com.mowesta.android.app.IApp;
import com.mowesta.android.app.MowestaApp;
import com.mowesta.android.app.MowestaService;
import com.mowesta.android.app.MowestaSettings;
import com.mowesta.android.app.R;
import com.mowesta.android.app.database.FavoriteDatabase;
import com.mowesta.android.app.repository.DeviceRepository;
import com.mowesta.android.app.task.DatabaseTask;
import com.mowesta.android.sdk.SdkRepository;
import com.mowesta.android.sdk.task.ClearTask;
import android.annotation.TargetApi;
import android.app.Activity;
@@ -24,8 +19,6 @@ import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
@@ -159,7 +152,6 @@ public class SettingsFragment extends PreferenceFragmentCompat {
bindReset();
bindTerms();
bindLicenses();
bindSdkSettings();
return v;
}
@@ -200,8 +192,6 @@ public class SettingsFragment extends PreferenceFragmentCompat {
*/
private void updateBuild() {
try {
ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(getActivity().getPackageName(), 0);
PackageInfo pi = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
String summary = getResources().getString(R.string.setting_about_build_summary);
summary = summary.replace("$version$", BuildConfig.VERSION_NAME);
summary = summary.replace("$code$", "" + BuildConfig.VERSION_CODE);
@@ -240,7 +230,6 @@ public class SettingsFragment extends PreferenceFragmentCompat {
// there are no notification settings on older devices
getPreferenceScreen().removePreference(category);
} else {
setClickListener(KEY_NOTIFICATION_APP, createNotificationSettingsListener(getActivity().getPackageName(), getString(R.string.mowesta_sdk_notification_channel_id)));
setClickListener(KEY_NOTIFICATION_OS, createNotificationSettingsListener("android", "FOREGROUND_SERVICE"));
}
}
@@ -354,20 +343,6 @@ public class SettingsFragment extends PreferenceFragmentCompat {
});
}
/**
* Binds the sdk settings.
*/
private void bindSdkSettings() {
setClickListener(KEY_DEVELOPMENT_CLEAR_CACHE, new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
new ClearTask(SdkRepository.getInstance(getActivity().getApplication()), false, () -> {
Toast.makeText(preference.getContext(), R.string.setting_development_clear_message, Toast.LENGTH_SHORT).show();
}).execute();
return false;
}
});
}
/**
* Enables the developmentGroup mode.
@@ -438,26 +413,13 @@ public class SettingsFragment extends PreferenceFragmentCompat {
// stop the service and its background processing
Log.d(TAG, "Resetting the device.");
Activity activity = getActivity();
MowestaService.stopService(activity);
// reset the settings
MowestaApp app = (MowestaApp)activity.getApplication();
SdkRepository sdk = SdkRepository.getInstance(app);
MowestaSettings settings = app.getSettings();
settings.setPrivacyMeasure(false);
settings.setCollectionShown(false);
app.getUserRepository().clearCredentials();
app.getDeviceRepository().clearDevice();
new ClearTask(sdk, true, ()-> {
new DatabaseTask<FavoriteDatabase, Void, Void>
((input, database)-> {
Log.d(TAG, "Clearing database.");
database.getAccessor().clearAll();
return null;
},(input, result)-> {
Log.d(TAG, "Finishing the activity.");
activity.finish();
}).execute(null, app.getFavoriteRepository().getDatabase());
}).execute();
}
});
b.setNegativeButton(R.string.button_no, new DialogInterface.OnClickListener() {
@@ -17,6 +17,7 @@ import android.view.animation.OvershootInterpolator;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
@@ -66,7 +67,7 @@ public class SetupFragment extends Fragment {
SetupViewModel.GpsStatus status = model.registerGpsReceiver();
switch (status) {
case PROHIBITED:
((MowestaActivity)getActivity()).requestPermissions(PermissionUtil.getForegroundPermissions(getActivity()));
ActivityCompat.requestPermissions(getActivity(), PermissionUtil.getForegroundPermissions(getActivity()), MowestaActivity.CODE_REQUEST_FOREGROUND_PERMISSIONS);
break;
case DISABLED:
Snackbar.make(container, R.string.setup_error_gps_disabled, Snackbar.LENGTH_LONG).setAction(R.string.button_configure, (v) -> {
@@ -45,8 +45,6 @@ public class SplashFragment extends Fragment {
Navigation.findNavController(getView()).navigate(R.id.action_splash_terms);
} else if (shouldShowLogin()) {
Navigation.findNavController(getView()).navigate(R.id.action_splash_login);
} else if (shouldShowCollection()) {
Navigation.findNavController(getView()).navigate(R.id.action_splash_collection);
} else {
Navigation.findNavController(getView()).navigate(R.id.action_splash_drawer);
}
@@ -84,7 +84,7 @@ public class StateFragment extends AbstractPlaceFragment {
binding.setModel(model);
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
AppBarConfiguration.Builder builder = new AppBarConfiguration.Builder();
builder.setFallbackOnNavigateUpListener(() -> { getActivity().onBackPressed(); return true; });
builder.setFallbackOnNavigateUpListener(() -> { getActivity().getOnBackPressedDispatcher().onBackPressed(); return true; });
NavigationUI.setupWithNavController(layout, toolbar, controller, builder.build());
return root;
}
@@ -82,7 +82,7 @@ public class StationFragment extends AbstractDiagramFragment {
binding.setModel(model);
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
AppBarConfiguration.Builder builder = new AppBarConfiguration.Builder();
builder.setFallbackOnNavigateUpListener(() -> { getActivity().onBackPressed(); return true; });
builder.setFallbackOnNavigateUpListener(() -> { getActivity().getOnBackPressedDispatcher().onBackPressed(); return true; });
NavigationUI.setupWithNavController(layout, toolbar, controller, builder.build());
return root;
}
@@ -1,5 +1,6 @@
package com.mowesta.android.app.fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
@@ -23,14 +24,33 @@ import com.mowesta.android.app.databinding.FragmentStationsBinding;
import com.mowesta.android.app.databinding.ViewStationEntryBinding;
import com.mowesta.android.app.model.AbstractNetworkViewModel;
import com.mowesta.android.app.model.StationsViewModel;
import com.mowesta.android.app.util.TabletUtil;
import com.mowesta.android.feign.model.WeatherStation;
import org.jetbrains.annotations.NotNull;
/**
* Shows a list of the available stations.
*
* @author Marcus
*/
public class StationsFragment extends AbstractNetworkFragment {
private RecyclerView recyclerView;
private void applyGridWidth() {
if (!TabletUtil.isTablet(requireContext())) {
return;
}
int width = requireContext().getResources().getInteger(R.integer.RecyclerWidth);
TabletUtil.setGridLayout(recyclerView, width);
}
@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
applyGridWidth();
}
@Override
protected AbstractNetworkViewModel getNetworkViewModel() {
@@ -50,7 +70,9 @@ public class StationsFragment extends AbstractNetworkFragment {
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recycler = view.findViewById(R.id.recycler);
recyclerView = view.findViewById(R.id.recycler);
applyGridWidth();
StationsViewModel model = new ViewModelProvider(this).get(StationsViewModel.class);
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
StationEntryPagedListAdapter adapter = new StationEntryPagedListAdapter(getViewLifecycleOwner(), (station) -> {
@@ -65,7 +87,7 @@ public class StationsFragment extends AbstractNetworkFragment {
model.getStations().observe(getViewLifecycleOwner(), (list) -> {
adapter.submitList(list);
});
recycler.setAdapter(adapter);
recyclerView.setAdapter(adapter);
}
/**
@@ -141,7 +163,7 @@ public class StationsFragment extends AbstractNetworkFragment {
* Creates a new paged list adapter that will inform
* the listener about click events.
*
* @param owner The lifecycle owner.
* @param owner The lifecycle owner.
* @param listener The listener.
*/
public StationEntryPagedListAdapter(@NonNull LifecycleOwner owner, @NonNull StationsViewModel.OnStationSelectedListener listener) {
@@ -150,7 +150,7 @@ public class TermsFragment extends Fragment {
*
* @author Marcus
*/
public static class BrowserFragment extends CityFragment.ChildFragment {
public static class BrowserFragment extends Fragment {
/**
* The web view to show the contents.
@@ -19,22 +19,23 @@ import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.OptIn;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.media3.common.util.UnstableApi;
import androidx.preference.PreferenceManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.google.android.exoplayer2.util.Util;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.common.MediaItem;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.exoplayer.source.ProgressiveMediaSource;
import androidx.media3.ui.AspectRatioFrameLayout;
import androidx.media3.ui.PlayerView;
import androidx.media3.datasource.DefaultHttpDataSource;
import androidx.media3.datasource.cache.CacheDataSource;
import androidx.media3.common.util.Util;
import com.mowesta.android.app.IApp;
import com.mowesta.android.app.MowestaSettings;
import com.mowesta.android.app.R;
@@ -232,6 +233,7 @@ public class VideoFragment extends AbstractNetworkFragment {
}
@Override
@OptIn(markerClass = UnstableApi.class)
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
model = new ViewModelProvider(this).get(ExoPlayerViewModel.class);
@@ -272,7 +274,7 @@ public class VideoFragment extends AbstractNetworkFragment {
timeUtils = new TimeUtils(System.currentTimeMillis(), timezone);
formatter = new DateFormatter(getContext());
if (model.exoPlayer == null) {
model.exoPlayer = new SimpleExoPlayer.Builder(getContext()).build();
model.exoPlayer = new ExoPlayer.Builder(getContext()).build();
model.scaler.setContent(video.getWidth(), video.getHeight());
IApp app = (IApp)getActivity().getApplication();
DefaultHttpDataSource.Factory hf = new DefaultHttpDataSource.Factory();
@@ -347,6 +349,7 @@ public class VideoFragment extends AbstractNetworkFragment {
* @param width The width.
* @param height The height.
*/
@OptIn(markerClass = UnstableApi.class)
private void updateVideo(int width, int height) {
model.scaler.setScreen(width, height);
double scale = model.scaler.getScale();
@@ -0,0 +1,68 @@
package com.mowesta.android.app.model;
import android.app.Application;
import androidx.annotation.OptIn;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.common.MediaItem;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.exoplayer.source.ProgressiveMediaSource;
import androidx.media3.datasource.AssetDataSource;
import androidx.media3.datasource.DataSource;
public class AdvertiseViewModel extends AndroidViewModel {
private ExoPlayer exoPlayer;
private MutableLiveData<Boolean> close = new MutableLiveData<>(Boolean.FALSE);
private MutableLiveData<Boolean> open = new MutableLiveData<>(Boolean.FALSE);
@OptIn(markerClass = UnstableApi.class)
public AdvertiseViewModel(Application app) {
super(app);
ExoPlayer.Builder builder = new ExoPlayer.Builder(app);
exoPlayer = builder.build();
DataSource.Factory df = new DataSource.Factory() {
@Override
public DataSource createDataSource() {
return new AssetDataSource(app);
}
};
MediaSource videoSource = new ProgressiveMediaSource.Factory(df)
.createMediaSource(MediaItem.fromUri("android_assets:///dasfest.mp4"));
exoPlayer.setRepeatMode(ExoPlayer.REPEAT_MODE_ALL);
exoPlayer.setMediaSource(videoSource);
exoPlayer.prepare();
exoPlayer.setPlayWhenReady(true);
}
public MutableLiveData<Boolean> getClose() {
return close;
}
public MutableLiveData<Boolean> getOpen() {
return open;
}
public void close() {
close.setValue(Boolean.TRUE);
}
public void open() {
open.setValue(Boolean.TRUE);
}
public ExoPlayer getExoPlayer() {
return exoPlayer;
}
@Override
protected void onCleared() {
exoPlayer.stop();
}
}
@@ -196,7 +196,7 @@ public class DeviceViewModel extends AbstractNetworkViewModel {
@Override
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<DiagramEntry<Measurement>> callback) {
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(id, 0l, now, params.requestedStartPosition, params.requestedLoadSize ); },
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(id, 0L, now, params.requestedStartPosition, params.requestedLoadSize ); },
(id, page) -> { completeRequest(requestCode, () -> callback.onResult(toEntries(page.getElements()), params.requestedStartPosition, page.getTotal())); },
(id, status) -> { finishRequest(requestCode, true); });
if (isCurrentRequest(requestCode)) {
@@ -211,7 +211,7 @@ public class DeviceViewModel extends AbstractNetworkViewModel {
@Override
public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<DiagramEntry<Measurement>> callback) {
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(id, 0l, now, params.startPosition, params.loadSize ); },
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(id, 0L, now, params.startPosition, params.loadSize ); },
(id, page) -> { completeRequest(requestCode, () -> callback.onResult(toEntries(page.getElements()))); },
(id, status) -> { finishRequest(requestCode, true); });
if (id != null && credentials != null && isCurrentRequest(requestCode)) {
@@ -35,7 +35,7 @@ public class LoginViewModel extends AndroidViewModel {
/**
* Constants to model different destinations to go to.
*/
public enum Destination { DEVICES, COLLECTION};
public enum Destination { DEVICES, DRAWER};
/**
@@ -123,7 +123,7 @@ public class LoginViewModel extends AndroidViewModel {
getUserRepository().setCredentials(input);
syncFavorites();
}
destination.setValue(Destination.COLLECTION);
destination.setValue(Destination.DRAWER);
}, (input, status) -> {
checking.setValue(false);
if (status == 403) {
@@ -355,16 +355,22 @@ public class SetupViewModel extends AndroidViewModel {
private Double parseValue(String value) {
if (value == null) return null;
value = value.trim();
LocaleListCompat c = ConfigurationCompat.getLocales(getApplication().getResources().getConfiguration());
for (int i = 0; i < c.size(); i++) {
Locale l = c.get(i);
NumberFormat f = NumberFormat.getNumberInstance(l);
try {
return ((Number)f.parseObject(value.trim())).doubleValue();
return ((Number)f.parseObject(value)).doubleValue();
} catch (ParseException e) {
Log.d(TAG, "Failed to parse double from: " + value);
}
}
try {
return Double.parseDouble(value.replace(',', '.'));
} catch (NumberFormatException e) {
Log.d(TAG, "Failed to parse double, giving up: " + value);
}
return null;
}
@@ -201,7 +201,7 @@ public class StationViewModel extends AbstractNetworkViewModel {
@Override
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<DiagramEntry<WeatherReport>> callback) {
ApiTask<Long, WeatherReportPage> task = new ApiTask<>((id, client) -> { return client.getStationReports(id, 0l, now, params.requestedStartPosition, params.requestedLoadSize ); },
ApiTask<Long, WeatherReportPage> task = new ApiTask<>((id, client) -> { return client.getStationReports(id, 0L, now, params.requestedStartPosition, params.requestedLoadSize ); },
(id, page) -> { completeRequest(requestCode, () -> callback.onResult(toEntries(page.getElements()), params.requestedStartPosition, page.getTotal())); },
(id, status) -> { finishRequest(requestCode, true); });
if (id != null && isCurrentRequest(requestCode)) {
@@ -150,7 +150,7 @@ public class StationsViewModel extends AbstractNetworkViewModel {
@Override
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<WeatherStation> callback) {
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(term,0, params.requestedLoadSize ); },
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(term, 0, params.requestedLoadSize); },
(v, page) -> { completeRequest(requestCode, () -> callback.onResult(page.getElements(), 0, page.getTotal())); },
(v, status) -> { finishRequest(requestCode, true); });
if (isCurrentRequest(requestCode)) {
@@ -117,7 +117,7 @@ public class ClientFactory {
String p = credentials.getPassword();
String user = l == null ? "" : l;
String pass = p == null ? "" : p;
return "Basic " + new String(Base64.encode((user + ":" + pass).getBytes(ISO_8859_1), 0), ASCII);
return "Basic " + new String(Base64.encode((user + ":" + pass).getBytes(ISO_8859_1), Base64.NO_WRAP), ASCII);
}
/**
@@ -196,7 +196,7 @@ public class DeviceRepository extends Repository {
d.setId(handle.getId());
d.setDevice(handle.getDevice());
d.setCreationTime(handle.getCreationTime());
d.setDeleted(handle.isDeleted());
d.setDeleted(handle.getDeleted());
d.setManufacturer(handle.getManufacturer());
d.setModificationTime(handle.getModificationTime());
d.setModel(handle.getModel());
@@ -8,7 +8,7 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.security.crypto.EncryptedFile;
import androidx.security.crypto.MasterKey;
import androidx.security.crypto.MasterKeys;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -281,9 +281,8 @@ public class FileStoreObserver<T> implements Observer<T> {
* be setup.
*/
@NonNull EncryptedFile getEncryptedFile() throws IOException, GeneralSecurityException {
MasterKey.Builder b = new MasterKey.Builder(context);
b.setKeyScheme(MasterKey.KeyScheme.AES256_GCM);
return new EncryptedFile.Builder(context, getFile(), b.build(),
String keySpec = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
return new EncryptedFile.Builder(getFile(), context, keySpec,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB).build();
}
@@ -0,0 +1,158 @@
package com.mowesta.android.app.task;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
/**
* The base class for tasks. This is a drop in replacement for Android's async task,
* which is now deprecated.
*
* @param <Result>
*/
public abstract class AbstractTask<Result> {
/**
* The log tag of the task.
*/
private static final String TAG = "Task";
/**
* The executor to execute a couple of tasks in parallel. We limit this to
* 4 threads to avoid excessive sever loads.
*/
public static ExecutorService POOL_EXECUTOR = Executors.newFixedThreadPool(4);
/**
* The executor used to run tasks sequentially. This is used to ensure that
* tasks requiring a specific order will respect the scheduling order.
*/
public static ExecutorService SERIAL_EXECUTOR = Executors.newSingleThreadExecutor();
private static int counter = 0;
/**
* A flag to indicate whether the execution will take place on the pooled
* or on a serial executor.
*/
private final boolean pooled;
/**
* The flag to determine whether the task is canceled.
*/
private boolean cancelled;
/**
* A flag to prevent the duplicate task execution.
*/
private boolean executed;
/**
* The handler to perform execution
*/
protected final Handler handler = new Handler(Looper.getMainLooper());
/**
* Creates a new task executed on a serial executor.
*/
public AbstractTask() {
this.pooled = false;
}
/**
* Creates a new task that is running on a serial executor (false
* or thred pool executor (true).
*
* @param pooled True to run the task on a thread pool, false to
* run it on a serial executor.
*/
public AbstractTask(boolean pooled) {
this.pooled = pooled;
}
/**
* Determines whether the execution will take place on a pool (true)
* or on a serial executor (false).
*
* @return True for pooled execution, false for serial execution.
*/
public boolean isPooled() {
return pooled;
}
/**
* Executes the task on the executor.
*/
public void execute() {
int c;
synchronized (this) {
counter += 1;
c = counter;
if (executed) throw new RuntimeException("Cannot execute task twice.");
executed = true;
}
ExecutorService target = pooled?POOL_EXECUTOR:SERIAL_EXECUTOR;
try {
Log.v(TAG, "Schedule " + c + " (" + pooled + ")");
target.execute(() -> {
try {
Log.v(TAG, "Running " + c);
Result r = doInBackground();
handler.post(() -> {
try {
onPostExecute(r);
} catch (Exception e) {
Log.d(TAG, "Unexpected exception while executing post execute.", e);
}
});
Log.v(TAG, "Completed " + c);
} catch (Exception e) {
Log.d(TAG, "Unexpected exception while executing in background.", e);
}
});
} catch (RejectedExecutionException e) {
Log.d(TAG, "Scheduling of task failed.", e);
}
}
/**
* Sets the canceled flag on the task, if not set already and
* notifies the monitor associated with this object.
*/
public void cancel() {
synchronized (this) {
cancelled = true;
this.notifyAll();
}
}
/**
* Determines whether the task is canceled.
*
* @return True to cancel.
*/
public boolean isCancelled() {
synchronized (this) {
return cancelled;
}
}
/**
* The method that will be called on a background thread.
*
* @return The result value.
*/
protected abstract Result doInBackground();
/**
* The method that wil be called.
*
* @param result The result.
*/
protected void onPostExecute(Result result) { }
}
@@ -4,7 +4,6 @@ import android.annotation.SuppressLint;
import android.util.Log;
import com.mowesta.android.feign.api.DefaultApi;
import com.mowesta.android.sdk.task.AbstractTask;
import feign.FeignException;
@@ -4,8 +4,6 @@ import android.annotation.SuppressLint;
import androidx.room.RoomDatabase;
import com.mowesta.android.sdk.task.AbstractTask;
/**
* A task that interacts with a room database. Note that this
* task is executed on the serial executor to ensure that it
@@ -8,8 +8,6 @@ import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.mowesta.android.sdk.task.AbstractTask;
import java.io.InputStream;
import java.net.URL;
@@ -7,7 +7,6 @@ import com.mowesta.android.app.database.FavoriteDatabase;
import com.mowesta.android.feign.api.DefaultApi;
import com.mowesta.android.feign.model.City;
import com.mowesta.android.feign.model.CityPage;
import com.mowesta.android.sdk.task.AbstractTask;
import java.util.ArrayList;
import java.util.List;
@@ -7,7 +7,6 @@ import com.mowesta.android.app.database.FavoriteDatabase;
import com.mowesta.android.feign.api.DefaultApi;
import com.mowesta.android.feign.model.LocationReference;
import com.mowesta.android.feign.model.Settings;
import com.mowesta.android.sdk.task.AbstractTask;
import java.util.ArrayList;
import java.util.HashMap;
@@ -30,7 +30,7 @@ public class ColoredSnackbar {
*/
public static Snackbar make(View view, CharSequence text, int duration) {
Snackbar snackbar = Snackbar.make(view, text, duration);
snackbar.getView().setBackgroundColor(getAttribute(view.getContext(), R.attr.colorAccent));
snackbar.getView().setBackgroundColor(getAttribute(view.getContext(), androidx.appcompat.R.attr.colorAccent));
List<View> views = new ArrayList<>();
views.add(snackbar.getView());
while (! views.isEmpty()) {
@@ -96,4 +96,18 @@ public class PermissionUtil {
return new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION };
}
/**
* Determines whether the app has the post notification permission.
*
* @param context The context.
* @return True if the app may post notifications.
*/
public static boolean hasNotificationPermission(@NonNull Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
return hasPermissions(context, new String[] { Manifest.permission.POST_NOTIFICATIONS });
} else {
return true;
}
}
}
@@ -1,10 +1,6 @@
package com.mowesta.android.app.util;
import android.content.Context;
import android.content.res.Resources;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.os.ConfigurationCompat;
import com.mowesta.android.app.R;
@@ -17,7 +13,7 @@ import java.util.List;
import java.util.TimeZone;
/**
* A utiltiy class to comptue times when aggregating weather
* A utility class to computes times when aggregating weather
* conditions into weather summaries.
*
* @author Marcus
@@ -44,15 +40,15 @@ public class TimeUtils {
* @param tz The time zone.
*/
public TimeUtils(long now, String tz) {
if (tz != null) {
c.setTimeZone(TimeZone.getTimeZone(tz));
}
c.setTimeInMillis(now);
update(today);
c.add(Calendar.DAY_OF_MONTH, -1);
update(yesterday);
c.add(Calendar.DAY_OF_MONTH, 2);
update(tomorrow);
if (tz != null) {
c.setTimeZone(TimeZone.getTimeZone(tz));
}
}
/**
@@ -7,8 +7,10 @@ import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import com.mowesta.android.app.IApp;
import com.mowesta.android.app.R;
import com.mowesta.android.app.database.Widget;
import com.mowesta.android.app.database.WidgetAccessor;
import com.mowesta.android.app.database.WidgetDatabase;
@@ -133,7 +135,7 @@ public abstract class AbstractWidgetProvider extends AppWidgetProvider {
* @param id The id.
*/
public void triggerUpdate(Context context, int id, boolean schedule) {
if (schedule) WidgetService.scheduleUpdate(context, type, id);
if (schedule) OnetimeWidgetWorker.updateWidget(context, type, id);
Log.d(TAG, "Start database query for widget " + id + ".");
DatabaseTask<WidgetDatabase, Integer, Widget> task = new DatabaseTask<WidgetDatabase, Integer, Widget>((input, database)-> {
List<Widget> widgets = database.getAccessor().get(type, input);
@@ -143,11 +145,26 @@ public abstract class AbstractWidgetProvider extends AppWidgetProvider {
if (widget != null) {
Log.d(TAG, "Finish database query for widget " + input + ".");
updateWidget(context, widget);
} else {
loadWidget(context, id);
}
});
task.execute(id, getWidgetDatabase(context));
}
/**
* Displays a remote view that shows that the widget is loading.
*
* @param context The context.
* @param id The id.
*/
public void loadWidget(Context context, int id) {
Log.d(TAG, "Building loading view for widget " + id + ".");
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_loading);
appWidgetManager.updateAppWidget(id, views);
}
/**
* Returns the widget dimensions for the app widget. If the options
* cannot be retrieved, the width and height will be 0.
@@ -157,6 +174,7 @@ public abstract class AbstractWidgetProvider extends AppWidgetProvider {
* @return An int array containing the width and height.
*/
protected int[] getWidgetDimensions(Context context, int id) {
Log.d(TAG, "Requesting app widget manager options.");
AppWidgetManager manager = AppWidgetManager.getInstance(context);
Bundle options = manager.getAppWidgetOptions(id);
if (options == null) return new int[] { 0, 0 };
@@ -165,6 +183,9 @@ public abstract class AbstractWidgetProvider extends AppWidgetProvider {
int minHeight = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, 0);
int maxHeight = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, 0);
Log.d(TAG, String.format("Widget %d: Width(%d-%d) Height(%d-%d)", id, minWidth, maxWidth, minHeight, maxHeight));
if (maxWidth == 0 && maxHeight == 0) {
return new int[] { 100, 100 };
}
if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
return new int[] { minWidth, maxHeight };
} else {
@@ -3,6 +3,7 @@ package com.mowesta.android.app.widget;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
@@ -41,4 +42,9 @@ public class ForecastWidgetActivity extends AppCompatActivity {
setResult(RESULT_CANCELED, resultValue);
}
@Override
protected void onStop() {
super.onStop();
Log.d("ForecastWidgetActivity", "onStop");
}
}
@@ -6,7 +6,9 @@ import android.content.ComponentName;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.RemoteViews;
@@ -74,6 +76,7 @@ public class ForecastWidgetProvider extends AbstractWidgetProvider {
@Override
public void updateWidget(Context context, Widget widget) {
Log.d(TAG, "Performing forecast widget update "+ widget.getReference() + ".");
City city = widget.getData(City.class);
if (city == null) {
Log.d(TAG, "Ignoring update without for widget " + widget.getReference() + " without city.");
@@ -92,6 +95,7 @@ public class ForecastWidgetProvider extends AbstractWidgetProvider {
}
days = a.getDays();
}
Log.d(TAG, "Building remote views.");
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_forecast);
// set color
@@ -117,7 +121,10 @@ public class ForecastWidgetProvider extends AbstractWidgetProvider {
views.setTextViewText(R.id.widget_condition_temperature, UnitUtils.toSpanned(UnitUtils.getTemperature(context, condition.getTemperature(), unit)));
}
}
float scale = context.getResources().getDisplayMetrics().scaledDensity / context.getResources().getDisplayMetrics().density;
DisplayMetrics dm = context.getResources().getDisplayMetrics();
float scaledDensity = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, dm);
float scale = scaledDensity / dm.density;
Log.d(TAG, "Building remote views done.");
int[] widgetDimension = getWidgetDimensions(context, widget.getReference());
int width = widgetDimension[0];
int height = widgetDimension[1];
@@ -5,9 +5,12 @@ import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.widget.RemoteViews;
import androidx.navigation.NavDeepLinkBuilder;
@@ -59,6 +62,7 @@ public class MeasureWidgetProvider extends AbstractWidgetProvider {
@Override
public void updateWidget(Context context, Widget widget) {
Log.d(TAG, "Performing measure widget update "+ widget.getReference() + ".");
Device device = widget.getData(Device.class);
if (device == null) {
Log.d(TAG, "Ignoring update without for widget " + widget.getReference() + " without device.");
@@ -67,7 +71,11 @@ public class MeasureWidgetProvider extends AbstractWidgetProvider {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
MowestaSettings.TemperatureUnit unit = widget.isCelsius()?MowestaSettings.TemperatureUnit.CELSIUS:MowestaSettings.TemperatureUnit.FAHRENHEIT;
MowestaSettings.UnitSystem system = widget.isSi()?MowestaSettings.UnitSystem.STANDARD:MowestaSettings.UnitSystem.IMPERIAL;
float scale = context.getResources().getDisplayMetrics().scaledDensity / context.getResources().getDisplayMetrics().density;
DisplayMetrics dm = context.getResources().getDisplayMetrics();
float scaledDensity = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, dm);
float scale = scaledDensity / dm.density;
int[] widgetDimension = getWidgetDimensions(context, widget.getReference());
int width = widgetDimension[0];
int height = widgetDimension[1];
@@ -92,11 +100,6 @@ public class MeasureWidgetProvider extends AbstractWidgetProvider {
Measurement measurement = widget.getContent(Measurement.class);
if (measurement != null) {
List<RemoteViews> items = new ArrayList<>();
Date dateTime = new Date(measurement.getTime());
String date = android.text.format.DateFormat.getDateFormat(context).format(dateTime);
createItemView(items, context, R.drawable.ic_calendar_today_normal_24, R.string.widget_measure_date, UnitUtils.toSpanned(date), widget.getColor());
String time = android.text.format.DateFormat.getTimeFormat(context).format(dateTime);
createItemView(items, context, R.drawable.ic_alarm_normal_24, R.string.widget_measure_time , UnitUtils.toSpanned(time), widget.getColor());
if (measurement.getTemperature() != null) {
createItemView(items, context, R.drawable.ic_thermometer_normal_24, R.string.label_temperature, UnitUtils.toSpanned(UnitUtils.getTemperature(context, measurement.getTemperature(), unit)), widget.getColor());
}
@@ -114,6 +117,11 @@ public class MeasureWidgetProvider extends AbstractWidgetProvider {
}
}
}
Date dateTime = new Date(measurement.getTime());
String date = android.text.format.DateFormat.getDateFormat(context).format(dateTime);
createItemView(items, context, R.drawable.ic_calendar_today_normal_24, R.string.widget_measure_date, UnitUtils.toSpanned(date), widget.getColor());
String time = android.text.format.DateFormat.getTimeFormat(context).format(dateTime);
createItemView(items, context, R.drawable.ic_alarm_normal_24, R.string.widget_measure_time , UnitUtils.toSpanned(time), widget.getColor());
int max = Math.min(items.size(), (int)((height - (HEIGHT_DEVICE * scale)) / (HEIGHT_ITEM * scale)));
for (int i = 0; i < max; i++) {
views.addView(R.id.widget_container_item, items.get(i));
@@ -0,0 +1,206 @@
package com.mowesta.android.app.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.OutOfQuotaPolicy;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.mowesta.android.app.IApp;
import com.mowesta.android.app.database.Widget;
import com.mowesta.android.app.database.WidgetAccessor;
import com.mowesta.android.app.database.WidgetDatabase;
import com.mowesta.android.feign.api.DefaultApi;
import com.mowesta.android.feign.model.City;
import com.mowesta.android.feign.model.Device;
import com.mowesta.android.feign.model.Measurement;
import com.mowesta.android.feign.model.MeasurementPage;
import com.mowesta.android.feign.model.WeatherForecast;
import java.util.List;
/**
* A worker that updates a widget. The widget reference
* is passed as a parameter to the job.
*/
public class OnetimeWidgetWorker extends Worker {
/**
* The worker to update the widget.
*/
public static final String TAG = "OnetimeWidgetWorker";
/**
* The extra containing the reference.
*/
public static final String EXTRA_WIDGET_REFERENCE = "reference";
/**
* The extra containing the widget type.
*/
public static final String EXTRA_WIDGET_TYPE = "type";
/**
* The delay to update the data.
*/
private static final int DELAY_DATA = 24 * 60 * 60 * 1000;
/**
* The delay to update the content.
*/
private static final int DELAY_CONTENT = 30 * 60 * 1000;
/** The widget type. */
private int type;
/** The widget reference. */
private int reference;
/** The handler. */
private Handler handler;
/** The app. */
private IApp app;
public OnetimeWidgetWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
app = (IApp)context.getApplicationContext();
handler = new Handler(Looper.getMainLooper());
type = params.getInputData().getInt(EXTRA_WIDGET_TYPE, Widget.TYPE_INVALID);
reference = params.getInputData().getInt(EXTRA_WIDGET_REFERENCE, AppWidgetManager.INVALID_APPWIDGET_ID);
}
public static void updateWidget(Context context, int type, int reference) {
Log.d(TAG, "Scheduling update for widget " + type + " " + reference + ".");
try {
WorkManager workManager = WorkManager.getInstance(context);
OneTimeWorkRequest.Builder builder = new OneTimeWorkRequest.Builder(OnetimeWidgetWorker.class);
builder.setInputData(OnetimeWidgetWorker.createData(type, reference));
builder.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST);
OneTimeWorkRequest request = builder.build();
workManager.beginWith(request).enqueue();
} catch (Exception e) {
Log.e(TAG, "Failed to schedule update for widget " + type + " " + reference + ".", e);
}
}
/**
* Creates the data for scheduling the worker.
*
* @param type The type.
* @param reference The reference.
* @return The data.
*/
public static Data createData(int type, int reference) {
Data.Builder b = new Data.Builder();
b.putInt(EXTRA_WIDGET_TYPE, type);
b.putInt(EXTRA_WIDGET_REFERENCE, reference);
return b.build();
}
@Override
public Result doWork() {
try {
Log.d(TAG, "Performing update for widget " + type + " " + reference + ".");
if (type == Widget.TYPE_INVALID || reference == AppWidgetManager.INVALID_APPWIDGET_ID) {
Log.d(TAG, "Received an invalid request for type " + type + " and reference " + reference + ".");
return Result.success();
}
WidgetDatabase database = app.getWidgetRepository().getDatabase();
WidgetAccessor accessor = database.getAccessor();
List<Widget> widgets = accessor.get(type, reference);
if (widgets.isEmpty()) {
Log.d(TAG, "Received a request for removed widget with type " + type + " and reference " + reference + ".");
return Result.success();
}
Widget widget = widgets.get(0);
if (type == Widget.TYPE_FORECAST) {
try {
DefaultApi api = app.getClientFactory().createClient();
long time = System.currentTimeMillis();
City[] city = new City[] { widget.getData(City.class) };
long[] dataTime = new long[] { widget.getDataTime() };
if (city[0] == null || time - dataTime[0] > DELAY_DATA) {
city[0] = api.getCity(widget.getDataId());
dataTime[0] = time;
}
WeatherForecast[] content = new WeatherForecast[] { widget.getContent(WeatherForecast.class) };
long[] contentTime = new long[] { widget.getContentTime() };
if (content[0] == null || time - contentTime[0] > DELAY_CONTENT) {
content[0] = api.getCityForecast(widget.getDataId());
contentTime[0] = time;
}
database.runInTransaction(() -> {
Widget w = accessor.get(widget.getId());
if (w == null) return;
w.setDataTime(dataTime[0]);
w.setData(city[0]);
w.setContentTime(contentTime[0]);
w.setContent(content[0]);
accessor.update(w);
});
} catch (Exception e) {
Log.e(TAG, "Failed to update widget state with type " + type + " and reference " + reference + ".", e);
}
Widget w = accessor.get(widget.getId());
if (w != null) {
handler.post(()-> {
ForecastWidgetProvider provider = new ForecastWidgetProvider();
provider.updateWidget(app.getContext(), w);
});
}
} else if (type == Widget.TYPE_MEASURE) {
try {
DefaultApi api = app.getClientFactory().createClient(app.getUserRepository().getCredentials().getValue());
long time = System.currentTimeMillis();
Device[] device = new Device[] { widget.getData(Device.class) };
long[] dataTime = new long[] { widget.getDataTime() };
if (device[0] == null || time - dataTime[0] > DELAY_DATA) {
device[0] = api.getDevice(widget.getDataId());
dataTime[0] = time;
}
Measurement[] content = new Measurement[] { widget.getContent(Measurement.class) };
long[] contentTime = new long[] { widget.getContentTime() };
if (content[0] == null || time - contentTime[0] > DELAY_CONTENT) {
MeasurementPage page = api.getDeviceMeasurements(widget.getDataId(), 0L, time, 0, 1);
if (page.getElements().size() > 0) {
content[0] = page.getElements().get(0);
contentTime[0] = time;
}
}
database.runInTransaction(() -> {
Widget w = accessor.get(widget.getId());
if (w == null) return;
w.setDataTime(dataTime[0]);
w.setData(device[0]);
w.setContentTime(contentTime[0]);
w.setContent(content[0]);
accessor.update(w);
});
} catch (Exception e) {
Log.e(TAG, "Failed to update widget state with type " + type + " and reference " + reference + ".", e);
}
Widget w = accessor.get(widget.getId());
if (w != null) {
handler.post(()-> {
MeasureWidgetProvider provider = new MeasureWidgetProvider();
provider.updateWidget(app.getContext(), w);
});
}
}
} catch (Exception e) {
Log.d(TAG, "Failed to perform background update.", e);
}
// Indicate whether the work finished successfully with the Result
return Result.success();
}
}
@@ -0,0 +1,95 @@
package com.mowesta.android.app.widget;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.mowesta.android.app.database.Widget;
import java.util.concurrent.TimeUnit;
/**
* A widget worker that is scheduled for periodic
* execution and triggers immediate one-time updates
* for all widgets.
*
* @author Marcus
*/
public class PeriodicWidgetWorker extends Worker {
public static final String TAG = "PeriodicWidgetWorker";
private static final String WORK_TAG = "widget_refresh";
public PeriodicWidgetWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
updateWidgets(getApplicationContext());
return Result.success();
}
/**
* Schedules periodic updates to all widgets.
*
* @param context The context.
*/
public static void scheduleUpdates(Context context) {
Log.d(TAG, "Scheduling periodic widget updates.");
PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(PeriodicWidgetWorker.class, 15, TimeUnit.MINUTES);
WorkManager.getInstance(context).enqueueUniquePeriodicWork(WORK_TAG, ExistingPeriodicWorkPolicy.KEEP, builder.build());
}
/**
* Updates all widgets one time.
*
* @param context The context.
*/
public static void updateWidgets(Context context) {
Log.d(TAG, "Received widget update request.");
boolean hasWidgets = updateWidgets(context, ForecastWidgetProvider.class, Widget.TYPE_FORECAST);
hasWidgets |= updateWidgets(context, MeasureWidgetProvider.class, Widget.TYPE_MEASURE);
if (!hasWidgets) cancelUpdates(context);
}
/**
* Updates all widgets of a particular provider and returns whether anything
* has been scheduled.
*
* @param context The context.
* @param provider The widget provider class.
* @param type The widget type.
* @return True if any update has been scheduled.
*/
private static boolean updateWidgets(Context context, Class<?> provider, int type) {
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] ids = manager.getAppWidgetIds(new ComponentName(context, provider));
WorkManager workManager = WorkManager.getInstance(context);
for (int id: ids) {
OnetimeWidgetWorker.updateWidget(context, type, id);
}
return ids.length > 0;
}
/**
* Removes the scheduled periodic update.
*
* @param context The context.
*/
public static void cancelUpdates(Context context) {
WorkManager.getInstance(context).cancelUniqueWork(WORK_TAG);
}
}
@@ -1,113 +0,0 @@
package com.mowesta.android.app.widget;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;
import com.mowesta.android.app.database.Widget;
/**
* The receiver that is called periodically by the alarm
* manager to perform widget updates every x minutes.
*
* @author Marcus
*/
public class WidgetReceiver extends BroadcastReceiver {
/**
* The log tag.
*/
private static final String TAG = "WidgetReceiver";
/**
* The request code.
*/
private static final int REQuEST_CODE = 2298;
/**
* The initial scheduling delay.
*/
private static final int DELAY_START = 60000;
/**
* The periodic update rate.
*/
private static final int DELAY_PERIOD = 15 * 60000;
@Override
public void onReceive(Context context, Intent intent) {
updateWidgets(context);
}
/**
* Updates all widgets.
*
* @param context The context.
*/
public static void updateWidgets(Context context) {
Log.d(TAG, "Received widget update request.");
boolean hasWidgets = updateWidgets(context, ForecastWidgetProvider.class, Widget.TYPE_FORECAST);
hasWidgets |= updateWidgets(context, MeasureWidgetProvider.class, Widget.TYPE_MEASURE);
if (!hasWidgets) cancelUpdates(context);
}
/**
* Updates all widgets of a particular provider and returns whether anything
* has been scheduled.
*
* @param context The context.
* @param provider The widget provider class.
* @param type The widget type.
* @return True if any update has been scheduled.
*/
private static boolean updateWidgets(Context context, Class<?> provider, int type) {
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] ids = manager.getAppWidgetIds(new ComponentName(context, provider));
for (int id: ids) {
WidgetService.scheduleUpdate(context, type, id);
}
return ids.length > 0;
}
/**
* Schedules periodic widget updates.
*
* @param context The context.
*/
public static void scheduleUpdates(Context context) {
Log.d(TAG, "Scheduling periodic widget updates.");
AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + DELAY_START, DELAY_PERIOD, createIntent(context));
}
/**
* Creates a pending intent for the updates.
*
* @param context The context.
* @return The pending intent.
*/
private static PendingIntent createIntent(Context context) {
Intent intent = new Intent(context, WidgetReceiver.class);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) flags = flags | PendingIntent.FLAG_IMMUTABLE;
return PendingIntent.getBroadcast(context, REQuEST_CODE, intent, flags);
}
/**
* Cancels the period widget updates.
*
* @param context The context.
*/
public static void cancelUpdates(Context context) {
Log.d(TAG, "Canceling periodic widget updates.");
AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(createIntent(context));
}
}
@@ -1,205 +0,0 @@
package com.mowesta.android.app.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import com.mowesta.android.app.IApp;
import com.mowesta.android.app.database.Widget;
import com.mowesta.android.app.database.WidgetAccessor;
import com.mowesta.android.app.database.WidgetDatabase;
import com.mowesta.android.feign.api.DefaultApi;
import com.mowesta.android.feign.model.City;
import com.mowesta.android.feign.model.Device;
import com.mowesta.android.feign.model.Measurement;
import com.mowesta.android.feign.model.MeasurementPage;
import com.mowesta.android.feign.model.WeatherForecast;
import com.mowesta.android.sdk.task.AbstractTask;
import java.util.List;
/**
* The service that updates the forecast widgets.
*
* @author Marcus
*/
public class WidgetService extends JobIntentService {
/**
* The extra containing the reference.
*/
public static final String EXTRA_WIDGET_REFERENCE = "reference";
/**
* The delay to update the data.
*/
private static final int DELAY_DATA = 24 * 60 * 60 * 1000;
/**
* The delay to update the content.
*/
private static final int DELAY_CONTENT = 1 * 60 * 60 * 1000;
/**
* The extra containing the widget type.
*/
public static final String EXTRA_WIDGET_TYPE = "type";
/**
* The id for the service.
*/
private static final int SERVICE_ID = 1111;
/**
* The log tag.
*/
private static final String TAG = "WidgetService";
/**
* A handler to perform work on the ui thread.
*/
private Handler handler = new Handler(Looper.getMainLooper());
/**
* Schedules an update for a particular widget referenced by its type and its
* local id.
*
* @param context Tthe context.
* @param reference The widget reference.
* @param type The widget type.
*/
public static void scheduleUpdate(Context context, int type, int reference) {
Log.d(TAG, "Schedule background update for widget " + reference + " type " + type + ".");
Intent intent = new Intent();
intent.setClass(context, JobIntentService.class);
intent.putExtra(EXTRA_WIDGET_TYPE, type);
intent.putExtra(EXTRA_WIDGET_REFERENCE, reference);
// schedule background execution with proper locks
enqueueWork(context, WidgetService.class, SERVICE_ID, intent);
// and also execute immediately, if we are on > o
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Handler handler = new Handler(Looper.getMainLooper());
IApp app = (IApp)context.getApplicationContext();
new AbstractTask<Void>(true) {
@Override
protected Void doInBackground() {
updateWidget(app, handler, type, reference);
return null;
}
}.execute();
}
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
int type = intent.getIntExtra(EXTRA_WIDGET_TYPE, Widget.TYPE_INVALID);
int reference = intent.getIntExtra(EXTRA_WIDGET_REFERENCE, AppWidgetManager.INVALID_APPWIDGET_ID);
IApp app = (IApp)getApplicationContext();
updateWidget(app, handler, type, reference);
}
/**
* Updates the data contained in the widget and requests a ui update.
*
* @param app The app.
* @param handler A handler to trigger a refresh.
* @param type The type.
* @param reference The reference.
*/
public static void updateWidget(IApp app, Handler handler, int type, int reference) {
if (type == Widget.TYPE_INVALID || reference == AppWidgetManager.INVALID_APPWIDGET_ID) {
Log.d(TAG, "Received an invalid request for type " + type + " and reference " + reference + ".");
return;
}
WidgetDatabase database = app.getWidgetRepository().getDatabase();
WidgetAccessor accessor = database.getAccessor();
List<Widget> widgets = accessor.get(type, reference);
if (widgets.isEmpty()) {
Log.d(TAG, "Received a request for removed widget with type " + type + " and reference " + reference + ".");
return;
}
Widget widget = widgets.get(0);
if (type == Widget.TYPE_FORECAST) {
try {
DefaultApi api = app.getClientFactory().createClient();
long time = System.currentTimeMillis();
City[] city = new City[] { widget.getData(City.class) };
long[] dataTime = new long[] { widget.getDataTime() };
if (city[0] == null || time - dataTime[0] > DELAY_DATA) {
city[0] = api.getCity(widget.getDataId());
dataTime[0] = time;
}
WeatherForecast[] content = new WeatherForecast[] { widget.getContent(WeatherForecast.class) };
long[] contentTime = new long[] { widget.getContentTime() };
if (content[0] == null || time - contentTime[0] > DELAY_CONTENT) {
content[0] = api.getCityForecast(widget.getDataId());
contentTime[0] = time;
}
database.runInTransaction(() -> {
Widget w = accessor.get(widget.getId());
if (w == null) return;
w.setDataTime(dataTime[0]);
w.setData(city[0]);
w.setContentTime(contentTime[0]);
w.setContent(content[0]);
accessor.update(w);
});
} catch (Exception e) {
Log.e(TAG, "Failed to update widget state with type " + type + " and reference " + reference + ".", e);
}
Widget w = accessor.get(widget.getId());
if (w != null) {
handler.post(()-> {
ForecastWidgetProvider provider = new ForecastWidgetProvider();
provider.updateWidget(app.getContext(), w);
});
}
} else if (type == Widget.TYPE_MEASURE) {
try {
DefaultApi api = app.getClientFactory().createClient(app.getUserRepository().getCredentials().getValue());
long time = System.currentTimeMillis();
Device[] device = new Device[] { widget.getData(Device.class) };
long[] dataTime = new long[] { widget.getDataTime() };
if (device[0] == null || time - dataTime[0] > DELAY_DATA) {
device[0] = api.getDevice(widget.getDataId());
dataTime[0] = time;
}
Measurement[] content = new Measurement[] { widget.getContent(Measurement.class) };
long[] contentTime = new long[] { widget.getContentTime() };
if (content[0] == null || time - contentTime[0] > DELAY_CONTENT) {
MeasurementPage page = api.getDeviceMeasurements(widget.getDataId(), 0l, time, 0, 1);
if (page.getElements().size() > 0) {
content[0] = page.getElements().get(0);
contentTime[0] = time;
}
}
database.runInTransaction(() -> {
Widget w = accessor.get(widget.getId());
if (w == null) return;
w.setDataTime(dataTime[0]);
w.setData(device[0]);
w.setContentTime(contentTime[0]);
w.setContent(content[0]);
accessor.update(w);
});
} catch (Exception e) {
Log.e(TAG, "Failed to update widget state with type " + type + " and reference " + reference + ".", e);
}
Widget w = accessor.get(widget.getId());
if (w != null) {
handler.post(()-> {
MeasureWidgetProvider provider = new MeasureWidgetProvider();
provider.updateWidget(app.getContext(), w);
});
}
}
}
}
@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M20.94,11c-0.46,-4.17 -3.77,-7.48 -7.94,-7.94L13,1h-2v2.06c-1.13,0.12 -2.19,0.46 -3.16,0.97l1.5,1.5C10.16,5.19 11.06,5 12,5c3.87,0 7,3.13 7,7 0,0.94 -0.19,1.84 -0.52,2.65l1.5,1.5c0.5,-0.96 0.84,-2.02 0.97,-3.15L23,13v-2h-2.06zM3,4.27l2.04,2.04C3.97,7.62 3.25,9.23 3.06,11L1,11v2h2.06c0.46,4.17 3.77,7.48 7.94,7.94L11,23h2v-2.06c1.77,-0.2 3.38,-0.91 4.69,-1.98L19.73,21 21,19.73 4.27,3 3,4.27zM16.27,17.54C15.09,18.45 13.61,19 12,19c-3.87,0 -7,-3.13 -7,-7 0,-1.61 0.55,-3.09 1.46,-4.27l9.81,9.81z"/>
</vector>
@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-6h2v6zM13,9h-2L11,7h2v2z"/>
</vector>
@@ -9,7 +9,7 @@
<com.google.android.material.navigation.NavigationView
android:id="@+id/navigation_view"
android:layout_width="210dp"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:itemTextAppearance="?attr/textAppearanceBody1"
@@ -6,6 +6,7 @@
tools:context=".MowestaActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="false"
android:id="@+id/layout_coordinator">
<androidx.fragment.app.FragmentContainerView
@@ -1,6 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent">
@@ -10,4 +12,4 @@
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="model"
type="com.mowesta.android.app.model.AdvertiseViewModel" />
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/header"
android:background="@color/accent"
tools:targetApi="21"
android:elevation="4dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Space
android:layout_width="@dimen/space_medium"
android:layout_height="wrap_content"/>
<ImageView
android:contentDescription="@null"
android:layout_width="48dp"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"
app:tint="@color/fg_accent"
app:srcCompat="@drawable/ic_info_normal_24"/>
<TextView
android:layout_weight="1"
android:layout_marginStart="@dimen/space_medium"
android:layout_marginEnd="@dimen/space_medium"
android:layout_gravity="center_vertical"
style="@style/TextAppearance.MaterialComponents.Subtitle1"
android:text="@string/advertise_header"
android:textColor="@color/fg_accent"
android:singleLine="true"
android:ellipsize="end"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
<ImageButton
android:contentDescription="@string/button_close"
android:layout_width="48dp"
app:tint="@color/fg_accent"
android:layout_height="wrap_content"
android:onClick="@{ () -> model.close() }"
style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
app:srcCompat="@drawable/ic_close_normal_24" />
</LinearLayout>
<RelativeLayout
android:clickable="true"
android:focusable="true"
android:onClick="@{ () -> model.open() }"
android:layout_width="match_parent"
android:layout_height="180dp">
<androidx.media3.ui.PlayerView
android:id="@+id/video_view"
android:layout_alignParentBottom="true"
app:use_controller="false"
app:resize_mode="zoom"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="@+id/ad_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:padding="8dp"
android:text="@string/advertise_title"
android:textAppearance="?attr/textAppearanceHeadline3"
android:textColor="@color/white" />
<TextView
android:text="@string/advertise_more"
android:textAppearance="?attr/textAppearanceBody1"
android:layout_centerInParent="true"
android:paddingTop="16dp"
android:paddingBottom="8dp"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:gravity="center"
android:textStyle="bold"
android:textColor="@color/accent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/ad_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:padding="8dp"
android:text="@string/advertise_description"
android:textAppearance="?attr/textAppearanceBody2"
android:textColor="@color/white"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
</layout>
@@ -38,7 +38,7 @@
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="@color/primary"
app:itemIconTint="@drawable/selector_navigation"
@@ -30,6 +30,8 @@
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:inputType="text"
android:hint="@string/action_search"
android:text="@={model.term}" />
@@ -8,7 +8,7 @@
android:layout_height="match_parent">
<com.google.android.exoplayer2.ui.PlayerView
<androidx.media3.ui.PlayerView
android:id="@+id/video_view"
android:layout_centerInParent="true"
app:resize_mode="zoom"
@@ -7,14 +7,17 @@
android:id="@+id/layout_appbar"
android:theme="@style/ThemeOverlay.MaterialComponents.Dark"
app:liftOnScroll="true"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="128dp">
android:layout_height="@dimen/appbar_height">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="@+id/layout_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:statusBarScrim="?attr/colorPrimary"
app:collapsedTitleTextAppearance="@style/TextAppearance.Mowesta.AppBar.Collapsed"
app:expandedTitleTextAppearance="@style/TextAppearance.Mowesta.AppBar.Expanded"
app:expandedTitleMarginStart="40dp"
@@ -29,6 +32,7 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:fitsSystemWindows="true"
app:srcCompat="@drawable/icon_launch_sun"
android:scaleType="fitEnd"
app:layout_collapseMode="parallax" />
@@ -5,14 +5,17 @@
xmlns:tools="http://schemas.android.com/tools"
android:theme="@style/ThemeOverlay.MaterialComponents.Dark"
android:id="@+id/layout_appbar"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="128dp">
android:layout_height="@dimen/appbar_height">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="@+id/layout_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:statusBarScrim="?attr/colorPrimary"
app:collapsedTitleTextAppearance="@style/TextAppearance.Mowesta.AppBar.Collapsed"
app:expandedTitleTextAppearance="@style/TextAppearance.Mowesta.AppBar.Expanded"
app:expandedTitleMarginStart="40dp"
@@ -24,7 +27,8 @@
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<com.locoslab.android.leafless.MapView
android:id="@+id/map"
android:layout_centerInParent="true"
@@ -41,7 +41,7 @@
android:layout_height="wrap_content"
tools:text="Sony Xperia Foo"
android:gravity="end"
android:lines="1"
android:maxLines="2"
android:ellipsize="end"
android:id="@+id/view_header_device"
android:textAppearance="?android:attr/textAppearanceSmallInverse" />
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/widget_measure"
android:orientation="vertical"
android:gravity="center"
tools:layout_width="110dp"
tools:layout_height="40dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/widget_device_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:shadowColor="@color/black"
android:paddingStart="1dp"
android:paddingEnd="1dp"
android:textStyle="bold"
android:shadowRadius="3"
android:shadowDx="1"
android:shadowDy="1"
android:textSize="12sp"
android:ellipsize="end"
android:maxLines="1"
android:text="@string/widget_loading" />
</LinearLayout>
@@ -33,12 +33,12 @@
app:exitAnim="@anim/slide_out_left"
app:destination="@id/destination_login" />
<action
android:id="@+id/action_splash_collection"
android:id="@+id/action_splash_core"
app:popUpTo="@id/destination_splash"
app:popUpToInclusive="true"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left"
app:destination="@id/destination_collection" />
app:destination="@id/navigation_core" />
</fragment>
<fragment
android:id="@+id/destination_terms"
@@ -66,25 +66,19 @@
android:label="@string/navigation_login"
tools:layout="@layout/fragment_login">
<action
android:id="@+id/action_login_collection"
android:id="@+id/action_login_drawer"
app:popUpTo="@id/destination_login"
app:popUpToInclusive="true"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left"
app:destination="@id/destination_collection" />
</fragment>
<fragment
android:id="@+id/destination_collection"
android:name="com.mowesta.android.app.fragment.CollectionFragment"
android:label="@string/navigation_login"
tools:layout="@layout/fragment_login">
<action
android:id="@+id/action_collection_drawer"
app:popUpTo="@id/destination_collection"
app:popUpToInclusive="true"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left"
app:destination="@id/navigation_core" />
</fragment>
<action
android:id="@+id/action_core"
app:popUpTo="@id/destination_splash"
app:popUpToInclusive="true"
app:launchSingleTop="true"
app:destination="@id/navigation_core" />
</navigation>
@@ -87,6 +87,7 @@
android:id="@+id/action_drawer"
app:popUpTo="@id/destination_drawer"
app:popUpToInclusive="true"
app:launchSingleTop="true"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left"
app:destination="@id/destination_drawer" />
+11 -2
View File
@@ -16,9 +16,11 @@
<string name="button_yes">Ja</string>
<string name="button_no">Nein</string>
<string name="message_no_browser">Dein Webbrowser konnte nicht geöffnet werden.</string>
<string name="message_no_permission">Der App fehlt eine notwendige Berechtigung.</string>
<string name="message_permission_title">Fehlende Berechtigung</string>
<string name="message_permission_background">Um automatisch Messungen zu erfassen, benötigt MoWeSta die Berechtigung auf den Gerätestandort im Hintergrund zugreifen zu können.</string>
<string name="message_permission_foreground">Um den Standort automatisch zu bestimmen, benötigt MoWeSta die Berechtigung auf den Gerätestandort zugreifen zu können.</string>
<string name="message_configure_failed">Die Einstellungen konnten nicht geöffnet werden.</string>
<string name="button_configure">An-\npassen</string>
<string name="button_configure">Einstellungen anpasssen</string>
<!-- video controls -->
<string name="button_fit_screen">Anzeige anpasen</string>
@@ -311,6 +313,7 @@
<string name="widget_measure_time">Uhrzeit</string>
<string name="widget_measure_date">Datum</string>
<string name="widget_measure_explain">Um die Messungen Deiner Geräte auf Deinem Startbildschirm anzeigen zu können, musst Du Dich leider erst mit Deinem Konto anmelden.</string>
<string name="widget_loading">Lädt…</string>
<string name="color_dialog_open">Farbe anpassen</string>
<string name="color_dialog_example">Beispiel</string>
@@ -318,4 +321,10 @@
<string name="color_dialog_blue">Blau</string>
<string name="color_dialog_green">Grün</string>
<string name="advertise_header">Veranstaltungshinweis</string>
<string name="advertise_description">Mach mit beim FAIR Experiment bei DAS FEST vom 21. bis zum 24. Juli in Karlsruhe</string>
<string name="advertise_more">Mehr erfahren…</string>
<string name="advertise_title">DAS FEST</string>
</resources>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="match_parent_limit">
<item name="android:layout_width">390dp</item>
<item name="android:layout_width">340dp</item>
</style>
</resources>
@@ -1,6 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
<integer name="RecyclerWidth">375</integer>
<declare-styleable name="DataView">
<attr name="direction" format="enum">
<enum name="HORIZONTAL" value="0" />
@@ -6,5 +6,6 @@
<dimen name="space_medium">8dp</dimen>
<dimen name="max_font_headline">34sp</dimen>
<dimen name="min_font_headline">18sp</dimen>
<dimen name="appbar_height">176dp</dimen>
</resources>
+10 -2
View File
@@ -16,9 +16,11 @@
<string name="button_yes">Yes</string>
<string name="button_no">No</string>
<string name="message_no_browser">Unable to open your web browser.</string>
<string name="message_no_permission">The app is missing a required permission.</string>
<string name="message_permission_title">Missing Permission</string>
<string name="message_permission_background">To automatically collect measurements, MoWeSta needs your permission to locate your device in the background.</string>
<string name="message_permission_foreground">To automatically set the location, MoWeSta needs your permission to locate your device.</string>
<string name="message_configure_failed">Could not open the app settings.</string>
<string name="button_configure">Con-\nfigure</string>
<string name="button_configure">Configure settings</string>
<!-- video controls -->
<string name="button_fit_screen">Match screen</string>
@@ -316,10 +318,16 @@
<string name="widget_measure_time">Time</string>
<string name="widget_measure_date">Date</string>
<string name="widget_measure_explain">To display the measurements of your devices on your home screen, you have to set up your account.</string>
<string name="widget_loading">Loading…</string>
<string name="color_dialog_open">Adjust color</string>
<string name="color_dialog_example">Example</string>
<string name="color_dialog_red">Red</string>
<string name="color_dialog_blue">Blue</string>
<string name="color_dialog_green">Green</string>
<string name="advertise_header">Event note</string>
<string name="advertise_description">Join the FAIR Experiment at DAS FEST from July 21th to 24th in Karlsruhe</string>
<string name="advertise_more">Read more…</string>
<string name="advertise_title">DAS FEST</string>
</resources>
+3 -3
View File
@@ -1,12 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
<resources>
<style name="Theme.Mowesta" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primaryDark</item>
<item name="colorAccent">@color/accent</item>
<item name="android:navigationBarColor" tools:targetApi="21">@color/primary</item>
<item name="android:navigationBarColor" >@color/primary</item>
<item name="fontFamily">@font/text</item>
<item name="colorOnPrimary">@color/white</item>
</style>
@@ -31,7 +31,7 @@
<style name="TextAppearance.Mowesta.TabLayout" parent="TextAppearance.MaterialComponents.Button">
<item name="android:letterSpacing" tools:targetApi="21">0</item>
<item name="android:letterSpacing">0</item>
</style>
</resources>
-29
View File
@@ -2,12 +2,6 @@
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="@string/setting_category_privacy" >
<CheckBoxPreference
android:icon="@drawable/ic_ac_unit_normal_24"
android:key="privacy_measure"
android:defaultValue="@bool/privacy_measure_default"
android:summary="@string/setting_privacy_measure_summary"
android:title="@string/setting_privacy_measure_title" />
<Preference
android:icon="@drawable/ic_delete_forever_normal_24"
android:key="privacy_reset"
@@ -21,11 +15,6 @@
android:key="notification_app"
android:summary="@string/setting_notification_app_summary"
android:title="@string/setting_notification_app_title" />
<Preference
android:icon="@drawable/ic_android_normal_24"
android:key="notification_os"
android:summary="@string/setting_notification_os_summary"
android:title="@string/setting_notification_os_title" />
</PreferenceCategory>
<PreferenceCategory android:title="@string/setting_category_about" >
@@ -66,24 +55,6 @@
android:key="development_clear_cache"
android:title="@string/setting_development_clear_title"
android:summary="@string/setting_development_clear_summary"/>
<CheckBoxPreference
android:icon="@drawable/ic_storage_normal_24"
android:key="mowesta_sdk_use_cache"
android:defaultValue="@bool/mowesta_sdk_use_cache_default"
android:summary="@string/setting_development_cache_summary"
android:title="@string/setting_development_cache_title" />
<CheckBoxPreference
android:icon="@drawable/ic_gps_fixed_normal_24"
android:key="mowesta_sdk_use_gps"
android:defaultValue="@bool/mowesta_sdk_use_gps_default"
android:summary="@string/setting_development_gps_summary"
android:title="@string/setting_development_gps_title" />
<CheckBoxPreference
android:icon="@drawable/ic_wifi_normal_24"
android:key="mowesta_sdk_use_network"
android:defaultValue="@bool/mowesta_sdk_use_network_default"
android:summary="@string/setting_development_net_summary"
android:title="@string/setting_development_net_title" />
</PreferenceCategory>
</PreferenceScreen>
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:minWidth="250dp"
android:minHeight="80dp"
android:minResizeHeight="40dp"
@@ -9,5 +9,7 @@
android:widgetCategory="home_screen"
android:configure="com.mowesta.android.app.widget.ForecastWidgetActivity"
android:initialLayout="@layout/widget_forecast"
tools:targetApi="28"
android:widgetFeatures="reconfigurable"
android:updatePeriodMillis="43200000">
</appwidget-provider>
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:minWidth="110dp"
android:minHeight="110dp"
android:minResizeWidth="110dp"
@@ -9,5 +9,7 @@
android:widgetCategory="home_screen"
android:configure="com.mowesta.android.app.widget.MeasureWidgetActivity"
android:initialLayout="@layout/widget_measure"
tools:targetApi="28"
android:widgetFeatures="reconfigurable"
android:updatePeriodMillis="43200000">
</appwidget-provider>
@@ -1,41 +0,0 @@
package com.mowesta.android.app.test;
import androidx.test.core.app.ApplicationProvider;
import com.mowesta.android.app.R;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
/**
* Runs a simple roboelectric test.
*
* @author Marcus
*/
@RunWith(RobolectricTestRunner.class)
// you can use the @Config annotation here to configure
// various aspects of the test such as the SDK version,
// the resource type to be loaded (e.g. "en-port" for
// english resources in portrait mode, etc.
// @Config(qualifiers = "en-port", sdk = 18)
@Config(manifest = "AndroidManifest.xml")
public class MainActivityTest {
@Test
public void test() {
// if you do not have an activity or a context, you can get access
// to the application class through the "RuntimeEnvironment" object
String name = ApplicationProvider.getApplicationContext().getResources().getString(R.string.application_long);
System.out.println("The application name is: " + name);
// create an activity
// TODO: fix test failures caused by MainActivity
// Activity activity = Robolectric.setupActivity(MainActivity.class);
// String expectedTitle = activity.getResources().getString(R.string.application_short);
// Assert.assertEquals("Title should match resource.", expectedTitle, activity.getTitle());
// fumble around in the layout
// Assert.assertNotNull("MapView should be loaded.", activity.findViewById(R.id.map));
}
}
@@ -1,62 +0,0 @@
package com.mowesta.android.app.test;
import android.view.View;
import android.widget.Button;
import com.mowesta.android.app.R;
import com.mowesta.android.app.fragment.SplashFragment;
import com.mowesta.android.app.fragment.TermsFragment;
import com.mowesta.android.app.test.util.FragmentActivity;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;
import static org.robolectric.Shadows.shadowOf;
/**
* Runs a simple roboelectric test for start activity.
*
* @author sarah
*/
@RunWith(RobolectricTestRunner.class)
// you can use the @Config annotation here to configure
// various aspects of the test such as the SDK version,
// the resource type to be loaded (e.g. "en-port" for
// english resources in portrait mode, etc.
// @Config(qualifiers = "en-port", sdk = 18)
@Config(manifest = "AndroidManifest.xml")
public class StartActivityTest {
@Test
public void test() {
/*
// create start activity and show logo
ActivityController<FragmentActivity> ac = Robolectric.buildActivity(FragmentActivity.class);
FragmentActivity activity = ac.create().start().visible().resume().get();
final SplashFragment logoFragment = new SplashFragment();
activity.showFragment(logoFragment);
// change to T&Cs
final TermsFragment termsFragment = new TermsFragment();
activity.showFragment(termsFragment);
Assert.assertNotNull("WebView should be present.", activity.findViewById(R.id.web_view));
Assert.assertNotNull("Accept & continue button should be present.", activity.findViewById(R.id.start_button_continue));
// continue to main activity
Button buttonContinue = (Button) activity.findViewById(R.id.start_button_continue);
final boolean[] clicked = new boolean[1];
termsFragment.setOnContinueListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clicked[0] = true;
}
});
buttonContinue.performClick();
Assert.assertTrue("Button click should call continue.", clicked[0]);
*/
}
}
@@ -1,48 +0,0 @@
package com.mowesta.android.app.test.util;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.FrameLayout;
/**
* An activity showing a single fragment. This
* is useful for standalone fragment testing.
*
* @author Marcus
*/
public class FragmentActivity extends AppCompatActivity {
/**
* The id of the view. Somewhat hacky.
*/
public static final int FRAME_ID = 1;
/**
* Creates the fragment with a single frame layout.
*
* @param savedInstanceState The instance state.
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout view = new FrameLayout(this);
view.setId(FRAME_ID);
this.setContentView(view);
}
/**
* Replaces any fragment on the main view with the
* specified fragment.
*
* @param fragment The fragment.
*/
public void showFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction().replace(FRAME_ID, fragment).commit();
}
@Override
public void invalidateOptionsMenu() {
super.invalidateOptionsMenu();
}
}
@@ -1,151 +0,0 @@
package com.mowesta.android.app.test.util;
import com.mowesta.android.feign.api.DefaultApi;
import feign.QueryMap;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* A simple proxy generator that enables us to emulate the
* mowesta server locally while testing. If only one method
* is required, you can use the createApiProxy(String,Object)
* method to create a proxy that will return the specified
* object in response to a call to the specified method.
*
* @author Marcus
*/
public class ProxyGenerator {
/**
* An interface for a method filter.
*/
public interface IMethodFilter {
/**
* Returns true if the method is acceptable.
*
* @param m The method.
* @return True if accepted, false otherwise.
*/
boolean accept(Method m);
}
/**
* A method filter that filters out the generated
* methods of the feign library which contain a
* query param annotation (or app should not call
* these methods as it would become dependent on
* the feign library).
*/
public static final IMethodFilter QUERY_PARAM_FILTER = new IMethodFilter() {
@Override
public boolean accept(Method m) {
for (Annotation[] annos: m.getParameterAnnotations()) {
for (Annotation a: annos) {
if (a instanceof QueryMap) {
return false;
}
}
}
return true;
}
};
/**
* Creates a proxy for a in interface that will return the predefined
* values as result of every method call.
*
* @param type The type of the interface to implement.
* @param results The mapping between methods and results.
* @param <T> The interface type to implement.
* @return The proxy for the interface.
*/
@SuppressWarnings("unchecked")
public static <T> T createProxy(Class<T> type, final Map<Method, Object> results) {
return (T)Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (results.containsKey(method)) {
return results.get(method);
} else {
throw new RuntimeException("Method not proxied (fix your test case).");
}
}
});
}
/**
* Finds a method in an interface type and returns the associated method object.
*
* @param type The interface type.
* @param name The name of the method.
* @param filters A set of filters to apply during search.
* @return The method.
* @throws RuntimeException Thrown if the type does not contain the method or
* if the type specifies multiple methods with the same name.
*/
public static Method findMethod(Class<?> type, String name, IMethodFilter[] filters) {
Set<Method> candidates = new HashSet<>();
method: for (Method m: type.getMethods()) {
if (m.getName().equals(name)) {
for (IMethodFilter f: filters) {
if (! f.accept(m)) continue method;
}
candidates.add(m);
}
}
if (candidates.size() == 0) {
throw new RuntimeException("Cannot find method " + name + " in " + type.getName() + ".");
} else if (candidates.size() > 1) {
throw new RuntimeException("Found " + candidates.size() + " methods for " + name + " in " + type.getName() + ".");
} else {
return candidates.iterator().next();
}
}
/**
* Finds an api method by name.
*
* @param name The name of the method.
* @return The method.
* @throws RuntimeException Thrown if the type does not contain the method or
* if the type specifies multiple methods with the same name.
*/
public static Method findApiMethod(String name) {
return findMethod(DefaultApi.class, name, new IMethodFilter[] { QUERY_PARAM_FILTER });
}
/**
* Creates an api proxy that implements the methods specified by
* the map with the specified result.
*
* @param results The results.
* @return The proxy.
*/
public static DefaultApi createApiProxy(Map<Method, Object> results) {
return createProxy(DefaultApi.class, results);
}
/**
* Creates a simple api proxy that implements the method with the specified name
* using the specified result.
*
* @param method The method.
* @param result The result.
* @return The proxy.
*/
public static DefaultApi createApiProxy(String method, Object result) {
Map<Method, Object> results = new HashMap<>();
results.put(findApiMethod(method), result);
return createApiProxy(results);
}
}
-45
View File
@@ -1,45 +0,0 @@
plugins {
id 'org.hidetake.swagger.generator' version '2.18.2'
}
description = "Mowesta Android Feign"
// downgrade jackson for Android, since versions > 2.9
// will contain module-info.class files that will result
// in a large number of android lint warnings
versionJackson = "2.9.10"
dependencies {
api "de.grundid.opendatalab:geojson-jackson:${versionGeojson}"
api "io.swagger:swagger-annotations:${versionSwagger}"
api "com.fasterxml.jackson.core:jackson-core:${versionJackson}"
api "com.fasterxml.jackson.core:jackson-annotations:${versionJackson}"
api "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
api "com.fasterxml.jackson.datatype:jackson-datatype-joda:${versionJackson}"
api "javax.annotation:javax.annotation-api:${versionAnnotation}"
api "io.github.openfeign:feign-core:9.4.0"
api "io.github.openfeign:feign-jackson:9.4.0"
compileOnly "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.1"
swaggerCodegen 'io.swagger:swagger-codegen-cli:2.4.9'
}
sourceSets.main.java.srcDirs = ['src/main/java', 'build/swagger/src/main/java']
swaggerSources {
mowesta {
inputFile = file(project(':common-api:').buildDir.path + '/swagger/mowesta.json')
code {
outputDir = file("${project.buildDir}/swagger")
language = 'java'
configFile = file('config.json')
components = [ models: true, apis: 'Default']
rawOptions = [ '--import-mappings', 'Geometry=org.geojson.Geometry']
}
}
}
// require api build to access swagger definition
tasks['resolveSwaggerTemplate'].dependsOn(project(':common-api').tasks['build'])
// require swagger code gen before compilation
compileJava.dependsOn('generateSwaggerCode')
@@ -1,325 +0,0 @@
package com.mowesta.android.feign;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.mowesta.android.feign.auth.*;
import com.mowesta.android.feign.auth.OAuth.AccessTokenListener;
import feign.Feign;
import feign.RequestInterceptor;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-10-20T17:10:12.901+02:00")
public class ApiClient {
public interface Api {}
protected ObjectMapper objectMapper;
private String basePath = "https://www.mowesta.com/api";
private Map<String, RequestInterceptor> apiAuthorizations;
private Feign.Builder feignBuilder;
public ApiClient() {
objectMapper = createObjectMapper();
apiAuthorizations = new LinkedHashMap<String, RequestInterceptor>();
feignBuilder = Feign.builder()
.requestInterceptor(request -> {
Map<String, Collection<String>> headers = request.request().headers();
if (!headers.containsKey("Content-Type" ) && request.method().equals("DELETE") ) {
request.header("Content-Type", "application/json");
}
})
.encoder(new JacksonEncoder(objectMapper))
.decoder(new JacksonDecoder(objectMapper));
}
public ApiClient(String[] authNames) {
this();
for(String authName : authNames) {
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
}
}
/**
* Basic constructor for single auth name
* @param authName
*/
public ApiClient(String authName) {
this(new String[]{authName});
}
/**
* Helper constructor for single api key
* @param authName
* @param apiKey
*/
public ApiClient(String authName, String apiKey) {
this(authName);
this.setApiKey(apiKey);
}
/**
* Helper constructor for single basic auth or password oauth2
* @param authName
* @param username
* @param password
*/
public ApiClient(String authName, String username, String password) {
this(authName);
this.setCredentials(username, password);
}
/**
* Helper constructor for single password oauth2
* @param authName
* @param clientId
* @param secret
* @param username
* @param password
*/
public ApiClient(String authName, String clientId, String secret, String username, String password) {
this(authName);
this.getTokenEndPoint()
.setClientId(clientId)
.setClientSecret(secret)
.setUsername(username)
.setPassword(password);
}
public String getBasePath() {
return basePath;
}
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
return this;
}
public Map<String, RequestInterceptor> getApiAuthorizations() {
return apiAuthorizations;
}
public void setApiAuthorizations(Map<String, RequestInterceptor> apiAuthorizations) {
this.apiAuthorizations = apiAuthorizations;
}
public Feign.Builder getFeignBuilder() {
return feignBuilder;
}
public ApiClient setFeignBuilder(Feign.Builder feignBuilder) {
this.feignBuilder = feignBuilder;
return this;
}
private ObjectMapper createObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.registerModule(new JodaModule());
return objectMapper;
}
public ObjectMapper getObjectMapper(){
return objectMapper;
}
/**
* Creates a feign client for given API interface.
*
* Usage:
* ApiClient apiClient = new ApiClient();
* apiClient.setBasePath("http://localhost:8080");
* XYZApi api = apiClient.buildClient(XYZApi.class);
* XYZResponse response = api.someMethod(...);
* @param <T> Type
* @param clientClass Client class
* @return The Client
*/
public <T extends Api> T buildClient(Class<T> clientClass) {
return feignBuilder.target(clientClass, basePath);
}
/**
* Select the Accept header's value from the given accepts array:
* if JSON exists in the given array, use it;
* otherwise use all of them (joining into a string)
*
* @param accepts The accepts array to select from
* @return The Accept header to use. If the given array is empty,
* null will be returned (not to set the Accept header explicitly).
*/
public String selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) return null;
if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json";
return StringUtil.join(accepts, ",");
}
/**
* Select the Content-Type header's value from the given array:
* if JSON exists in the given array, use it;
* otherwise use the first one of the array.
*
* @param contentTypes The Content-Type array to select from
* @return The Content-Type header to use. If the given array is empty,
* JSON will be used.
*/
public String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) return "application/json";
if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json";
return contentTypes[0];
}
/**
* Helper method to configure the first api key found
* @param apiKey API key
*/
public void setApiKey(String apiKey) {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof ApiKeyAuth) {
ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization;
keyAuth.setApiKey(apiKey);
return ;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to configure the username/password for basic auth or password OAuth
* @param username Username
* @param password Password
*/
public void setCredentials(String username, String password) {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof HttpBasicAuth) {
HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization;
basicAuth.setCredentials(username, password);
return;
}
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.getTokenRequestBuilder().setUsername(username).setPassword(password);
return;
}
}
throw new RuntimeException("No Basic authentication or OAuth configured!");
}
/**
* Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return Token request builder
*/
public TokenRequestBuilder getTokenEndPoint() {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
return oauth.getTokenRequestBuilder();
}
}
return null;
}
/**
* Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return Authentication request builder
*/
public AuthenticationRequestBuilder getAuthorizationEndPoint() {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
return oauth.getAuthenticationRequestBuilder();
}
}
return null;
}
/**
* Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one)
* @param accessToken Access Token
* @param expiresIn Validity period in seconds
*/
public void setAccessToken(String accessToken, Long expiresIn) {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.setAccessToken(accessToken, expiresIn);
return;
}
}
}
/**
* Helper method to configure the oauth accessCode/implicit flow parameters
* @param clientId Client ID
* @param clientSecret Client secret
* @param redirectURI Redirect URI
*/
public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.getTokenRequestBuilder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRedirectURI(redirectURI);
oauth.getAuthenticationRequestBuilder()
.setClientId(clientId)
.setRedirectURI(redirectURI);
return;
}
}
}
/**
* Configures a listener which is notified when a new access token is received.
* @param accessTokenListener Acesss token listener
*/
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.registerAccessTokenListener(accessTokenListener);
return;
}
}
}
/**
* Gets request interceptor based on authentication name
* @param authName Authentiation name
* @return Request Interceptor
*/
public RequestInterceptor getAuthorization(String authName) {
return apiAuthorizations.get(authName);
}
/**
* Adds an authorization to be used by the client
* @param authName Authentication name
* @param authorization Request interceptor
*/
public void addAuthorization(String authName, RequestInterceptor authorization) {
if (apiAuthorizations.containsKey(authName)) {
throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations");
}
apiAuthorizations.put(authName, authorization);
feignBuilder.requestInterceptor(authorization);
}
}
@@ -1,86 +0,0 @@
package com.mowesta.android.feign;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Utilities to support Swagger encoding formats in Feign.
*/
public final class EncodingUtils {
/**
* Private constructor. Do not construct this class.
*/
private EncodingUtils() {}
/**
* <p>Encodes a collection of query parameters according to the Swagger
* collection format.</p>
*
* <p>Of the various collection formats defined by Swagger ("csv", "tsv",
* etc), Feign only natively supports "multi". This utility generates the
* other format types so it will be properly processed by Feign.</p>
*
* <p>Note, as part of reformatting, it URL encodes the parameters as
* well.</p>
* @param parameters The collection object to be formatted. This object will
* not be changed.
* @param collectionFormat The Swagger collection format (eg, "csv", "tsv",
* "pipes"). See the
* <a href="http://swagger.io/specification/#parameter-object-44">
* Swagger Spec</a> for more details.
* @return An object that will be correctly formatted by Feign.
*/
public static Object encodeCollection(Collection<?> parameters,
String collectionFormat) {
if (parameters == null) {
return parameters;
}
List<String> stringValues = new ArrayList<>(parameters.size());
for (Object parameter : parameters) {
// ignore null values (same behavior as Feign)
if (parameter != null) {
stringValues.add(encode(parameter));
}
}
// Feign natively handles single-element lists and the "multi" format.
if (stringValues.size() < 2 || "multi".equals(collectionFormat)) {
return stringValues;
}
// Otherwise return a formatted String
String[] stringArray = stringValues.toArray(new String[0]);
switch (collectionFormat) {
case "csv":
default:
return StringUtil.join(stringArray, ",");
case "ssv":
return StringUtil.join(stringArray, " ");
case "tsv":
return StringUtil.join(stringArray, "\t");
case "pipes":
return StringUtil.join(stringArray, "|");
}
}
/**
* URL encode a single query parameter.
* @param parameter The query parameter to encode. This object will not be
* changed.
* @return The URL encoded string representation of the parameter. If the
* parameter is null, returns null.
*/
public static String encode(Object parameter) {
if (parameter == null) {
return null;
}
try {
return URLEncoder.encode(parameter.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
// Should never happen, UTF-8 is always supported
throw new RuntimeException(e);
}
}
}
@@ -1,42 +0,0 @@
package com.mowesta.android.feign;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-10-20T17:10:12.901+02:00")
public class StringUtil {
/**
* Check if the given array contains the given value (with case-insensitive comparison).
*
* @param array The array
* @param value The value to search
* @return true if the array contains the value
*/
public static boolean containsIgnoreCase(String[] array, String value) {
for (String str : array) {
if (value == null && str == null) return true;
if (value != null && value.equalsIgnoreCase(str)) return true;
}
return false;
}
/**
* Join an array of strings with the given separator.
* <p>
* Note: This might be replaced by utility method from commons-lang or guava someday
* if one of those libraries is added as dependency.
* </p>
*
* @param array The array of strings
* @param separator The separator
* @return the resulting string
*/
public static String join(String[] array, String separator) {
int len = array.length;
if (len == 0) return "";
StringBuilder out = new StringBuilder();
out.append(array[0]);
for (int i = 1; i < len; i++) {
out.append(separator).append(array[i]);
}
return out.toString();
}
}
@@ -1,41 +0,0 @@
package com.mowesta.android.feign.auth;
import feign.RequestInterceptor;
import feign.RequestTemplate;
public class ApiKeyAuth implements RequestInterceptor {
private final String location;
private final String paramName;
private String apiKey;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
@Override
public void apply(RequestTemplate template) {
if ("query".equals(location)) {
template.query(paramName, apiKey);
} else if ("header".equals(location)) {
template.header(paramName, apiKey);
}
}
}

Some files were not shown because too many files have changed in this diff Show More