├── .idea
├── .name
├── codeStyles
│ ├── codeStyleConfig.xml
│ └── Project.xml
├── compiler.xml
├── kotlinc.xml
├── vcs.xml
├── AndroidProjectSystem.xml
├── .gitignore
├── migrations.xml
├── detekt.xml
├── deploymentTargetSelector.xml
├── misc.xml
├── gradle.xml
├── runConfigurations.xml
└── jarRepositories.xml
├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-ldpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-tvdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── xml
│ │ │ │ ├── file_paths.xml
│ │ │ │ ├── widget_large.xml
│ │ │ │ ├── widget_small.xml
│ │ │ │ ├── widget_medium.xml
│ │ │ │ └── preferences.xml
│ │ │ ├── drawable
│ │ │ │ ├── widget_preview_large.png
│ │ │ │ ├── widget_preview_small.png
│ │ │ │ ├── widget_preview_meduim.png
│ │ │ │ ├── widget_divider.xml
│ │ │ │ ├── splash.xml
│ │ │ │ ├── widget_rounded_bg.xml
│ │ │ │ ├── ic_error.xml
│ │ │ │ ├── ic_mail_outline.xml
│ │ │ │ ├── widget_rounded_bg_stroke.xml
│ │ │ │ ├── ic_event.xml
│ │ │ │ ├── ic_place.xml
│ │ │ │ ├── widget_inner_shadow_gradient_dark_vertical.xml
│ │ │ │ ├── widget_inner_shadow_gradient_light_horizontal.xml
│ │ │ │ ├── widget_inner_shadow_gradient_light_vertical.xml
│ │ │ │ ├── widget_inner_shadow_gradient_dark_horizontal.xml
│ │ │ │ ├── ic_refresh.xml
│ │ │ │ ├── ic_alarm.xml
│ │ │ │ ├── ic_clock.xml
│ │ │ │ ├── ic_source.xml
│ │ │ │ ├── ic_twitter.xml
│ │ │ │ ├── ic_github.xml
│ │ │ │ ├── ic_web.xml
│ │ │ │ ├── ic_icon.xml
│ │ │ │ ├── ic_icon_small.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ │ ├── values
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── styles.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── strings.xml
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ ├── activity_settings.xml
│ │ │ │ ├── activity_main.xml
│ │ │ │ ├── fragment_sub_webview.xml
│ │ │ │ ├── widget_period_item.xml
│ │ │ │ ├── widget_course_item_with_header.xml
│ │ │ │ ├── widget_course_item.xml
│ │ │ │ ├── widget_error.xml
│ │ │ │ ├── widget_small.xml
│ │ │ │ ├── widget_large.xml
│ │ │ │ └── widget_medium.xml
│ │ │ ├── values-night
│ │ │ │ ├── styles.xml
│ │ │ │ └── colors.xml
│ │ │ └── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ ├── java
│ │ │ └── net
│ │ │ │ └── twinte
│ │ │ │ ├── android
│ │ │ │ ├── datastore
│ │ │ │ │ ├── user
│ │ │ │ │ │ ├── UserDataStore.kt
│ │ │ │ │ │ └── TwinteBackendUserDataStore.kt
│ │ │ │ │ ├── schedulenotification
│ │ │ │ │ │ ├── ScheduleNotificationDataStore.kt
│ │ │ │ │ │ └── SharedPreferencesScheduleNotificationDataStore.kt
│ │ │ │ │ ├── resetcookiesforsamesite
│ │ │ │ │ │ ├── ResetCookiesForSameSiteDataStore.kt
│ │ │ │ │ │ └── ResetCookiesForSameSiteDataStoreImpl.kt
│ │ │ │ │ └── schedule
│ │ │ │ │ │ ├── ScheduleDataStore.kt
│ │ │ │ │ │ └── SharedPreferencesScheduleDataStore.kt
│ │ │ │ ├── MainApplication.kt
│ │ │ │ ├── widget
│ │ │ │ │ ├── WidgetCourseViewModel.kt
│ │ │ │ │ ├── SmallWidgetProvider.kt
│ │ │ │ │ ├── Utils.kt
│ │ │ │ │ ├── LargeWidgetProvider.kt
│ │ │ │ │ └── MediumWidgetProvider.kt
│ │ │ │ ├── network
│ │ │ │ │ ├── serversettings
│ │ │ │ │ │ ├── ServerSettings.kt
│ │ │ │ │ │ └── ProductionServerSettings.kt
│ │ │ │ │ ├── TwinteBackendHttpClient.kt
│ │ │ │ │ ├── V4ApiClient.kt
│ │ │ │ │ ├── QueryParameters.kt
│ │ │ │ │ ├── V4ApiClientImpl.kt
│ │ │ │ │ └── TwinteBackendHttpClientImpl.kt
│ │ │ │ ├── model
│ │ │ │ │ ├── Format.kt
│ │ │ │ │ ├── EventType.kt
│ │ │ │ │ ├── Day.kt
│ │ │ │ │ ├── Module.kt
│ │ │ │ │ └── Timetable.kt
│ │ │ │ ├── Network.kt
│ │ │ │ ├── mapping
│ │ │ │ │ └── proto
│ │ │ │ │ │ ├── EventTypeMapper.kt
│ │ │ │ │ │ ├── ModuleMapper.kt
│ │ │ │ │ │ ├── EventMapper.kt
│ │ │ │ │ │ ├── ScheduleMapper.kt
│ │ │ │ │ │ ├── RegisteredCourseMapper.kt
│ │ │ │ │ │ └── GetByDateResponseMapper.kt
│ │ │ │ ├── ShareScreen.kt
│ │ │ │ ├── SettingsActivity.kt
│ │ │ │ ├── MainApplicationModule.kt
│ │ │ │ ├── work
│ │ │ │ │ ├── UpdateScheduleWorker.kt
│ │ │ │ │ └── ScheduleNotifier.kt
│ │ │ │ └── SubWebViewFragment.kt
│ │ │ │ └── api
│ │ │ │ ├── unified
│ │ │ │ └── v1
│ │ │ │ │ ├── UnifiedServiceClientInterface.kt
│ │ │ │ │ └── UnifiedServiceClient.kt
│ │ │ │ ├── announcement
│ │ │ │ └── v1
│ │ │ │ │ ├── AnnouncementServiceClientInterface.kt
│ │ │ │ │ └── AnnouncementServiceClient.kt
│ │ │ │ ├── schoolcalendar
│ │ │ │ └── v1
│ │ │ │ │ ├── SchoolCalendarServiceClientInterface.kt
│ │ │ │ │ └── SchoolCalendarServiceClient.kt
│ │ │ │ ├── auth
│ │ │ │ └── v1
│ │ │ │ │ ├── AuthServiceClientInterface.kt
│ │ │ │ │ └── AuthServiceClient.kt
│ │ │ │ ├── donation
│ │ │ │ └── v1
│ │ │ │ │ ├── DonationServiceClientInterface.kt
│ │ │ │ │ └── DonationServiceClient.kt
│ │ │ │ └── timetable
│ │ │ │ └── v1
│ │ │ │ ├── TimetableServiceClientInterface.kt
│ │ │ │ └── TimetableServiceClient.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── net
│ │ │ └── twinte
│ │ │ └── android
│ │ │ ├── ExampleUnitTest.kt
│ │ │ └── datastore
│ │ │ ├── user
│ │ │ └── TwinteBackendUserDataStoreTest.kt
│ │ │ └── schedule
│ │ │ └── SharedPreferencesScheduleDataStoreTest.kt
│ └── androidTest
│ │ └── java
│ │ └── net
│ │ └── twinte
│ │ └── android
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle.kts
├── .gitattributes
├── settings.gradle.kts
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── libs.versions.toml
├── buf.gen.yml
├── .gitignore
├── README.md
├── .github
└── workflows
│ └── android.yml
├── gradle.properties
├── gradlew.bat
├── config
└── detekt
│ └── detekt.yml
└── gradlew
/.idea/.name:
--------------------------------------------------------------------------------
1 | TwinteAndroid
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | app/src/main/java/net/twinte/api/** linguist-generated=true
2 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | include(":app")
2 | rootProject.name = "TwinteAndroid"
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-ldpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-ldpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-tvdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-tvdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/xml/file_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/widget_preview_large.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/drawable/widget_preview_large.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/widget_preview_small.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/drawable/widget_preview_small.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/widget_preview_meduim.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/drawable/widget_preview_meduim.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/twin-te/twinte-android/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 16dp
3 | 21.67dp
4 |
5 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/datastore/user/UserDataStore.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.datastore.user
2 |
3 | interface UserDataStore {
4 | suspend fun validateGoogleIdToken(idToken: String): Boolean
5 | }
6 |
--------------------------------------------------------------------------------
/buf.gen.yml:
--------------------------------------------------------------------------------
1 | version: v2
2 | plugins:
3 | - remote: buf.build/protocolbuffers/java:v30.2
4 | out: app/src/main/java
5 | opt: lite
6 | - remote: buf.build/connectrpc/kotlin
7 | out: app/src/main/java
8 | opt: lite
9 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/MainApplication.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android
2 |
3 | import android.app.Application
4 | import dagger.hilt.android.HiltAndroidApp
5 |
6 | @HiltAndroidApp
7 | class MainApplication : Application()
8 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/datastore/schedulenotification/ScheduleNotificationDataStore.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.datastore.schedulenotification
2 |
3 | interface ScheduleNotificationDataStore {
4 | fun schedule()
5 | }
6 |
--------------------------------------------------------------------------------
/.idea/AndroidProjectSystem.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/widget/WidgetCourseViewModel.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.widget
2 |
3 | /**
4 | * ウィジットで表示される授業のVM
5 | */
6 | data class WidgetCourseViewModel(val name: String, val room: String, val time: String, val id: String?)
7 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/network/serversettings/ServerSettings.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.network.serversettings
2 |
3 | interface ServerSettings {
4 | val twinteBackendApiEndpointScheme: String
5 | val twinteBackendApiEndpointHost: String
6 | }
7 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | .idea/dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
10 | deploymentTargetDropDown.xml
11 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/network/TwinteBackendHttpClient.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.network
2 |
3 | import okhttp3.Response
4 |
5 | interface TwinteBackendHttpClient {
6 | suspend fun get(path: String, params: QueryParameters = QueryParameters()): Response
7 | }
8 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Apr 12 16:51:02 JST 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | *.jks
15 | .cxx
16 |
--------------------------------------------------------------------------------
/.idea/migrations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/detekt.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/network/serversettings/ProductionServerSettings.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.network.serversettings
2 |
3 | class ProductionServerSettings : ServerSettings {
4 | override val twinteBackendApiEndpointScheme: String = "https"
5 | override val twinteBackendApiEndpointHost: String = "app.twinte.net"
6 | }
7 |
--------------------------------------------------------------------------------
/.idea/deploymentTargetSelector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # twinte-android
2 |
3 | Twin:teのAndroid版ネイティブアプリ
4 |
5 | ## code generation
6 |
7 | 1. https://buf.build/docs/cli/installation/ を参考にBuf CLIをインストールしてください
8 | 2. https://github.com/twin-te/twin-te をクローンします(ここでは `/path/to/twin-te` にクローンしたものとする)
9 | 3. リポジトリのルートで以下のコマンドを実行するとAPI用のコードが生成されます
10 |
11 | ```shell
12 | buf generate --template ./buf.gen.yml
13 | ```
14 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/widget_divider.xml:
--------------------------------------------------------------------------------
1 |
3 |
5 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/splash.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
8 |
9 | -
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/widget_rounded_bg.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/widget_large.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/widget_small.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/widget_medium.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/network/V4ApiClient.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.network
2 |
3 | import net.twinte.api.schoolcalendar.v1.SchoolCalendarServiceClient
4 | import net.twinte.api.timetable.v1.TimetableServiceClient
5 | import net.twinte.api.unified.v1.UnifiedServiceClient
6 |
7 | interface V4ApiClient {
8 | val timetable: TimetableServiceClient
9 | val schoolCalendar: SchoolCalendarServiceClient
10 | val unified: UnifiedServiceClient
11 | }
12 |
--------------------------------------------------------------------------------
/app/src/test/java/net/twinte/android/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android
2 |
3 | import org.junit.Assert.assertEquals
4 | import org.junit.Test
5 |
6 | /**
7 | * Example local unit test, which will execute on the development machine (host).
8 | *
9 | * See [testing documentation](http://d.android.com/tools/testing).
10 | */
11 | class ExampleUnitTest {
12 | @Test
13 | fun addition_isCorrect() {
14 | assertEquals(4, 2 + 2)
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/model/Format.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.model
2 |
3 | import com.google.gson.annotations.SerializedName
4 |
5 | enum class Format(val f: String) {
6 | @SerializedName("Asynchronous")
7 | OnlineAsynchronous("オンデマンド"),
8 |
9 | @SerializedName("Synchronous")
10 | OnlineSynchronous("同時双方向"),
11 |
12 | @SerializedName("FaceToFace")
13 | FaceToFace("対面"),
14 |
15 | @SerializedName("Others")
16 | Others("その他"),
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/network/QueryParameters.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.network
2 |
3 | /**
4 | * リクエスト送信時に指定するクエリパラメータを保持するためのデータ構造
5 | */
6 | typealias QueryParameters = MutableMap
7 |
8 | /**
9 | * 空のクエリパラメータ
10 | */
11 | fun QueryParameters(): QueryParameters = mutableMapOf()
12 |
13 | /**
14 | * クエリパラメータを指定するための shorthand 用関数
15 | */
16 | fun params(block: QueryParameters.() -> Unit): QueryParameters =
17 | QueryParameters().apply(block)
18 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_error.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/datastore/resetcookiesforsamesite/ResetCookiesForSameSiteDataStore.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.datastore.resetcookiesforsamesite
2 |
3 | /**
4 | * ref: https://github.com/twin-te/twinte-android/issues/44
5 | * SameSite 属性が付与されていない twinte_session Cookie があるとき、
6 | * lTWINS からの時間割インポートに失敗するため、一度 WebView が利用できる Cookie を
7 | * すべて削除し、再度 Twin:te の認証を行わせるために利用される DataStore
8 | */
9 | interface ResetCookiesForSameSiteDataStore {
10 | var shouldResetCookiesForSameSite: Boolean
11 | }
12 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_mail_outline.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/model/EventType.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.model
2 |
3 | import com.google.gson.annotations.SerializedName
4 |
5 | enum class EventType(val e: String) {
6 | @SerializedName("Holiday")
7 | Holiday("休日"),
8 |
9 | @SerializedName("PublicHoliday")
10 | PublicHoliday("祝日"),
11 |
12 | @SerializedName("Exam")
13 | Exam("試験"),
14 |
15 | @SerializedName("SubstituteDay")
16 | SubstituteDay("振替授業日"),
17 |
18 | @SerializedName("Other")
19 | Other("その他"),
20 | }
21 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/widget_rounded_bg_stroke.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_event.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/datastore/schedule/ScheduleDataStore.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.datastore.schedule
2 |
3 | import net.twinte.android.model.Timetable
4 | import java.util.Calendar
5 | import java.util.Date
6 |
7 | interface ScheduleDataStore {
8 | suspend fun update(
9 | calendar: Array = arrayOf(
10 | Calendar.getInstance().time,
11 | Calendar.getInstance().apply { add(Calendar.DATE, 1) }.time,
12 | ),
13 | )
14 |
15 | suspend fun getSchedule(date: Date): Timetable?
16 | }
17 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_place.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/Network.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android
2 |
3 | import android.net.Uri
4 | import net.twinte.android.network.serversettings.ServerSettings
5 |
6 | fun twinteUrlBuilder(
7 | serverSettings: ServerSettings,
8 | ): Uri.Builder = Uri
9 | .Builder()
10 | .scheme(serverSettings.twinteBackendApiEndpointScheme)
11 | .path(serverSettings.twinteBackendApiEndpointHost)
12 |
13 | fun Uri.Builder.buildUrl() = build().toString()
14 | class NotLoggedInException(cause: Throwable? = null) : Throwable("Not Logged in", cause)
15 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/model/Day.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.model
2 |
3 | import com.google.gson.annotations.SerializedName
4 |
5 | enum class Day(val d: String) {
6 | @SerializedName("Sun")
7 | Sun("日"),
8 |
9 | @SerializedName("Mon")
10 | Mon("月"),
11 |
12 | @SerializedName("Tue")
13 | Tue("火"),
14 |
15 | @SerializedName("Wed")
16 | Wed("水"),
17 |
18 | @SerializedName("Thu")
19 | Thu("木"),
20 |
21 | @SerializedName("Fri")
22 | Fri("金"),
23 |
24 | @SerializedName("Sat")
25 | Sat("土"),
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/widget_inner_shadow_gradient_dark_vertical.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/widget_inner_shadow_gradient_light_horizontal.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/widget_inner_shadow_gradient_light_vertical.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/widget_inner_shadow_gradient_dark_horizontal.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_refresh.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_alarm.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_clock.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
13 |
14 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
11 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_sub_webview.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/net/twinte/android/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android
2 |
3 | import androidx.test.ext.junit.runners.AndroidJUnit4
4 | import androidx.test.platform.app.InstrumentationRegistry
5 | import org.junit.Assert.*
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | /**
10 | * Instrumented test, which will execute on an Android device.
11 | *
12 | * See [testing documentation](http://d.android.com/tools/testing).
13 | */
14 | @RunWith(AndroidJUnit4::class)
15 | class ExampleInstrumentedTest {
16 | @Test
17 | fun useAppContext() {
18 | // Context of the app under test.
19 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
20 | assertEquals("net.twinte.android", appContext.packageName)
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/mapping/proto/EventTypeMapper.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.mapping.proto
2 |
3 | import net.twinte.android.model.EventType as ModelEventType
4 | import net.twinte.api.schoolcalendar.v1.Type.EventType as ProtoEventType
5 |
6 | internal fun ProtoEventType.asModel(): ModelEventType = when (this) {
7 | ProtoEventType.EVENT_TYPE_UNSPECIFIED -> ModelEventType.Other
8 | ProtoEventType.EVENT_TYPE_HOLIDAY -> ModelEventType.Holiday
9 | ProtoEventType.EVENT_TYPE_PUBLIC_HOLIDAY -> ModelEventType.PublicHoliday
10 | ProtoEventType.EVENT_TYPE_EXAM -> ModelEventType.Exam
11 | ProtoEventType.EVENT_TYPE_SUBSTITUTE_DAY -> ModelEventType.SubstituteDay
12 | ProtoEventType.EVENT_TYPE_OTHER -> ModelEventType.Other
13 | ProtoEventType.UNRECOGNIZED -> ModelEventType.Other
14 | }
15 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/datastore/user/TwinteBackendUserDataStore.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.datastore.user
2 |
3 | import kotlinx.coroutines.Dispatchers
4 | import kotlinx.coroutines.withContext
5 | import net.twinte.android.network.TwinteBackendHttpClient
6 | import net.twinte.android.network.params
7 | import javax.inject.Inject
8 |
9 | class TwinteBackendUserDataStore @Inject constructor(
10 | private val twinteBackendHttpClient: TwinteBackendHttpClient,
11 | ) : UserDataStore {
12 | override suspend fun validateGoogleIdToken(idToken: String): Boolean = withContext(Dispatchers.IO) {
13 | val res = twinteBackendHttpClient.get(
14 | "/auth/v4/google/idToken",
15 | params {
16 | put("token", idToken)
17 | },
18 | )
19 | res.isSuccessful
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/model/Module.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.model
2 |
3 | import com.google.gson.annotations.SerializedName
4 |
5 | enum class Module(val m: String) {
6 | @SerializedName("SpringA")
7 | SpringA("春A"),
8 |
9 | @SerializedName("SpringB")
10 | SpringB("春B"),
11 |
12 | @SerializedName("SpringC")
13 | SpringC("春C"),
14 |
15 | @SerializedName("FallA")
16 | FallA("秋A"),
17 |
18 | @SerializedName("FallB")
19 | FallB("秋B"),
20 |
21 | @SerializedName("FallC")
22 | FallC("秋C"),
23 |
24 | @SerializedName("SummerVacation")
25 | SummerVacation("夏季休業中"),
26 |
27 | @SerializedName("SpringVacation")
28 | SpringVacation("春季休業中"),
29 |
30 | @SerializedName("Annual")
31 | Annual("通年"),
32 |
33 | @SerializedName("Unknown")
34 | Unknown("不明"),
35 | }
36 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/widget_period_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_source.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/unified/v1/UnifiedServiceClientInterface.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: unified/v1/service.proto
4 | //
5 | package net.twinte.api.unified.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.ResponseMessage
9 |
10 | /**
11 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
12 | * - shared.InvalidArgument
13 | * - shared.Unauthenticated
14 | * - shared.Unauthorized
15 | */
16 | public interface UnifiedServiceClientInterface {
17 | /**
18 | * GetByDate returns the resources related to the given date.
19 | * Only registered courses which will be held on the given date will be returned.
20 | */
21 | public suspend fun getByDate(request: Service.GetByDateRequest, headers: Headers = emptyMap()): ResponseMessage
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/mapping/proto/ModuleMapper.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.mapping.proto
2 |
3 | import net.twinte.android.model.Module as ModelModule
4 | import net.twinte.api.timetable.v1.Type.Module as ProtoModule
5 |
6 | internal fun ProtoModule.asModel(): ModelModule = when (this) {
7 | ProtoModule.MODULE_UNSPECIFIED -> ModelModule.Unknown
8 | ProtoModule.MODULE_SPRING_A -> ModelModule.SpringA
9 | ProtoModule.MODULE_SPRING_B -> ModelModule.SpringB
10 | ProtoModule.MODULE_SPRING_C -> ModelModule.SpringC
11 | ProtoModule.MODULE_SUMMER_VACATION -> ModelModule.SummerVacation
12 | ProtoModule.MODULE_FALL_A -> ModelModule.FallA
13 | ProtoModule.MODULE_FALL_B -> ModelModule.FallB
14 | ProtoModule.MODULE_FALL_C -> ModelModule.SpringC
15 | ProtoModule.MODULE_SPRING_VACATION -> ModelModule.SpringVacation
16 | ProtoModule.UNRECOGNIZED -> ModelModule.Unknown
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/announcement/v1/AnnouncementServiceClientInterface.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: announcement/v1/service.proto
4 | //
5 | package net.twinte.api.announcement.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.ResponseMessage
9 |
10 | /**
11 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
12 | * - shared.InvalidArgument
13 | * - shared.Unauthenticated
14 | * - shared.Unauthorized
15 | */
16 | public interface AnnouncementServiceClientInterface {
17 | public suspend fun listAnnouncements(request: Service.ListAnnouncementsRequest, headers: Headers = emptyMap()): ResponseMessage
18 |
19 | public suspend fun readAnnouncements(request: Service.ReadAnnouncementsRequest, headers: Headers = emptyMap()): ResponseMessage
20 | }
21 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/schoolcalendar/v1/SchoolCalendarServiceClientInterface.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: schoolcalendar/v1/service.proto
4 | //
5 | package net.twinte.api.schoolcalendar.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.ResponseMessage
9 |
10 | /**
11 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
12 | * - shared.InvalidArgument
13 | * - shared.Unauthenticated
14 | * - shared.Unauthorized
15 | */
16 | public interface SchoolCalendarServiceClientInterface {
17 | public suspend fun listEventsByDate(request: Service.ListEventsByDateRequest, headers: Headers = emptyMap()): ResponseMessage
18 |
19 | public suspend fun getModuleByDate(request: Service.GetModuleByDateRequest, headers: Headers = emptyMap()): ResponseMessage
20 | }
21 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_twitter.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/mapping/proto/EventMapper.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.mapping.proto
2 |
3 | import net.twinte.android.model.Day
4 | import net.twinte.api.shared.Type.Weekday
5 | import net.twinte.android.model.Timetable.Event as ModuleEvent
6 | import net.twinte.api.schoolcalendar.v1.Type.Event as ProtoEvent
7 |
8 | internal fun ProtoEvent.asModel(): ModuleEvent =
9 | ModuleEvent(
10 | date = date.value,
11 | eventType = type.asModel(),
12 | description = description,
13 | changeTo = changeTo.asModel(),
14 | )
15 |
16 | internal fun Weekday.asModel(): Day? = when (this) {
17 | Weekday.WEEKDAY_SUNDAY -> Day.Sun
18 | Weekday.WEEKDAY_MONDAY -> Day.Mon
19 | Weekday.WEEKDAY_TUESDAY -> Day.Tue
20 | Weekday.WEEKDAY_WEDNESDAY -> Day.Wed
21 | Weekday.WEEKDAY_THURSDAY -> Day.Thu
22 | Weekday.WEEKDAY_FRIDAY -> Day.Fri
23 | Weekday.WEEKDAY_SATURDAY -> Day.Sat
24 | else -> null
25 | }
26 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/mapping/proto/ScheduleMapper.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.mapping.proto
2 |
3 | import net.twinte.android.model.Day as ModelDay
4 | import net.twinte.android.model.Timetable.Course.Schedule as ModelSchedule
5 | import net.twinte.api.timetable.v1.Type.Day as ProtoDay
6 | import net.twinte.api.timetable.v1.Type.Schedule as ProtoSchedule
7 |
8 | internal fun ProtoSchedule.asModel(): ModelSchedule =
9 | ModelSchedule(
10 | module = module.asModel(),
11 | day = day.asModel() ?: ModelDay.Sun, // TODO: Fix
12 | period = period,
13 | room = locations,
14 | )
15 |
16 | internal fun ProtoDay.asModel(): ModelDay? = when (this) {
17 | ProtoDay.DAY_SUN -> ModelDay.Sun
18 | ProtoDay.DAY_MON -> ModelDay.Mon
19 | ProtoDay.DAY_TUE -> ModelDay.Tue
20 | ProtoDay.DAY_WED -> ModelDay.Wed
21 | ProtoDay.DAY_THU -> ModelDay.Thu
22 | ProtoDay.DAY_FRI -> ModelDay.Fri
23 | ProtoDay.DAY_SAT -> ModelDay.Sat
24 | else -> null
25 | }
26 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #1e2430
4 |
5 | @color/n_colorPrimary
6 | @color/n_widget_text_main
7 | @color/n_widget_text_sub
8 | @color/n_widget_text_disabled
9 | @color/n_widget_text_danger
10 |
11 | #1B202D
12 | #03050B
13 | #1B202C
14 | #141821
15 | #00141821
16 | #131720
17 | #00131720
18 | #141A22
19 | #1C2734
20 |
21 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/auth/v1/AuthServiceClientInterface.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: auth/v1/service.proto
4 | //
5 | package net.twinte.api.auth.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.ResponseMessage
9 |
10 | /**
11 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
12 | * - shared.InvalidArgument
13 | * - shared.Unauthenticated
14 | * - shared.Unauthorized
15 | */
16 | public interface AuthServiceClientInterface {
17 | public suspend fun getMe(request: Service.GetMeRequest, headers: Headers = emptyMap()): ResponseMessage
18 |
19 | public suspend fun deleteUserAuthentication(request: Service.DeleteUserAuthenticationRequest, headers: Headers = emptyMap()): ResponseMessage
20 |
21 | public suspend fun deleteAccount(request: Service.DeleteAccountRequest, headers: Headers = emptyMap()): ResponseMessage
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_github.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/datastore/resetcookiesforsamesite/ResetCookiesForSameSiteDataStoreImpl.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.datastore.resetcookiesforsamesite
2 |
3 | import android.content.Context
4 | import androidx.core.content.edit
5 | import dagger.hilt.android.qualifiers.ApplicationContext
6 | import javax.inject.Inject
7 |
8 | class ResetCookiesForSameSiteDataStoreImpl @Inject constructor(
9 | @ApplicationContext private val context: Context,
10 | ) : ResetCookiesForSameSiteDataStore {
11 | private val preferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
12 |
13 | override var shouldResetCookiesForSameSite: Boolean
14 | get() = preferences.getBoolean(KEY_RESET_COOKIES_FOR_SAMESITE, true)
15 | set(value) {
16 | preferences.edit {
17 | putBoolean(KEY_RESET_COOKIES_FOR_SAMESITE, value)
18 | }
19 | }
20 |
21 | companion object {
22 | const val FILE_NAME = "reset_cookies_For_samesite"
23 | private const val KEY_RESET_COOKIES_FOR_SAMESITE = "resetCookiesForSameSite"
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_web.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.github/workflows/android.yml:
--------------------------------------------------------------------------------
1 | on:
2 | push:
3 | branches:
4 | - master
5 | - develop
6 | pull_request:
7 | branches:
8 | - master
9 | - develop
10 |
11 | jobs:
12 | lint:
13 | runs-on: ubuntu-22.04
14 | timeout-minutes: 30
15 | steps:
16 | - uses: actions/checkout@v3
17 | - uses: actions/setup-java@v3
18 | with:
19 | distribution: zulu
20 | java-version: '17'
21 | cache: 'gradle'
22 | - name: Lint
23 | run: ./gradlew detekt lint
24 | test:
25 | runs-on: ubuntu-22.04
26 | timeout-minutes: 30
27 | steps:
28 | - uses: actions/checkout@v3
29 | - uses: actions/setup-java@v3
30 | with:
31 | distribution: zulu
32 | java-version: '17'
33 | cache: 'gradle'
34 | - name: Run tests
35 | run: ./gradlew testDebug --continue
36 | assemble:
37 | runs-on: ubuntu-22.04
38 | timeout-minutes: 30
39 | steps:
40 | - uses: actions/checkout@v3
41 | - uses: actions/setup-java@v3
42 | with:
43 | distribution: zulu
44 | java-version: '17'
45 | cache: 'gradle'
46 | - name: Build APK
47 | run: ./gradlew assemble
48 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
15 |
19 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/ShareScreen.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android
2 |
3 | import android.content.Intent
4 | import android.graphics.Bitmap
5 | import android.graphics.Canvas
6 | import android.webkit.WebView
7 | import androidx.core.content.FileProvider
8 | import androidx.core.graphics.createBitmap
9 | import java.io.File
10 | import java.io.FileOutputStream
11 |
12 | fun WebView.shareScreen(body: String) = context.run {
13 | val bmp = createBitmap(width, height)
14 | draw(Canvas(bmp))
15 |
16 | File(cacheDir, "images").mkdir()
17 | val uri = File(File(cacheDir, "images"), "share.png").let { shareFile ->
18 | FileOutputStream(shareFile).also { fos ->
19 | bmp.compress(Bitmap.CompressFormat.PNG, 100, fos)
20 | }.close()
21 | FileProvider.getUriForFile(this, "net.twinte.android.fileprovider", shareFile)
22 | }
23 |
24 | val sendIntent: Intent = Intent().apply {
25 | action = Intent.ACTION_SEND
26 | putExtra(Intent.EXTRA_STREAM, uri)
27 | putExtra(Intent.EXTRA_TEXT, body)
28 | addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
29 | type = "image/png"
30 | }
31 |
32 | val shareIntent = Intent.createChooser(sendIntent, null)
33 | startActivity(shareIntent)
34 | }
35 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 | android.defaults.buildfeatures.buildconfig=true
23 | android.nonTransitiveRClass=false
24 | android.nonFinalResIds=false
25 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/widget_course_item_with_header.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
12 |
13 |
22 |
23 |
28 |
29 |
30 |
33 |
34 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #00c0c0
4 | #007B8B
5 | #4380f8
6 |
7 | #eff1f6
8 | #FFFFFF
9 |
10 | #626A76
11 | #838E95
12 | #ADADAD
13 | #ED7F93
14 |
15 | #F3F5FA
16 | #EBEDF2
17 | #FFFFFF
18 | #E2E6ED
19 | #00E2E6ED
20 | #FAFAFA
21 | #00FAFAFA
22 | #D0DCE5
23 | #EEF0F5
24 |
25 | #19C6C6
26 | #DFE6F0
27 | #95A5AE
28 | #475258
29 | #ED7F93
30 |
31 |
--------------------------------------------------------------------------------
/app/src/test/java/net/twinte/android/datastore/user/TwinteBackendUserDataStoreTest.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.datastore.user
2 |
3 | import io.mockk.coEvery
4 | import io.mockk.every
5 | import io.mockk.mockk
6 | import io.mockk.slot
7 | import kotlinx.coroutines.ExperimentalCoroutinesApi
8 | import kotlinx.coroutines.test.runTest
9 | import net.twinte.android.network.QueryParameters
10 | import net.twinte.android.network.TwinteBackendHttpClient
11 | import okhttp3.Response
12 | import org.junit.Test
13 |
14 | class TwinteBackendUserDataStoreTest {
15 | @OptIn(ExperimentalCoroutinesApi::class)
16 | @Test
17 | fun validPath() = runTest {
18 | // given
19 | val httpClient = mockk()
20 | val datastore = TwinteBackendUserDataStore(
21 | httpClient,
22 | )
23 | val idToken = "idToken123"
24 | val pathSlot = slot()
25 | val argumentSlot = slot()
26 | coEvery { httpClient.get(capture(pathSlot), capture(argumentSlot)) } returns mockk().also {
27 | every { it.isSuccessful } returns true
28 | }
29 |
30 | // when
31 | datastore.validateGoogleIdToken(idToken)
32 |
33 | // then
34 | assert(pathSlot.captured == "/auth/v4/google/idToken")
35 | assert(argumentSlot.captured.getValue("token") == idToken)
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/unified/v1/UnifiedServiceClient.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: unified/v1/service.proto
4 | //
5 | package net.twinte.api.unified.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.Idempotency
9 | import com.connectrpc.MethodSpec
10 | import com.connectrpc.ProtocolClientInterface
11 | import com.connectrpc.ResponseMessage
12 | import com.connectrpc.StreamType
13 |
14 | /**
15 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
16 | * - shared.InvalidArgument
17 | * - shared.Unauthenticated
18 | * - shared.Unauthorized
19 | */
20 | public class UnifiedServiceClient(
21 | private val client: ProtocolClientInterface,
22 | ) : UnifiedServiceClientInterface {
23 | /**
24 | * GetByDate returns the resources related to the given date.
25 | * Only registered courses which will be held on the given date will be returned.
26 | */
27 | override suspend fun getByDate(request: Service.GetByDateRequest, headers: Headers): ResponseMessage = client.unary(
28 | request,
29 | headers,
30 | MethodSpec(
31 | "unified.v1.UnifiedService/GetByDate",
32 | net.twinte.api.unified.v1.Service.GetByDateRequest::class,
33 | net.twinte.api.unified.v1.Service.GetByDateResponse::class,
34 | StreamType.UNARY,
35 | idempotency = Idempotency.NO_SIDE_EFFECTS,
36 | ),
37 | )
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_icon.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_icon_small.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/mapping/proto/RegisteredCourseMapper.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.mapping.proto
2 |
3 | import net.twinte.android.model.Format
4 | import net.twinte.api.timetable.v1.Type.CourseMethod
5 | import net.twinte.android.model.Timetable.Course as ModelCourse
6 | import net.twinte.api.timetable.v1.Type.RegisteredCourse as ProtoCourse
7 |
8 | internal fun ProtoCourse.asModel(): ModelCourse =
9 | ModelCourse(
10 | id = id.value,
11 | name = name,
12 | instructor = instructors,
13 | year = year.value,
14 | methods = methodsList.map { it.asModel() }.toTypedArray(),
15 | schedules = schedulesList.map { it.asModel() }.toTypedArray(),
16 | course = takeIf { it.methodsCount > 0 || it.schedulesCount > 0 }?.let { bc ->
17 | ModelCourse.BaseCourse(
18 | name = bc.name,
19 | instructor = bc.instructors,
20 | year = bc.year.value,
21 | methods = bc.methodsList.map { it.asModel() }.toTypedArray(),
22 | schedules = bc.schedulesList.map { it.asModel() }.toTypedArray(),
23 | )
24 | },
25 | )
26 |
27 | internal fun CourseMethod.asModel(): Format = when (this) {
28 | CourseMethod.COURSE_METHOD_UNSPECIFIED -> Format.Others
29 | CourseMethod.COURSE_METHOD_ONLINE_ASYNCHRONOUS -> Format.OnlineAsynchronous
30 | CourseMethod.COURSE_METHOD_ONLINE_SYNCHRONOUS -> Format.OnlineSynchronous
31 | CourseMethod.COURSE_METHOD_FACE_TO_FACE -> Format.FaceToFace
32 | CourseMethod.COURSE_METHOD_OTHERS -> Format.Others
33 | CourseMethod.UNRECOGNIZED -> Format.Others
34 | }
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
6 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/mapping/proto/GetByDateResponseMapper.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.mapping.proto
2 |
3 | import android.os.Build
4 | import androidx.annotation.RequiresApi
5 | import net.twinte.android.model.Timetable
6 | import net.twinte.api.schoolcalendar.v1.Type.Module
7 | import net.twinte.api.unified.v1.Service.GetByDateResponse
8 | import java.time.LocalDate
9 | import net.twinte.android.model.Module as ModelModule
10 | import net.twinte.api.schoolcalendar.v1.Type.Module as ProtoModule
11 |
12 | @RequiresApi(Build.VERSION_CODES.O)
13 | internal fun GetByDateResponse.toTimetable(reqDate: LocalDate): Timetable {
14 | val currentModule = module
15 | .takeIf { it != Module.MODULE_UNSPECIFIED }
16 | ?.let { Timetable.CurrentModule(reqDate.year, it.asModel()) }
17 |
18 | return Timetable(
19 | date = reqDate.toString(),
20 | module = currentModule,
21 | events = eventsList.map { it.asModel() }.toTypedArray(),
22 | courses = registeredCoursesList.map { it.asModel() }.toTypedArray(),
23 | )
24 | }
25 |
26 | internal fun ProtoModule.asModel(): ModelModule = when (this) {
27 | ProtoModule.MODULE_UNSPECIFIED -> ModelModule.Unknown
28 | ProtoModule.MODULE_SPRING_A -> ModelModule.SpringA
29 | ProtoModule.MODULE_SPRING_B -> ModelModule.SpringB
30 | ProtoModule.MODULE_SPRING_C -> ModelModule.SpringC
31 | ProtoModule.MODULE_SUMMER_VACATION -> ModelModule.SummerVacation
32 | ProtoModule.MODULE_FALL_A -> ModelModule.FallA
33 | ProtoModule.MODULE_FALL_B -> ModelModule.FallB
34 | ProtoModule.MODULE_WINTER_VACATION -> ModelModule.Unknown // TODO: Fix
35 | ProtoModule.MODULE_FALL_C -> ModelModule.SpringC
36 | ProtoModule.MODULE_SPRING_VACATION -> ModelModule.SpringVacation
37 | ProtoModule.UNRECOGNIZED -> ModelModule.Unknown
38 | }
39 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/announcement/v1/AnnouncementServiceClient.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: announcement/v1/service.proto
4 | //
5 | package net.twinte.api.announcement.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.Idempotency
9 | import com.connectrpc.MethodSpec
10 | import com.connectrpc.ProtocolClientInterface
11 | import com.connectrpc.ResponseMessage
12 | import com.connectrpc.StreamType
13 |
14 | /**
15 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
16 | * - shared.InvalidArgument
17 | * - shared.Unauthenticated
18 | * - shared.Unauthorized
19 | */
20 | public class AnnouncementServiceClient(
21 | private val client: ProtocolClientInterface,
22 | ) : AnnouncementServiceClientInterface {
23 | override suspend fun listAnnouncements(request: Service.ListAnnouncementsRequest, headers: Headers): ResponseMessage = client.unary(
24 | request,
25 | headers,
26 | MethodSpec(
27 | "announcement.v1.AnnouncementService/ListAnnouncements",
28 | net.twinte.api.announcement.v1.Service.ListAnnouncementsRequest::class,
29 | net.twinte.api.announcement.v1.Service.ListAnnouncementsResponse::class,
30 | StreamType.UNARY,
31 | idempotency = Idempotency.NO_SIDE_EFFECTS,
32 | ),
33 | )
34 |
35 |
36 | override suspend fun readAnnouncements(request: Service.ReadAnnouncementsRequest, headers: Headers): ResponseMessage = client.unary(
37 | request,
38 | headers,
39 | MethodSpec(
40 | "announcement.v1.AnnouncementService/ReadAnnouncements",
41 | net.twinte.api.announcement.v1.Service.ReadAnnouncementsRequest::class,
42 | net.twinte.api.announcement.v1.Service.ReadAnnouncementsResponse::class,
43 | StreamType.UNARY,
44 | ),
45 | )
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Twin:te
3 |
4 | - 前日19時
5 | - 前日20時
6 | - 前日21時
7 | - 前日22時
8 | - 前日23時
9 | - 当日0時
10 | - 当日1時
11 | - 当日2時
12 | - 当日3時
13 | - 当日4時
14 | - 当日5時
15 | - 当日6時
16 | - 当日7時
17 | - 当日8時
18 |
19 |
20 | - 19
21 | - 20
22 | - 21
23 | - 22
24 | - 23
25 | - 0
26 | - 1
27 | - 2
28 | - 3
29 | - 4
30 | - 5
31 | - 6
32 | - 7
33 | - 8
34 |
35 |
36 | - 21
37 | - 6
38 |
39 | schedule
40 | 日程通知
41 | 学年暦の日程を通知します
42 | 小ウィジット
43 | 中ウィジット
44 | 大ウィジット
45 | 617914047709-9dgo7djtadc11tf1tlrh8fj70v3glahe.apps.googleusercontent.com
46 | 通知を許可して振替日程の通知を受け取る
47 | 設定
48 |
49 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/schoolcalendar/v1/SchoolCalendarServiceClient.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: schoolcalendar/v1/service.proto
4 | //
5 | package net.twinte.api.schoolcalendar.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.Idempotency
9 | import com.connectrpc.MethodSpec
10 | import com.connectrpc.ProtocolClientInterface
11 | import com.connectrpc.ResponseMessage
12 | import com.connectrpc.StreamType
13 |
14 | /**
15 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
16 | * - shared.InvalidArgument
17 | * - shared.Unauthenticated
18 | * - shared.Unauthorized
19 | */
20 | public class SchoolCalendarServiceClient(
21 | private val client: ProtocolClientInterface,
22 | ) : SchoolCalendarServiceClientInterface {
23 | override suspend fun listEventsByDate(request: Service.ListEventsByDateRequest, headers: Headers): ResponseMessage = client.unary(
24 | request,
25 | headers,
26 | MethodSpec(
27 | "schoolcalendar.v1.SchoolCalendarService/ListEventsByDate",
28 | net.twinte.api.schoolcalendar.v1.Service.ListEventsByDateRequest::class,
29 | net.twinte.api.schoolcalendar.v1.Service.ListEventsByDateResponse::class,
30 | StreamType.UNARY,
31 | idempotency = Idempotency.NO_SIDE_EFFECTS,
32 | ),
33 | )
34 |
35 |
36 | override suspend fun getModuleByDate(request: Service.GetModuleByDateRequest, headers: Headers): ResponseMessage = client.unary(
37 | request,
38 | headers,
39 | MethodSpec(
40 | "schoolcalendar.v1.SchoolCalendarService/GetModuleByDate",
41 | net.twinte.api.schoolcalendar.v1.Service.GetModuleByDateRequest::class,
42 | net.twinte.api.schoolcalendar.v1.Service.GetModuleByDateResponse::class,
43 | StreamType.UNARY,
44 | idempotency = Idempotency.NO_SIDE_EFFECTS,
45 | ),
46 | )
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/app/src/test/java/net/twinte/android/datastore/schedule/SharedPreferencesScheduleDataStoreTest.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.datastore.schedule
2 |
3 | import com.connectrpc.ResponseMessage
4 | import io.mockk.coEvery
5 | import io.mockk.every
6 | import io.mockk.mockk
7 | import io.mockk.slot
8 | import kotlinx.coroutines.ExperimentalCoroutinesApi
9 | import kotlinx.coroutines.test.runTest
10 | import net.twinte.android.network.V4ApiClient
11 | import net.twinte.api.shared.Type.RFC3339FullDate
12 | import net.twinte.api.unified.v1.Service.GetByDateRequest
13 | import net.twinte.api.unified.v1.Service.GetByDateResponse
14 | import net.twinte.api.unified.v1.UnifiedServiceClient
15 | import org.junit.Test
16 | import java.time.LocalDate
17 | import java.util.Date
18 | import java.util.TimeZone
19 |
20 | @OptIn(ExperimentalCoroutinesApi::class)
21 | class SharedPreferencesScheduleDataStoreTest {
22 | @Test
23 | fun validTimetablePath() = runTest {
24 | // given
25 | val unifiedClient = mockk()
26 | val v4Client = mockk()
27 | every { v4Client.unified } returns unifiedClient
28 |
29 | val datastore = SharedPreferencesScheduleDataStore(
30 | mockk(relaxed = true),
31 | v4Client,
32 | )
33 |
34 | val targetDate = LocalDate.of(2022, 6, 10)
35 | val dateSlot = slot()
36 |
37 | val success = ResponseMessage.Success(
38 | message = GetByDateResponse.getDefaultInstance(),
39 | headers = emptyMap(),
40 | trailers = emptyMap(),
41 | )
42 | coEvery { unifiedClient.getByDate(capture(dateSlot)) } returns success
43 |
44 | // when
45 | datastore.update(
46 | arrayOf(
47 | Date.from(
48 | targetDate.atStartOfDay(
49 | TimeZone.getDefault().toZoneId(),
50 | ).toInstant(),
51 | ),
52 | ),
53 | )
54 |
55 | // then
56 | assert(dateSlot.captured.date == RFC3339FullDate.newBuilder().setValue("2022-06-10").build())
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/auth/v1/AuthServiceClient.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: auth/v1/service.proto
4 | //
5 | package net.twinte.api.auth.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.Idempotency
9 | import com.connectrpc.MethodSpec
10 | import com.connectrpc.ProtocolClientInterface
11 | import com.connectrpc.ResponseMessage
12 | import com.connectrpc.StreamType
13 |
14 | /**
15 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
16 | * - shared.InvalidArgument
17 | * - shared.Unauthenticated
18 | * - shared.Unauthorized
19 | */
20 | public class AuthServiceClient(
21 | private val client: ProtocolClientInterface,
22 | ) : AuthServiceClientInterface {
23 | override suspend fun getMe(request: Service.GetMeRequest, headers: Headers): ResponseMessage = client.unary(
24 | request,
25 | headers,
26 | MethodSpec(
27 | "auth.v1.AuthService/GetMe",
28 | net.twinte.api.auth.v1.Service.GetMeRequest::class,
29 | net.twinte.api.auth.v1.Service.GetMeResponse::class,
30 | StreamType.UNARY,
31 | idempotency = Idempotency.NO_SIDE_EFFECTS,
32 | ),
33 | )
34 |
35 |
36 | override suspend fun deleteUserAuthentication(request: Service.DeleteUserAuthenticationRequest, headers: Headers): ResponseMessage = client.unary(
37 | request,
38 | headers,
39 | MethodSpec(
40 | "auth.v1.AuthService/DeleteUserAuthentication",
41 | net.twinte.api.auth.v1.Service.DeleteUserAuthenticationRequest::class,
42 | net.twinte.api.auth.v1.Service.DeleteUserAuthenticationResponse::class,
43 | StreamType.UNARY,
44 | ),
45 | )
46 |
47 |
48 | override suspend fun deleteAccount(request: Service.DeleteAccountRequest, headers: Headers): ResponseMessage = client.unary(
49 | request,
50 | headers,
51 | MethodSpec(
52 | "auth.v1.AuthService/DeleteAccount",
53 | net.twinte.api.auth.v1.Service.DeleteAccountRequest::class,
54 | net.twinte.api.auth.v1.Service.DeleteAccountResponse::class,
55 | StreamType.UNARY,
56 | ),
57 | )
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/donation/v1/DonationServiceClientInterface.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: donation/v1/service.proto
4 | //
5 | package net.twinte.api.donation.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.ResponseMessage
9 |
10 | /**
11 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
12 | * - shared.InvalidArgument
13 | * - shared.Unauthenticated
14 | * - shared.Unauthorized
15 | */
16 | public interface DonationServiceClientInterface {
17 | public suspend fun createOneTimeCheckoutSession(request: Service.CreateOneTimeCheckoutSessionRequest, headers: Headers = emptyMap()): ResponseMessage
18 |
19 | public suspend fun createSubscriptionCheckoutSession(request: Service.CreateSubscriptionCheckoutSessionRequest, headers: Headers = emptyMap()): ResponseMessage
20 |
21 | public suspend fun getPaymentUser(request: Service.GetPaymentUserRequest, headers: Headers = emptyMap()): ResponseMessage
22 |
23 | public suspend fun updatePaymentUser(request: Service.UpdatePaymentUserRequest, headers: Headers = emptyMap()): ResponseMessage
24 |
25 | public suspend fun listPaymentHistories(request: Service.ListPaymentHistoriesRequest, headers: Headers = emptyMap()): ResponseMessage
26 |
27 | public suspend fun listSubscriptionPlans(request: Service.ListSubscriptionPlansRequest, headers: Headers = emptyMap()): ResponseMessage
28 |
29 | public suspend fun getActiveSubscription(request: Service.GetActiveSubscriptionRequest, headers: Headers = emptyMap()): ResponseMessage
30 |
31 | public suspend fun unsubscribe(request: Service.UnsubscribeRequest, headers: Headers = emptyMap()): ResponseMessage
32 |
33 | public suspend fun getTotalAmount(request: Service.GetTotalAmountRequest, headers: Headers = emptyMap()): ResponseMessage
34 |
35 | public suspend fun listContributors(request: Service.ListContributorsRequest, headers: Headers = emptyMap()): ResponseMessage
36 | }
37 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/widget_course_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
19 |
20 |
23 |
24 |
30 |
31 |
43 |
44 |
50 |
51 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/widget_error.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
21 |
22 |
27 |
28 |
36 |
37 |
38 |
39 |
49 |
50 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/timetable/v1/TimetableServiceClientInterface.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: timetable/v1/service.proto
4 | //
5 | package net.twinte.api.timetable.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.ResponseMessage
9 |
10 | /**
11 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
12 | * - shared.InvalidArgument
13 | * - shared.Unauthenticated
14 | * - shared.Unauthorized
15 | */
16 | public interface TimetableServiceClientInterface {
17 | public suspend fun listCoursesByCodes(request: Service.ListCoursesByCodesRequest, headers: Headers = emptyMap()): ResponseMessage
18 |
19 | public suspend fun searchCourses(request: Service.SearchCoursesRequest, headers: Headers = emptyMap()): ResponseMessage
20 |
21 | public suspend fun createRegisteredCoursesByCodes(request: Service.CreateRegisteredCoursesByCodesRequest, headers: Headers = emptyMap()): ResponseMessage
22 |
23 | public suspend fun createRegisteredCourseManually(request: Service.CreateRegisteredCourseManuallyRequest, headers: Headers = emptyMap()): ResponseMessage
24 |
25 | public suspend fun listRegisteredCourses(request: Service.ListRegisteredCoursesRequest, headers: Headers = emptyMap()): ResponseMessage
26 |
27 | public suspend fun updateRegisteredCourse(request: Service.UpdateRegisteredCourseRequest, headers: Headers = emptyMap()): ResponseMessage
28 |
29 | public suspend fun deleteRegisteredCourse(request: Service.DeleteRegisteredCourseRequest, headers: Headers = emptyMap()): ResponseMessage
30 |
31 | public suspend fun createTag(request: Service.CreateTagRequest, headers: Headers = emptyMap()): ResponseMessage
32 |
33 | public suspend fun listTags(request: Service.ListTagsRequest, headers: Headers = emptyMap()): ResponseMessage
34 |
35 | public suspend fun updateTag(request: Service.UpdateTagRequest, headers: Headers = emptyMap()): ResponseMessage
36 |
37 | public suspend fun deleteTag(request: Service.DeleteTagRequest, headers: Headers = emptyMap()): ResponseMessage
38 |
39 | public suspend fun rearrangeTags(request: Service.RearrangeTagsRequest, headers: Headers = emptyMap()): ResponseMessage
40 | }
41 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/widget_small.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
22 |
23 |
30 |
31 |
32 |
38 |
39 |
46 |
47 |
50 |
51 |
59 |
60 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/network/V4ApiClientImpl.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.network
2 |
3 | import android.webkit.CookieManager
4 | import com.connectrpc.ProtocolClientConfig
5 | import com.connectrpc.extensions.GoogleJavaLiteProtobufStrategy
6 | import com.connectrpc.impl.ProtocolClient
7 | import com.connectrpc.okhttp.ConnectOkHttpClient
8 | import com.connectrpc.protocols.NetworkProtocol
9 | import net.twinte.android.network.serversettings.ServerSettings
10 | import net.twinte.api.schoolcalendar.v1.SchoolCalendarServiceClient
11 | import net.twinte.api.timetable.v1.TimetableServiceClient
12 | import net.twinte.api.unified.v1.UnifiedServiceClient
13 | import okhttp3.Cookie
14 | import okhttp3.CookieJar
15 | import okhttp3.HttpUrl
16 | import okhttp3.OkHttpClient
17 | import java.util.concurrent.TimeUnit
18 |
19 | class V4ApiClientImpl(
20 | private val serverSettings: ServerSettings,
21 | private val cookieManager: CookieManager,
22 | ) : V4ApiClient {
23 | private val okHttp = OkHttpClient.Builder()
24 | .connectTimeout(3, TimeUnit.SECONDS)
25 | .readTimeout(3, TimeUnit.SECONDS)
26 | .cookieJar(WebViewCookieJar(cookieManager))
27 | .build()
28 |
29 | private val protocolClient = ProtocolClient(
30 | httpClient = ConnectOkHttpClient(okHttp),
31 | config = ProtocolClientConfig(
32 | host = "${serverSettings.twinteBackendApiEndpointScheme}://${serverSettings.twinteBackendApiEndpointHost}/api/v4",
33 | serializationStrategy = GoogleJavaLiteProtobufStrategy(),
34 | networkProtocol = NetworkProtocol.CONNECT,
35 | ),
36 | )
37 |
38 | override val timetable = TimetableServiceClient(protocolClient)
39 | override val schoolCalendar = SchoolCalendarServiceClient(protocolClient)
40 | override val unified = UnifiedServiceClient(protocolClient)
41 |
42 | private class WebViewCookieJar(
43 | private val cm: CookieManager,
44 | ) : CookieJar {
45 | override fun loadForRequest(url: HttpUrl): List =
46 | cm.getCookie(url.toString())
47 | ?.split(";")
48 | ?.mapNotNull { raw ->
49 | raw.trim().split("=", limit = 2).takeIf { it.size == 2 }?.let { kv ->
50 | Cookie.Builder()
51 | .name(kv[0])
52 | .value(kv[1])
53 | .domain(url.host)
54 | .build()
55 | }
56 | }
57 | .orEmpty()
58 |
59 | override fun saveFromResponse(url: HttpUrl, cookies: List) {
60 | cookies.forEach { cm.setCookie(url.toString(), it.toString()) }
61 | cm.flush()
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/network/TwinteBackendHttpClientImpl.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.network
2 |
3 | import android.webkit.CookieManager
4 | import okhttp3.ConnectionPool
5 | import okhttp3.Cookie
6 | import okhttp3.CookieJar
7 | import okhttp3.HttpUrl
8 | import okhttp3.OkHttpClient
9 | import okhttp3.Request
10 | import okhttp3.Response
11 | import java.util.concurrent.TimeUnit
12 |
13 | class TwinteBackendHttpClientImpl(
14 | private val scheme: String,
15 | private val host: String,
16 | cookieManager: CookieManager,
17 | ) : TwinteBackendHttpClient {
18 | private val httpClient = OkHttpClient.Builder()
19 | .connectTimeout(3000, TimeUnit.MILLISECONDS)
20 | .retryOnConnectionFailure(true)
21 | .readTimeout(3000, TimeUnit.MILLISECONDS)
22 | .connectionPool(ConnectionPool(0, 1, TimeUnit.NANOSECONDS))
23 | .cookieJar(WebViewCookieJar(cookieManager)).build()
24 |
25 | private fun baseUrl() = HttpUrl
26 | .Builder()
27 | .scheme(scheme)
28 | .host(host)
29 |
30 | private fun HttpUrl.Builder.path(path: String) = apply {
31 | path.split("/").forEach { addEncodedPathSegment(it) }
32 | }
33 |
34 | private fun HttpUrl.Builder.query(params: QueryParameters) = apply {
35 | params.entries.forEach { (key, value) -> addQueryParameter(key, value) }
36 | }
37 |
38 | private fun Request.Builder.url(path: String, params: QueryParameters): Request.Builder =
39 | url(baseUrl().path(path).query(params).build())
40 |
41 | override suspend fun get(path: String, params: QueryParameters): Response =
42 | httpClient.newCall(
43 | Request
44 | .Builder()
45 | .url(path, params)
46 | .method("GET", null)
47 | .build(),
48 | ).execute()
49 |
50 | class WebViewCookieJar(
51 | private val cookieManager: CookieManager,
52 | ) : CookieJar {
53 | override fun loadForRequest(url: HttpUrl): List {
54 | val cookiesStr = cookieManager.getCookie(url.toUrl().toString()) ?: return emptyList()
55 | return cookiesStr.split(";").map {
56 | val r = Regex("(.*?)=(.*)").find(it) ?: return@map null
57 | Cookie.Builder()
58 | .name(r.groups[1]?.value?.trim() ?: return@map null)
59 | .value(r.groups[2]?.value ?: return@map null)
60 | .domain(url.host)
61 | .build()
62 | }.filterNotNull()
63 | }
64 |
65 | override fun saveFromResponse(url: HttpUrl, cookies: List) {
66 | cookies.forEach {
67 | cookieManager.setCookie(url.toString(), it.toString())
68 | }
69 | cookieManager.flush()
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/config/detekt/detekt.yml:
--------------------------------------------------------------------------------
1 | complexity:
2 | excludes: &generatedFiles
3 | - '**/net/twinte/api/**'
4 | LongMethod:
5 | active: true
6 | threshold: 90
7 | LongParameterList:
8 | # 関数に渡す引数の個数が多くなってしまっても仕方がない
9 | active: false
10 | TooManyFunctions:
11 | # 関数の個数が多くなってしまっても仕方がない
12 | active: false
13 |
14 | coroutines:
15 | excludes: *generatedFiles
16 | active: true
17 |
18 | exceptions:
19 | excludes: *generatedFiles
20 | active: true
21 |
22 | SwallowedException:
23 | # TODO: active にする
24 | active: false
25 | TooGenericExceptionCaught:
26 | # TODO: active にする
27 | active: false
28 |
29 | performance:
30 | excludes: *generatedFiles
31 | active: true
32 |
33 | ForEachOnRange:
34 | active: true
35 |
36 | potential-bugs:
37 | excludes: *generatedFiles
38 | active: true
39 |
40 | style:
41 | excludes: *generatedFiles
42 | active: true
43 | MagicNumber:
44 | # Jetpack Compose 関連のコードでマジックナンバーを用いる機会が通常のものとして増えたため無視する
45 | active: false
46 | MaxLineLength:
47 | # formatting の MaximumLineLength と衝突するためこちらを無効にする
48 | active: false
49 | ReturnCount:
50 | # 早期 return の数に制限を設けなくてもよさそうなので無効化
51 | active: false
52 | WildcardImport:
53 | active: true
54 | ForbiddenComment:
55 | comments:
56 | - reason: 'Forbidden FIXME todo marker in comment, please fix the problem.'
57 | value: 'FIXME:'
58 | - reason: 'Forbidden STOPSHIP todo marker in comment, please address the problem before shipping the code.'
59 | value: 'STOPSHIP:'
60 |
61 | naming:
62 | excludes: *generatedFiles
63 | active: true
64 |
65 | MatchingDeclarationName:
66 | active: true
67 |
68 | VariableNaming:
69 | active: true
70 |
71 | empty-blocks:
72 | active: true
73 | EmptyFunctionBlock:
74 | ignoreOverridden: true
75 |
76 | #####
77 | # `./gradlew detektProjectBaseline` でベースラインファイルを生成するときは
78 | # この行より下の部分をコメントアウトしてください
79 | #####
80 |
81 | formatting:
82 | excludes: *generatedFiles
83 | active: true
84 | autoCorrect: true
85 |
86 | ArgumentListWrapping:
87 | active: true
88 | maxLineLength: 500
89 | ImportOrdering:
90 | active: true
91 | Indentation:
92 | active: true
93 | MaximumLineLength:
94 | active: true
95 | maxLineLength: 200
96 | MultiLineIfElse:
97 | active: true
98 | NoBlankLineBeforeRbrace:
99 | active: true
100 | NoConsecutiveBlankLines:
101 | active: true
102 | NoWildcardImports:
103 | active: true
104 | ParameterListWrapping:
105 | active: true
106 | maxLineLength: 500
107 | SpacingAroundKeyword:
108 | active: true
109 | SpacingBetweenDeclarationsWithAnnotations:
110 | active: true
111 | TrailingCommaOnCallSite:
112 | active: true
113 | TrailingCommaOnDeclarationSite:
114 | active: true
115 | Wrapping:
116 | active: true
117 |
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id(libs.plugins.android.application.get().pluginId)
3 | id(libs.plugins.kotlin.android.core.get().pluginId)
4 | id(libs.plugins.gms.oss.licenses.plugin.get().pluginId)
5 | alias(libs.plugins.ksp)
6 | alias(libs.plugins.dagger.hilt.android.core)
7 | }
8 |
9 | android {
10 | compileSdk = 35
11 |
12 | defaultConfig {
13 | applicationId = "net.twinte.android"
14 | minSdk = 24
15 | targetSdk = 35
16 | versionCode = 26
17 | versionName = "4.0.1"
18 |
19 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
20 | }
21 |
22 | buildFeatures {
23 | viewBinding = true
24 | }
25 |
26 | buildTypes {
27 | getByName("release") {
28 | isMinifyEnabled = false
29 | proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
30 | }
31 | }
32 | compileOptions {
33 | sourceCompatibility = JavaVersion.VERSION_17
34 | targetCompatibility = JavaVersion.VERSION_17
35 | }
36 | kotlinOptions {
37 | jvmTarget = "17"
38 | }
39 | namespace = "net.twinte.android"
40 | }
41 |
42 | dependencies {
43 | implementation(fileTree("dir" to "libs", "include" to listOf("*.jar")))
44 | implementation(libs.kotlin.stdlib)
45 | implementation(libs.kotlinx.coroutines.android)
46 | implementation(libs.androidx.core.ktx)
47 | implementation(libs.androidx.appcompat)
48 | implementation(libs.androidx.work.runtime.ktx)
49 | implementation(libs.android.material)
50 | implementation(libs.androidx.constraintlayout)
51 | implementation(libs.androidx.navigation.fragment.ktx)
52 | implementation(libs.androidx.navigation.ui.ktx)
53 | implementation(libs.androidx.preference.ktx)
54 | implementation(libs.androidx.webkit)
55 | implementation(libs.gms.play.services.auth)
56 | implementation(libs.squareup.okhttp3)
57 | implementation(libs.gms.play.services.oss.licenses)
58 | implementation(libs.gson)
59 | testImplementation(libs.junit.core)
60 | androidTestImplementation(libs.androidx.test.ext.junit)
61 | androidTestImplementation(libs.androidx.test.espresso.core)
62 |
63 | // gRPC, Connect
64 | implementation(libs.androidx.recyclerview)
65 | implementation(libs.androidx.lifecycle.runtime.ktx)
66 | implementation(libs.connect.kotlin.okhttp)
67 | // JavaLite specific dependencies
68 | implementation(libs.connect.kotlin.google.javalite.ext)
69 | implementation(libs.protobuf.javalite)
70 |
71 | // Hilt
72 | implementation(libs.hilt.android.core)
73 | ksp(libs.hilt.android.compiler)
74 | implementation(libs.hilt.work)
75 |
76 | implementation(libs.androidx.lifecycle.viewmodel.ktx)
77 |
78 | // Mocking interfaces for testing
79 | testImplementation(libs.mockk)
80 |
81 | // Running test with suspend functions
82 | testImplementation(libs.kotlinx.coroutines.test)
83 | }
84 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/preferences.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
7 |
8 |
15 |
23 |
24 |
25 |
26 |
30 |
33 |
34 |
38 |
41 |
42 |
43 |
44 |
47 |
52 |
53 |
57 |
60 |
61 |
62 |
67 |
70 |
71 |
72 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/model/Timetable.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.model
2 |
3 | data class Timetable(
4 | val date: String,
5 | val module: CurrentModule?,
6 | val events: Array,
7 | val courses: Array,
8 | ) {
9 | data class CurrentModule(
10 | val year: Int,
11 | val module: Module,
12 | )
13 |
14 | data class Event(
15 | val date: String,
16 | val eventType: EventType,
17 | val description: String,
18 | val changeTo: Day?,
19 | )
20 |
21 | data class Course(
22 | val id: String,
23 | val schedules: Array?,
24 | val methods: Array?,
25 | val name: String?,
26 | val instructor: String?,
27 | val year: Int?,
28 | val course: BaseCourse?,
29 | ) {
30 | data class Schedule(
31 | val module: Module,
32 | val day: Day,
33 | val period: Int,
34 | val room: String,
35 | )
36 |
37 | data class BaseCourse(
38 | val schedules: Array,
39 | val methods: Array,
40 | val name: String,
41 | val instructor: String,
42 | val year: Int,
43 | ) {
44 | override fun equals(other: Any?): Boolean {
45 | if (this === other) return true
46 | if (javaClass != other?.javaClass) return false
47 |
48 | other as BaseCourse
49 |
50 | if (year != other.year) return false
51 | if (!schedules.contentEquals(other.schedules)) return false
52 | if (!methods.contentEquals(other.methods)) return false
53 | if (name != other.name) return false
54 | if (instructor != other.instructor) return false
55 |
56 | return true
57 | }
58 |
59 | override fun hashCode(): Int {
60 | var result = year
61 | result = 31 * result + schedules.contentHashCode()
62 | result = 31 * result + methods.contentHashCode()
63 | result = 31 * result + name.hashCode()
64 | result = 31 * result + instructor.hashCode()
65 | return result
66 | }
67 | }
68 | }
69 |
70 | override fun equals(other: Any?): Boolean {
71 | if (this === other) return true
72 | if (javaClass != other?.javaClass) return false
73 |
74 | other as Timetable
75 |
76 | if (date != other.date) return false
77 | if (module != other.module) return false
78 | if (!events.contentEquals(other.events)) return false
79 | if (!courses.contentEquals(other.courses)) return false
80 |
81 | return true
82 | }
83 |
84 | override fun hashCode(): Int {
85 | var result = date.hashCode()
86 | result = 31 * result + (module?.hashCode() ?: 0)
87 | result = 31 * result + events.contentHashCode()
88 | result = 31 * result + courses.contentHashCode()
89 | return result
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/datastore/schedule/SharedPreferencesScheduleDataStore.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.datastore.schedule
2 |
3 | import android.content.Context
4 | import android.os.Build
5 | import androidx.annotation.RequiresApi
6 | import com.connectrpc.Code
7 | import com.connectrpc.ConnectException
8 | import com.connectrpc.getOrThrow
9 | import com.google.gson.Gson
10 | import dagger.hilt.android.qualifiers.ApplicationContext
11 | import kotlinx.coroutines.Dispatchers
12 | import kotlinx.coroutines.withContext
13 | import net.twinte.android.NotLoggedInException
14 | import net.twinte.android.mapping.proto.toTimetable
15 | import net.twinte.android.model.Timetable
16 | import net.twinte.android.network.V4ApiClient
17 | import net.twinte.api.shared.Type.RFC3339FullDate
18 | import net.twinte.api.unified.v1.Service.GetByDateRequest
19 | import java.io.IOException
20 | import java.text.SimpleDateFormat
21 | import java.time.LocalDate
22 | import java.time.ZoneId
23 | import java.time.format.DateTimeFormatter
24 | import java.util.Date
25 | import java.util.Locale
26 | import javax.inject.Inject
27 |
28 | @RequiresApi(Build.VERSION_CODES.O)
29 | class SharedPreferencesScheduleDataStore @Inject constructor(
30 | @ApplicationContext context: Context,
31 | private val api: V4ApiClient,
32 | ) : ScheduleDataStore {
33 | private val pref = context.getSharedPreferences("schedule_cache", Context.MODE_PRIVATE)
34 | private val keyFmt = SimpleDateFormat("yyyy-MM-dd", Locale.JAPAN)
35 |
36 | private val apiFmt = DateTimeFormatter.ISO_LOCAL_DATE // for RPC
37 | private val gson = Gson()
38 |
39 | override suspend fun update(calendar: Array): Unit = withContext(Dispatchers.IO) {
40 | val editor = pref.edit().also { it.clear() }
41 |
42 | for (day in calendar) {
43 | val key = keyFmt.format(day)
44 | val rpcDate = apiFmt.format(day.toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
45 |
46 | try {
47 | val reqDate = LocalDate.parse(rpcDate)
48 | val resp = api.unified.getByDate(
49 | GetByDateRequest.newBuilder()
50 | .setDate(RFC3339FullDate.newBuilder().setValue(rpcDate).build())
51 | .build(),
52 | ).getOrThrow()
53 |
54 | val timetable = resp.toTimetable(reqDate)
55 | editor.putString(key, gson.toJson(timetable))
56 | } catch (e: ConnectException) {
57 | if (e.code == Code.UNAUTHENTICATED) {
58 | throw NotLoggedInException()
59 | }
60 | throw IOException("Connect RPC failed: ${e.code}", e)
61 | } catch (e: IOException) { return@withContext }
62 | }
63 |
64 | editor.commit()
65 | }
66 |
67 | override suspend fun getSchedule(date: Date): Timetable? = withContext(Dispatchers.IO) {
68 | val key = keyFmt.format(date)
69 | if (!pref.contains(key)) update(arrayOf(date))
70 | pref.getString(key, null)?.let { gson.fromJson(it, Timetable::class.java) }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/datastore/schedulenotification/SharedPreferencesScheduleNotificationDataStore.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.datastore.schedulenotification
2 |
3 | import android.app.AlarmManager
4 | import android.app.PendingIntent
5 | import android.content.Context
6 | import android.content.Intent
7 | import android.content.SharedPreferences
8 | import android.util.Log
9 | import androidx.preference.PreferenceManager
10 | import dagger.hilt.android.qualifiers.ApplicationContext
11 | import net.twinte.android.work.ScheduleNotifier
12 | import java.util.Calendar
13 | import javax.inject.Inject
14 |
15 | class SharedPreferencesScheduleNotificationDataStore @Inject constructor(
16 | @ApplicationContext private val context: Context,
17 | ) : ScheduleNotificationDataStore {
18 | private val preferenceChangeListener by lazy {
19 | SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
20 | if (key != "enable_schedule_notification" && key != "notification_timing") return@OnSharedPreferenceChangeListener
21 | schedule()
22 | }
23 | }
24 |
25 | override fun schedule() {
26 | cancelAll()
27 | val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
28 | sharedPreferences
29 | .registerOnSharedPreferenceChangeListener(preferenceChangeListener)
30 | if (!sharedPreferences.getBoolean("enable_schedule_notification", true)) return
31 |
32 | val timing = sharedPreferences.getStringSet("notification_timing", setOf("21", "6"))?.map { it.toInt() }?.sorted()
33 | ?: emptyList()
34 |
35 | timing.forEach { hour ->
36 | val currentDate = Calendar.getInstance()
37 | val notifyDate = Calendar.getInstance().apply {
38 | set(Calendar.HOUR_OF_DAY, hour)
39 | set(Calendar.MINUTE, 0)
40 |
41 | if (before(currentDate)) {
42 | add(Calendar.HOUR_OF_DAY, 24)
43 | }
44 | }
45 |
46 | scheduleAt(notifyDate.timeInMillis, hour)
47 | }
48 | }
49 |
50 | private fun cancelAll() {
51 | val alarmManager = context.getSystemService(AlarmManager::class.java)
52 | for (requestCode in 0..24) {
53 | alarmManager.cancel(alarmIntent(requestCode))
54 | }
55 | Log.d("ScheduleNotifier", "All schedule canceled")
56 | }
57 |
58 | private fun scheduleAt(timeInMillis: Long, requestCode: Int) {
59 | val alarmManager = context.getSystemService(AlarmManager::class.java)
60 | // 指定された時刻付近で1日おきに設定
61 | alarmManager.setRepeating(
62 | AlarmManager.RTC_WAKEUP,
63 | timeInMillis,
64 | 1000 * 60 * 60 * 24,
65 | alarmIntent(requestCode),
66 | )
67 | Log.d("ScheduleNotifier", "Scheduled at $timeInMillis $requestCode")
68 | }
69 |
70 | private fun alarmIntent(requestCode: Int) =
71 | Intent(context, ScheduleNotifier::class.java).let { intent ->
72 | intent.action = "net.twinte.android.action.ScheduleNotifier"
73 | PendingIntent.getBroadcast(
74 | context,
75 | requestCode,
76 | intent,
77 | PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE,
78 | )
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/SettingsActivity.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import android.view.MenuItem
6 | import android.widget.Toast
7 | import androidx.appcompat.app.AppCompatActivity
8 | import androidx.preference.Preference
9 | import androidx.preference.PreferenceFragmentCompat
10 | import com.google.android.gms.oss.licenses.OssLicensesMenuActivity
11 | import dagger.hilt.android.AndroidEntryPoint
12 | import java.util.Timer
13 | import kotlin.concurrent.schedule
14 |
15 | @AndroidEntryPoint
16 | class SettingsActivity : AppCompatActivity() {
17 |
18 | override fun onCreate(savedInstanceState: Bundle?) {
19 | super.onCreate(savedInstanceState)
20 | setContentView(R.layout.activity_settings)
21 | title = "Androidアプリの設定"
22 | supportActionBar?.setDisplayHomeAsUpEnabled(true)
23 | supportFragmentManager
24 | .beginTransaction()
25 | .replace(R.id.preference_wrapper, SettingsFragment())
26 | .commit()
27 | }
28 |
29 | override fun onOptionsItemSelected(item: MenuItem): Boolean {
30 | if (item.itemId == android.R.id.home) {
31 | finish()
32 | return true
33 | }
34 | return false
35 | }
36 |
37 | class SettingsFragment : PreferenceFragmentCompat() {
38 |
39 | private var versionTapTime = 0L
40 | private var versionTapCount = 0
41 | override fun onPreferenceTreeClick(preference: Preference): Boolean {
42 | when (preference.key) {
43 | "license" -> startActivity(Intent(this.context, OssLicensesMenuActivity::class.java))
44 | "version" -> {
45 | if (System.currentTimeMillis() - versionTapTime < 500) {
46 | versionTapCount++
47 | if (versionTapCount >= 7) {
48 | Toast.makeText(
49 | this.context,
50 | "開発者の方々はGithubでお待ちしています!",
51 | Toast.LENGTH_LONG,
52 | ).show()
53 | Timer().schedule(1000) {
54 | findPreference("github")?.isVisible = true
55 | }
56 | } else if (versionTapCount >= 4) {
57 | Toast.makeText(
58 | this.context,
59 | "あと${ 7 - versionTapCount}ステップで開発者になります",
60 | Toast.LENGTH_SHORT,
61 | ).show()
62 | }
63 | }
64 | versionTapTime = System.currentTimeMillis()
65 | }
66 | }
67 | return super.onPreferenceTreeClick(preference)
68 | }
69 |
70 | override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
71 | setPreferencesFromResource(R.xml.preferences, rootKey)
72 | findPreference("github")?.isVisible = false
73 | findPreference("version")?.setSummaryProvider {
74 | this.context?.run {
75 | "version: ${packageManager.getPackageInfo(packageName, 0).versionName}"
76 | }
77 | }
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/MainApplicationModule.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android
2 |
3 | import android.content.Context
4 | import android.webkit.CookieManager
5 | import androidx.work.WorkManager
6 | import dagger.Binds
7 | import dagger.Module
8 | import dagger.Provides
9 | import dagger.hilt.InstallIn
10 | import dagger.hilt.android.qualifiers.ApplicationContext
11 | import dagger.hilt.components.SingletonComponent
12 | import net.twinte.android.datastore.resetcookiesforsamesite.ResetCookiesForSameSiteDataStore
13 | import net.twinte.android.datastore.resetcookiesforsamesite.ResetCookiesForSameSiteDataStoreImpl
14 | import net.twinte.android.datastore.schedule.ScheduleDataStore
15 | import net.twinte.android.datastore.schedule.SharedPreferencesScheduleDataStore
16 | import net.twinte.android.datastore.schedulenotification.ScheduleNotificationDataStore
17 | import net.twinte.android.datastore.schedulenotification.SharedPreferencesScheduleNotificationDataStore
18 | import net.twinte.android.datastore.user.TwinteBackendUserDataStore
19 | import net.twinte.android.datastore.user.UserDataStore
20 | import net.twinte.android.network.TwinteBackendHttpClient
21 | import net.twinte.android.network.TwinteBackendHttpClientImpl
22 | import net.twinte.android.network.V4ApiClient
23 | import net.twinte.android.network.V4ApiClientImpl
24 | import net.twinte.android.network.serversettings.ProductionServerSettings
25 | import net.twinte.android.network.serversettings.ServerSettings
26 |
27 | @Module
28 | @InstallIn(SingletonComponent::class)
29 | interface MainApplicationModule {
30 | @Binds
31 | fun bindScheduleDataStore(
32 | scheduleDataStore: SharedPreferencesScheduleDataStore,
33 | ): ScheduleDataStore
34 |
35 | @Binds
36 | fun bindUserDataStore(
37 | userDataStore: TwinteBackendUserDataStore,
38 | ): UserDataStore
39 |
40 | @Binds
41 | fun bindScheduleNotificationDataStore(
42 | scheduleNotificationDataStore: SharedPreferencesScheduleNotificationDataStore,
43 | ): ScheduleNotificationDataStore
44 |
45 | @Binds
46 | fun bindResetCookiesForSameSiteDataStore(
47 | resetCookiesForSameSiteDataStoreImpl: ResetCookiesForSameSiteDataStoreImpl,
48 | ): ResetCookiesForSameSiteDataStore
49 |
50 | companion object {
51 | // TODO: リリース版でのみ ProductionServerSettings を inject するように変更する(マルチモジュール化が必要)
52 | @Provides
53 | fun provideServerSettings(): ServerSettings = ProductionServerSettings()
54 |
55 | @Provides
56 | fun provideTwinteBackendHttpClient(
57 | serverSettings: ServerSettings,
58 | cookieManager: CookieManager,
59 | ): TwinteBackendHttpClient = TwinteBackendHttpClientImpl(
60 | serverSettings.twinteBackendApiEndpointScheme,
61 | serverSettings.twinteBackendApiEndpointHost,
62 | cookieManager,
63 | )
64 |
65 | @Provides
66 | fun provideV4ApiClient(
67 | serverSettings: ServerSettings,
68 | cookieManager: CookieManager,
69 | ): V4ApiClient = V4ApiClientImpl(
70 | serverSettings,
71 | cookieManager,
72 | )
73 |
74 | @Provides
75 | fun provideCookieManager(): CookieManager = CookieManager.getInstance().apply {
76 | setAcceptCookie(true)
77 | }
78 |
79 | @Provides
80 | fun provideWorkManager(
81 | @ApplicationContext context: Context,
82 | ): WorkManager = WorkManager.getInstance(context)
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/widget_large.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
23 |
24 |
31 |
32 |
40 |
41 |
50 |
51 |
52 |
58 |
59 |
64 |
65 |
71 |
72 |
79 |
80 |
86 |
87 |
95 |
96 |
97 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | xmlns:android
18 |
19 | ^$
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 | xmlns:.*
29 |
30 | ^$
31 |
32 |
33 | BY_NAME
34 |
35 |
36 |
37 |
38 |
39 |
40 | .*:id
41 |
42 | http://schemas.android.com/apk/res/android
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 | .*:name
52 |
53 | http://schemas.android.com/apk/res/android
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 | name
63 |
64 | ^$
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 | style
74 |
75 | ^$
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 | .*
85 |
86 | ^$
87 |
88 |
89 | BY_NAME
90 |
91 |
92 |
93 |
94 |
95 |
96 | .*
97 |
98 | http://schemas.android.com/apk/res/android
99 |
100 |
101 | ANDROID_ATTRIBUTE_ORDER
102 |
103 |
104 |
105 |
106 |
107 |
108 | .*
109 |
110 | .*
111 |
112 |
113 | BY_NAME
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/widget_medium.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
23 |
24 |
31 |
32 |
40 |
41 |
50 |
51 |
52 |
58 |
59 |
64 |
65 |
71 |
72 |
79 |
80 |
86 |
87 |
92 |
93 |
100 |
101 |
102 |
103 |
104 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | connect-kotlin-okhttp = "0.7.3"
3 | kotlin = "2.1.20"
4 | detekt = "1.23.5"
5 | hilt = "2.56.2"
6 | agp = "8.10.1"
7 | gms-oss-licenses = "0.10.6"
8 | ksp = "2.1.20-2.0.1"
9 | lifecycle-runtime-ktx = "2.9.1"
10 | protobuf-javalite = "4.30.2"
11 | recyclerview = "1.4.0"
12 |
13 | [libraries]
14 | android-tools-build-gradle = { group = "com.android.tools.build", name = "gradle", version.ref = "agp" }
15 | androidx-lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycle-runtime-ktx" }
16 | androidx-recyclerview = { module = "androidx.recyclerview:recyclerview", version.ref = "recyclerview" }
17 | connect-kotlin-google-javalite-ext = { module = "com.connectrpc:connect-kotlin-google-javalite-ext", version.ref = "connect-kotlin-okhttp" }
18 | connect-kotlin-okhttp = { module = "com.connectrpc:connect-kotlin-okhttp", version.ref = "connect-kotlin-okhttp" }
19 | kotlin-gradle-plugin = { group = "org.jetbrains.kotlin", name = "kotlin-gradle-plugin", version.ref = "kotlin" }
20 | gms-oss-licenses-plugin = { group = "com.google.android.gms", name = "oss-licenses-plugin", version.ref = "gms-oss-licenses" }
21 | detekt-formatting = { group = "io.gitlab.arturbosch.detekt", name = "detekt-formatting", version.ref = "detekt" }
22 | kotlin-stdlib = { group = "org.jetbrains.kotlin", name = "kotlin-stdlib", version.ref = "kotlin" }
23 | kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version = "1.10.2" }
24 | androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version = "1.16.0" }
25 | androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version = "1.7.1" }
26 | androidx-work-runtime-ktx = { group = "androidx.work", name = "work-runtime-ktx", version = "2.10.2" }
27 | android-material = { group = "com.google.android.material", name = "material", version = "1.12.0" }
28 | androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version = "2.2.1" }
29 | androidx-navigation-fragment-ktx = { group = "androidx.navigation", name = "navigation-fragment-ktx", version = "2.9.1" }
30 | androidx-navigation-ui-ktx = { group = "androidx.navigation", name = "navigation-ui-ktx", version = "2.9.1" }
31 | androidx-preference-ktx = { group = "androidx.preference", name = "preference-ktx", version = "1.2.1" }
32 | androidx-webkit = { group = "androidx.webkit", name = "webkit", version = "1.14.0" }
33 | gms-play-services-auth = { group = "com.google.android.gms", name = "play-services-auth", version = "21.3.0" }
34 | protobuf-javalite = { module = "com.google.protobuf:protobuf-javalite", version.ref = "protobuf-javalite" }
35 | squareup-okhttp3 = { group = "com.squareup.okhttp3", name = "okhttp", version = "5.0.0-alpha.13" }
36 | gms-play-services-oss-licenses = { group = "com.google.android.gms", name = "play-services-oss-licenses", version = "17.1.0" }
37 | gson = { group = "com.google.code.gson", name = "gson", version = "2.11.0" }
38 |
39 | junit-core = { group = "junit", name = "junit", version = "4.13.2" }
40 | androidx-test-ext-junit = { group = "androidx.test.ext", name = "junit", version = "1.2.1" }
41 | androidx-test-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version = "3.6.1" }
42 |
43 | hilt-android-core = { group = "com.google.dagger", name = "hilt-android", version.ref = "hilt" }
44 | hilt-android-compiler = { group = "com.google.dagger", name = "hilt-android-compiler", version.ref = "hilt" }
45 | hilt-work = { group = "androidx.hilt", name = "hilt-work", version = "1.2.0" }
46 | androidx-lifecycle-viewmodel-ktx = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-ktx", version = "2.9.1" }
47 | mockk = { group = "io.mockk", name = "mockk", version = "1.13.3" }
48 | kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version = "1.10.2" }
49 |
50 | [plugins]
51 | detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "detekt" }
52 | dagger-hilt-android-core = { id = "com.google.dagger.hilt.android", version.ref = "hilt" }
53 | ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
54 |
55 | android-application = { id = "com.android.application", version.ref = "agp" }
56 | kotlin-android-core = { id = "kotlin-android", version.ref = "kotlin" }
57 | gms-oss-licenses-plugin = { id = "com.google.android.gms.oss-licenses-plugin", version.ref = "gms-oss-licenses" }
58 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/widget/SmallWidgetProvider.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.widget
2 |
3 | import android.app.PendingIntent
4 | import android.appwidget.AppWidgetManager
5 | import android.appwidget.AppWidgetProvider
6 | import android.content.Context
7 | import android.content.Intent
8 | import android.util.Log
9 | import android.widget.RemoteViews
10 | import dagger.hilt.android.AndroidEntryPoint
11 | import kotlinx.coroutines.runBlocking
12 | import net.twinte.android.MainActivity
13 | import net.twinte.android.NotLoggedInException
14 | import net.twinte.android.R
15 | import net.twinte.android.TWINTE_DEBUG
16 | import net.twinte.android.datastore.schedule.ScheduleDataStore
17 | import java.text.SimpleDateFormat
18 | import java.util.Calendar
19 | import java.util.Locale
20 | import javax.inject.Inject
21 |
22 | /**
23 | * Smallウィジットの管理を担う
24 | */
25 | @AndroidEntryPoint
26 | class SmallWidgetProvider @Inject constructor() : AppWidgetProvider() {
27 | @Inject
28 | lateinit var scheduleDataStore: ScheduleDataStore
29 |
30 | /**
31 | * 設置されたSmallウィジットの数が 0 -> 1 になると呼び出される
32 | */
33 | override fun onEnabled(context: Context) {
34 | WidgetUpdater.schedule(context, this::class.java)
35 | }
36 |
37 | /**
38 | * Smallウィジットが全て無くなると呼び出される
39 | */
40 | override fun onDisabled(context: Context) {
41 | WidgetUpdater.cancel(context, this::class.java)
42 | }
43 |
44 | /**
45 | * ウィジットの更新依頼が来たら呼び出される
46 | */
47 | override fun onUpdate(
48 | context: Context,
49 | appWidgetManager: AppWidgetManager,
50 | appWidgetIds: IntArray,
51 | ) = runBlocking {
52 | Log.d("SmallWidgetProvider", "OnUpdate received")
53 | val (current, period) = WidgetUpdater.getShouldShowCurrentDate()
54 |
55 | try {
56 | val schedule = scheduleDataStore.getSchedule(current.time) ?: return@runBlocking
57 |
58 | appWidgetIds.forEach { appWidgetId ->
59 | val views = RemoteViews(
60 | context.packageName,
61 | R.layout.widget_small,
62 | )
63 | views.setTextViewText(R.id.date_textView, schedule.dateLabel(current))
64 | schedule.eventLabel().let { (label, attention) ->
65 | views.setTextViewText(R.id.event_textView, label)
66 | views.setTextColor(
67 | R.id.event_textView,
68 | context.getColor(if (attention) R.color.widget_text_danger else R.color.widget_text_main),
69 | )
70 | }
71 | val nextCourse = schedule.nextCourseViewModel(period)
72 | views.applyCourseItem(context, nextCourse)
73 |
74 | // タップした授業の詳細画面を表示するIntentを作成
75 | views.setOnClickPendingIntent(
76 | R.id.next_course_wrapper,
77 | PendingIntent.getActivity(
78 | context,
79 | 0,
80 | Intent(context, MainActivity::class.java).apply {
81 | flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
82 | nextCourse?.id?.let {
83 | putExtra("REGISTERED_COURSE_ID", it)
84 | }
85 | },
86 | PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
87 | ),
88 | )
89 |
90 | if (TWINTE_DEBUG) {
91 | views.setTextViewText(
92 | R.id.debug_textView,
93 | "last update: " + SimpleDateFormat(
94 | "MM/dd HH:mm:ss",
95 | Locale.JAPAN,
96 | ).format(Calendar.getInstance().time),
97 | )
98 | }
99 |
100 | appWidgetManager.updateAppWidget(appWidgetId, views)
101 | }
102 | } catch (e: NotLoggedInException) {
103 | appWidgetIds.forEach { appWidgetId ->
104 | appWidgetManager.updateAppWidget(appWidgetId, errorView(context, appWidgetId, "ログインしてください"))
105 | }
106 | } catch (e: Throwable) {
107 | appWidgetIds.forEach { appWidgetId ->
108 | appWidgetManager.updateAppWidget(
109 | appWidgetId,
110 | errorView(context, appWidgetId, "エラーが発生しました", e.stackTraceToString()),
111 | )
112 | }
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
10 |
12 |
14 |
16 |
18 |
20 |
22 |
24 |
26 |
28 |
30 |
32 |
34 |
36 |
38 |
40 |
42 |
44 |
46 |
48 |
50 |
52 |
54 |
56 |
58 |
60 |
62 |
64 |
66 |
68 |
70 |
72 |
74 |
75 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
16 |
17 |
18 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
32 |
33 |
34 |
35 |
39 |
40 |
41 |
42 |
45 |
46 |
47 |
51 |
52 |
53 |
54 |
57 |
58 |
59 |
63 |
64 |
65 |
66 |
69 |
70 |
71 |
72 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
86 |
87 |
92 |
93 |
94 |
95 |
96 |
97 |
100 |
101 |
102 |
103 |
104 |
105 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
120 |
123 |
124 |
125 |
126 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/work/UpdateScheduleWorker.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.work
2 |
3 | import android.Manifest
4 | import android.app.PendingIntent
5 | import android.content.Context
6 | import android.content.Intent
7 | import android.content.pm.PackageManager
8 | import android.util.Log
9 | import androidx.core.app.ActivityCompat
10 | import androidx.core.app.NotificationCompat
11 | import androidx.core.app.NotificationManagerCompat
12 | import androidx.hilt.work.HiltWorker
13 | import androidx.work.BackoffPolicy
14 | import androidx.work.Constraints
15 | import androidx.work.CoroutineWorker
16 | import androidx.work.ExistingWorkPolicy
17 | import androidx.work.NetworkType
18 | import androidx.work.OneTimeWorkRequestBuilder
19 | import androidx.work.WorkManager
20 | import androidx.work.WorkRequest.Companion.MIN_BACKOFF_MILLIS
21 | import androidx.work.WorkerParameters
22 | import dagger.assisted.Assisted
23 | import dagger.assisted.AssistedInject
24 | import net.twinte.android.MainActivity
25 | import net.twinte.android.R
26 | import net.twinte.android.TWINTE_DEBUG
27 | import net.twinte.android.datastore.schedule.ScheduleDataStore
28 | import java.text.SimpleDateFormat
29 | import java.util.Calendar
30 | import java.util.concurrent.TimeUnit
31 | import javax.inject.Inject
32 |
33 | /**
34 | * 一日一回、APIサーバーからウィジットに必要なデータを取得するJobの管理を行う
35 | */
36 | @HiltWorker
37 | class UpdateScheduleWorker @AssistedInject constructor(
38 | @Assisted private val appContext: Context,
39 | @Assisted workerParams: WorkerParameters,
40 | ) : CoroutineWorker(appContext, workerParams) {
41 |
42 | @Inject
43 | lateinit var scheduleDataStore: ScheduleDataStore
44 |
45 | @Inject
46 | lateinit var workManager: WorkManager
47 |
48 | companion object {
49 | private const val TAG = "UPDATE_SCHEDULE"
50 | fun scheduleNextUpdate(workManager: WorkManager) {
51 | val currentDate = Calendar.getInstance()
52 |
53 | // Set Execution around 18:00 ~ 18:30
54 | val dueDate = Calendar.getInstance().apply {
55 | set(Calendar.HOUR_OF_DAY, 18)
56 | set(Calendar.MINUTE, (Math.random() * 30).toInt())
57 | set(Calendar.SECOND, (Math.random() * 59).toInt())
58 | }
59 |
60 | if (dueDate.before(currentDate)) {
61 | dueDate.add(Calendar.HOUR_OF_DAY, 24)
62 | }
63 | val timeDiff = dueDate.timeInMillis - currentDate.timeInMillis
64 |
65 | val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
66 | val updateScheduleWorkRequest = OneTimeWorkRequestBuilder()
67 | .setConstraints(constraints)
68 | .setInitialDelay(timeDiff, TimeUnit.MILLISECONDS)
69 | .setBackoffCriteria(
70 | BackoffPolicy.LINEAR,
71 | MIN_BACKOFF_MILLIS,
72 | TimeUnit.MILLISECONDS,
73 | )
74 | .addTag(TAG).build()
75 | workManager.enqueueUniqueWork(TAG, ExistingWorkPolicy.REPLACE, updateScheduleWorkRequest)
76 | Log.d(
77 | "UpdateScheduleWorker",
78 | "work enqueued at ${SimpleDateFormat.getDateTimeInstance().format(dueDate.time)}",
79 | )
80 | }
81 | }
82 |
83 | override suspend fun doWork() = try {
84 | scheduleDataStore.update()
85 | scheduleNextUpdate(workManager)
86 | Log.d("UpdateScheduleWorker", "work success")
87 | if (TWINTE_DEBUG) {
88 | debugNotification("success")
89 | }
90 | Result.success()
91 | } catch (e: Throwable) {
92 | Log.d("UpdateScheduleWorker", "work failure $e")
93 | if (TWINTE_DEBUG) {
94 | debugNotification("$e")
95 | }
96 | Result.retry()
97 | }
98 |
99 | private fun debugNotification(msg: String) {
100 | val notificationManager = NotificationManagerCompat.from(applicationContext)
101 |
102 | val notification = NotificationCompat.Builder(applicationContext, applicationContext.getString(R.string.schedule_notify_channel_id))
103 | .setSmallIcon(R.drawable.ic_icon)
104 | .setAutoCancel(true)
105 | .setContentIntent(
106 | PendingIntent.getActivity(
107 | applicationContext,
108 | 1,
109 | Intent(applicationContext, MainActivity::class.java),
110 | PendingIntent.FLAG_IMMUTABLE,
111 | ),
112 | ).setContentTitle("[Debug]APIアクセス終了")
113 | .setContentText(msg)
114 | .setChannelId(applicationContext.getString(R.string.schedule_notify_channel_id))
115 | .build()
116 |
117 | // 以下の if 式は自動生成されている
118 | // TODO: API Level 33 以降向けに通知許可を得るための処理を追加する
119 | if (ActivityCompat.checkSelfPermission(
120 | appContext,
121 | Manifest.permission.POST_NOTIFICATIONS,
122 | ) != PackageManager.PERMISSION_GRANTED
123 | ) {
124 | // TODO: Consider calling
125 | // ActivityCompat#requestPermissions
126 | // here to request the missing permissions, and then overriding
127 | // public void onRequestPermissionsResult(int requestCode, String[] permissions,
128 | // int[] grantResults)
129 | // to handle the case where the user grants the permission. See the documentation
130 | // for ActivityCompat#requestPermissions for more details.
131 | return
132 | }
133 | notificationManager.notify(2, notification)
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/work/ScheduleNotifier.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.work
2 |
3 | import android.Manifest
4 | import android.app.PendingIntent
5 | import android.content.BroadcastReceiver
6 | import android.content.Context
7 | import android.content.Intent
8 | import android.content.pm.PackageManager
9 | import android.util.Log
10 | import androidx.core.app.ActivityCompat
11 | import androidx.core.app.NotificationChannelCompat
12 | import androidx.core.app.NotificationCompat
13 | import androidx.core.app.NotificationManagerCompat
14 | import dagger.hilt.android.AndroidEntryPoint
15 | import kotlinx.coroutines.runBlocking
16 | import net.twinte.android.MainActivity
17 | import net.twinte.android.R
18 | import net.twinte.android.SettingsActivity
19 | import net.twinte.android.TWINTE_DEBUG
20 | import net.twinte.android.datastore.schedule.ScheduleDataStore
21 | import net.twinte.android.datastore.schedulenotification.ScheduleNotificationDataStore
22 | import net.twinte.android.model.Day
23 | import java.util.Calendar
24 | import javax.inject.Inject
25 |
26 | /**
27 | * 特殊日程通知を管理する
28 | */
29 | @AndroidEntryPoint
30 | class ScheduleNotifier : BroadcastReceiver() {
31 | @Inject
32 | lateinit var scheduleDataStore: ScheduleDataStore
33 |
34 | override fun onReceive(context: Context, intent: Intent?) = runBlocking {
35 | Log.d("ScheduleNotifier", "Received Broadcast")
36 | try {
37 | val targetDate = Calendar.getInstance().apply {
38 | if (get(Calendar.HOUR_OF_DAY) > 18) add(Calendar.DATE, 1)
39 | }
40 |
41 | val schedule = scheduleDataStore.getSchedule(targetDate.time) ?: return@runBlocking
42 |
43 | val substitute = schedule.events.find { it.changeTo != null }?.changeTo
44 | if (substitute != null) {
45 | createSubstituteDayNotification(context, substitute)
46 | } else if (TWINTE_DEBUG) {
47 | createNotification(context, "[Debug]明日は通常日課です", "${schedule.date} ${schedule.module?.module?.m}")
48 | }
49 | } catch (e: Throwable) {
50 | // TODO エラー処理
51 | Log.d("ScheduleNotifier", "$e")
52 | Unit
53 | }
54 | }
55 |
56 | private fun createSubstituteDayNotification(context: Context, day: Day) {
57 | val label = if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) > 18) "明日" else "今日"
58 | val title = "${label}は${day.d}曜日課です"
59 | val text = "日程はウィジットで確認できます"
60 | createNotification(context, title, text)
61 | }
62 |
63 | private fun createNotification(context: Context, title: String, text: String) = with(context) {
64 | val name = getString(R.string.schedule_notify_channel_name)
65 | val descriptionText = getString(R.string.schedule_notify_channel_description)
66 | val importance = NotificationManagerCompat.IMPORTANCE_DEFAULT
67 | val channel = NotificationChannelCompat.Builder(context.getString(R.string.schedule_notify_channel_id), importance)
68 | .setName(name)
69 | .setDescription(descriptionText)
70 | .build()
71 | // Register the channel with the system
72 | val notificationManager = NotificationManagerCompat.from(context)
73 | notificationManager.createNotificationChannel(channel)
74 |
75 | val notification = NotificationCompat.Builder(context, getString(R.string.schedule_notify_channel_id))
76 | .setSmallIcon(R.drawable.ic_icon)
77 | .setAutoCancel(true)
78 | .setContentIntent(
79 | PendingIntent.getActivity(
80 | context,
81 | 0,
82 | Intent(context, MainActivity::class.java),
83 | PendingIntent.FLAG_IMMUTABLE,
84 | ),
85 | ).addAction(
86 | R.drawable.ic_icon,
87 | "通知設定",
88 | PendingIntent.getActivity(
89 | context,
90 | 0,
91 | Intent(context, SettingsActivity::class.java),
92 | PendingIntent.FLAG_IMMUTABLE,
93 | ),
94 | ).setContentTitle(title)
95 | .setContentText(text)
96 | .setChannelId(context.getString(R.string.schedule_notify_channel_id))
97 | .build()
98 |
99 | // 以下の if 式は自動生成されている
100 | // TODO: API Level 33 以降向けに通知許可を得るための処理を追加する
101 | if (ActivityCompat.checkSelfPermission(
102 | this,
103 | Manifest.permission.POST_NOTIFICATIONS,
104 | ) != PackageManager.PERMISSION_GRANTED
105 | ) {
106 | // TODO: Consider calling
107 | // ActivityCompat#requestPermissions
108 | // here to request the missing permissions, and then overriding
109 | // public void onRequestPermissionsResult(int requestCode, String[] permissions,
110 | // int[] grantResults)
111 | // to handle the case where the user grants the permission. See the documentation
112 | // for ActivityCompat#requestPermissions for more details.
113 | return
114 | }
115 | notificationManager.notify(1, notification)
116 | }
117 |
118 | @AndroidEntryPoint
119 | class OnBootCompleteOrPackageReplaced @Inject constructor() : BroadcastReceiver() {
120 | @Inject
121 | lateinit var scheduleNotificationDataStore: ScheduleNotificationDataStore
122 |
123 | override fun onReceive(context: Context, intent: Intent?) {
124 | Log.d("ScheduleNotifier", "onReceived ${intent?.action}")
125 | scheduleNotificationDataStore.schedule()
126 | }
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/widget/Utils.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.widget
2 |
3 | import android.app.PendingIntent
4 | import android.appwidget.AppWidgetManager
5 | import android.appwidget.AppWidgetProvider
6 | import android.content.Context
7 | import android.content.Intent
8 | import android.view.View
9 | import android.widget.RemoteViews
10 | import net.twinte.android.R
11 | import net.twinte.android.model.Day
12 | import net.twinte.android.model.EventType
13 | import net.twinte.android.model.Timetable
14 | import java.text.SimpleDateFormat
15 | import java.util.Calendar
16 | import java.util.Locale
17 |
18 | /**
19 | * Module名 + 日付
20 | */
21 | fun Timetable.dateLabel(calendar: Calendar): String {
22 | val formatter = SimpleDateFormat("MM/dd (E)", Locale.JAPAN)
23 | val date = formatter.format(calendar.time)
24 | return if (module?.module?.m == null) {
25 | date
26 | } else {
27 | "${module.module.m} $date"
28 | }
29 | }
30 |
31 | /**
32 | * イベントラベル
33 | */
34 | fun Timetable.eventLabel(): Pair {
35 | if (events.isEmpty()) return Pair("通常日課", false)
36 |
37 | val changeTo = events.find { it.eventType == EventType.SubstituteDay }?.changeTo?.d
38 | if (changeTo != null) return Pair("${changeTo}曜日課", true)
39 |
40 | return Pair(events.first().description, false)
41 | }
42 |
43 | /**
44 | * ○コマの授業
45 | */
46 | fun Timetable.courseCountLabel(): String {
47 | val module = module?.module ?: return "0コマの授業"
48 | val f = SimpleDateFormat("yyyy-MM-dd", Locale.JAPAN)
49 | val parsedDate = f.parse(date) ?: return ""
50 | val calendar = Calendar.getInstance().apply { time = parsedDate }
51 |
52 | val count = (1..6).filter { period ->
53 | courses.any { course ->
54 | val schedule = course.schedules ?: course.course!!.schedules
55 | schedule.any {
56 | it.module == module && it.period == period && it.day == Day.entries.toTypedArray()[calendar.get(Calendar.DAY_OF_WEEK) - 1]
57 | }
58 | }
59 | }.size
60 |
61 | return "${count}コマの授業"
62 | }
63 |
64 | /**
65 | * 指定された時限の授業の表示用データを作成
66 | */
67 | fun Timetable.courseViewModel(period: Int): WidgetCourseViewModel? {
68 | val module = module?.module ?: return null
69 | val f = SimpleDateFormat("yyyy-MM-dd", Locale.JAPAN)
70 | val parsedDate = f.parse(date) ?: return null
71 | val calendar = Calendar.getInstance().apply { time = parsedDate }
72 | val day = events.find {
73 | it.changeTo != null
74 | }?.changeTo ?: Day.entries.toTypedArray()[calendar.get(Calendar.DAY_OF_WEEK) - 1]
75 |
76 | val targets = courses.filter { course ->
77 | val schedule = course.schedules ?: course.course!!.schedules
78 | schedule.any { it.module == module && it.period == period && it.day == day }
79 | }
80 |
81 | if (targets.isEmpty()) {
82 | return null
83 | } else if (targets.size > 1) {
84 | return WidgetCourseViewModel(
85 | "${targets.size}件の授業重複あり",
86 | "-",
87 | WidgetUpdater.getPeriodStartTime(period).toString(),
88 | null,
89 | )
90 | }
91 |
92 | val target = targets.first()
93 | val targetName = target.name ?: target.course!!.name
94 |
95 | val schedule = target.schedules ?: target.course!!.schedules
96 | val targetSchedule = schedule.find { it.module == module && it.period == period }
97 |
98 | return WidgetCourseViewModel(
99 | targetName,
100 | targetSchedule!!.room,
101 | WidgetUpdater.getPeriodStartTime(period).toString(),
102 | target.id,
103 | )
104 | }
105 |
106 | /**
107 | * 指定された時限以降で一番早い授業の表示用データを作成
108 | */
109 | fun Timetable.nextCourseViewModel(period: Int): WidgetCourseViewModel? {
110 | var nextCourse: WidgetCourseViewModel? = null
111 | var p = period + 1
112 | while (p <= 6 && nextCourse == null) {
113 | nextCourse = courseViewModel(p)
114 | p++
115 | }
116 | return nextCourse
117 | }
118 |
119 | /**
120 | * 授業表示のコントロールを持つViewに内容を適用する
121 | */
122 | fun RemoteViews.applyCourseItem(context: Context, model: WidgetCourseViewModel?) {
123 | setTextViewText(R.id.course_name_textView, model?.name ?: "授業がありません")
124 | setTextViewText(R.id.course_room_textView, model?.room ?: "-")
125 | setTextViewText(R.id.course_time_textView, model?.time ?: "-")
126 |
127 | val textColor = context.getColor(if (model != null) R.color.widget_text_main else R.color.widget_text_disabled)
128 |
129 | setTextColor(R.id.course_name_textView, textColor)
130 | setTextColor(R.id.course_room_textView, textColor)
131 | setTextColor(R.id.course_time_textView, textColor)
132 |
133 | val iconColor = context.getColor(if (model != null) R.color.colorPrimary else R.color.widget_text_disabled)
134 |
135 | setInt(R.id.course_room_imageView, "setColorFilter", iconColor)
136 | setInt(R.id.course_time_imageView, "setColorFilter", iconColor)
137 | }
138 |
139 | fun AppWidgetProvider.errorView(context: Context, widgetId: Int, title: String, detail: String? = null) =
140 | RemoteViews(
141 | context.packageName,
142 | R.layout.widget_error,
143 | ).apply {
144 | setTextViewText(R.id.error_title_textView, title)
145 | if (detail != null) {
146 | setTextViewText(R.id.error_detail_textView, detail)
147 | } else {
148 | setViewVisibility(R.id.error_detail_textView, View.GONE)
149 | }
150 |
151 | setOnClickPendingIntent(
152 | R.id.error_reload_button,
153 | PendingIntent.getBroadcast(
154 | context,
155 | widgetId,
156 | Intent(context, this@errorView::class.java).apply {
157 | action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
158 | putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(widgetId))
159 | },
160 | PendingIntent.FLAG_IMMUTABLE,
161 | ),
162 | )
163 | }
164 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/donation/v1/DonationServiceClient.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: donation/v1/service.proto
4 | //
5 | package net.twinte.api.donation.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.Idempotency
9 | import com.connectrpc.MethodSpec
10 | import com.connectrpc.ProtocolClientInterface
11 | import com.connectrpc.ResponseMessage
12 | import com.connectrpc.StreamType
13 |
14 | /**
15 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
16 | * - shared.InvalidArgument
17 | * - shared.Unauthenticated
18 | * - shared.Unauthorized
19 | */
20 | public class DonationServiceClient(
21 | private val client: ProtocolClientInterface,
22 | ) : DonationServiceClientInterface {
23 | override suspend fun createOneTimeCheckoutSession(request: Service.CreateOneTimeCheckoutSessionRequest, headers: Headers): ResponseMessage = client.unary(
24 | request,
25 | headers,
26 | MethodSpec(
27 | "donation.v1.DonationService/CreateOneTimeCheckoutSession",
28 | net.twinte.api.donation.v1.Service.CreateOneTimeCheckoutSessionRequest::class,
29 | net.twinte.api.donation.v1.Service.CreateOneTimeCheckoutSessionResponse::class,
30 | StreamType.UNARY,
31 | ),
32 | )
33 |
34 |
35 | override suspend fun createSubscriptionCheckoutSession(request: Service.CreateSubscriptionCheckoutSessionRequest, headers: Headers): ResponseMessage = client.unary(
36 | request,
37 | headers,
38 | MethodSpec(
39 | "donation.v1.DonationService/CreateSubscriptionCheckoutSession",
40 | net.twinte.api.donation.v1.Service.CreateSubscriptionCheckoutSessionRequest::class,
41 | net.twinte.api.donation.v1.Service.CreateSubscriptionCheckoutSessionResponse::class,
42 | StreamType.UNARY,
43 | ),
44 | )
45 |
46 |
47 | override suspend fun getPaymentUser(request: Service.GetPaymentUserRequest, headers: Headers): ResponseMessage = client.unary(
48 | request,
49 | headers,
50 | MethodSpec(
51 | "donation.v1.DonationService/GetPaymentUser",
52 | net.twinte.api.donation.v1.Service.GetPaymentUserRequest::class,
53 | net.twinte.api.donation.v1.Service.GetPaymentUserResponse::class,
54 | StreamType.UNARY,
55 | idempotency = Idempotency.NO_SIDE_EFFECTS,
56 | ),
57 | )
58 |
59 |
60 | override suspend fun updatePaymentUser(request: Service.UpdatePaymentUserRequest, headers: Headers): ResponseMessage = client.unary(
61 | request,
62 | headers,
63 | MethodSpec(
64 | "donation.v1.DonationService/UpdatePaymentUser",
65 | net.twinte.api.donation.v1.Service.UpdatePaymentUserRequest::class,
66 | net.twinte.api.donation.v1.Service.UpdatePaymentUserResponse::class,
67 | StreamType.UNARY,
68 | ),
69 | )
70 |
71 |
72 | override suspend fun listPaymentHistories(request: Service.ListPaymentHistoriesRequest, headers: Headers): ResponseMessage = client.unary(
73 | request,
74 | headers,
75 | MethodSpec(
76 | "donation.v1.DonationService/ListPaymentHistories",
77 | net.twinte.api.donation.v1.Service.ListPaymentHistoriesRequest::class,
78 | net.twinte.api.donation.v1.Service.ListPaymentHistoriesResponse::class,
79 | StreamType.UNARY,
80 | idempotency = Idempotency.NO_SIDE_EFFECTS,
81 | ),
82 | )
83 |
84 |
85 | override suspend fun listSubscriptionPlans(request: Service.ListSubscriptionPlansRequest, headers: Headers): ResponseMessage = client.unary(
86 | request,
87 | headers,
88 | MethodSpec(
89 | "donation.v1.DonationService/ListSubscriptionPlans",
90 | net.twinte.api.donation.v1.Service.ListSubscriptionPlansRequest::class,
91 | net.twinte.api.donation.v1.Service.ListSubscriptionPlansResponse::class,
92 | StreamType.UNARY,
93 | idempotency = Idempotency.NO_SIDE_EFFECTS,
94 | ),
95 | )
96 |
97 |
98 | override suspend fun getActiveSubscription(request: Service.GetActiveSubscriptionRequest, headers: Headers): ResponseMessage = client.unary(
99 | request,
100 | headers,
101 | MethodSpec(
102 | "donation.v1.DonationService/GetActiveSubscription",
103 | net.twinte.api.donation.v1.Service.GetActiveSubscriptionRequest::class,
104 | net.twinte.api.donation.v1.Service.GetActiveSubscriptionResponse::class,
105 | StreamType.UNARY,
106 | idempotency = Idempotency.NO_SIDE_EFFECTS,
107 | ),
108 | )
109 |
110 |
111 | override suspend fun unsubscribe(request: Service.UnsubscribeRequest, headers: Headers): ResponseMessage = client.unary(
112 | request,
113 | headers,
114 | MethodSpec(
115 | "donation.v1.DonationService/Unsubscribe",
116 | net.twinte.api.donation.v1.Service.UnsubscribeRequest::class,
117 | net.twinte.api.donation.v1.Service.UnsubscribeResponse::class,
118 | StreamType.UNARY,
119 | ),
120 | )
121 |
122 |
123 | override suspend fun getTotalAmount(request: Service.GetTotalAmountRequest, headers: Headers): ResponseMessage = client.unary(
124 | request,
125 | headers,
126 | MethodSpec(
127 | "donation.v1.DonationService/GetTotalAmount",
128 | net.twinte.api.donation.v1.Service.GetTotalAmountRequest::class,
129 | net.twinte.api.donation.v1.Service.GetTotalAmountResponse::class,
130 | StreamType.UNARY,
131 | idempotency = Idempotency.NO_SIDE_EFFECTS,
132 | ),
133 | )
134 |
135 |
136 | override suspend fun listContributors(request: Service.ListContributorsRequest, headers: Headers): ResponseMessage = client.unary(
137 | request,
138 | headers,
139 | MethodSpec(
140 | "donation.v1.DonationService/ListContributors",
141 | net.twinte.api.donation.v1.Service.ListContributorsRequest::class,
142 | net.twinte.api.donation.v1.Service.ListContributorsResponse::class,
143 | StreamType.UNARY,
144 | idempotency = Idempotency.NO_SIDE_EFFECTS,
145 | ),
146 | )
147 |
148 | }
149 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/widget/LargeWidgetProvider.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.widget
2 |
3 | import android.app.PendingIntent
4 | import android.appwidget.AppWidgetManager
5 | import android.appwidget.AppWidgetProvider
6 | import android.content.Context
7 | import android.content.Intent
8 | import android.util.Log
9 | import android.widget.RemoteViews
10 | import android.widget.RemoteViewsService
11 | import dagger.hilt.android.AndroidEntryPoint
12 | import kotlinx.coroutines.runBlocking
13 | import net.twinte.android.MainActivity
14 | import net.twinte.android.NotLoggedInException
15 | import net.twinte.android.R
16 | import net.twinte.android.TWINTE_DEBUG
17 | import net.twinte.android.datastore.schedule.ScheduleDataStore
18 | import net.twinte.android.model.Timetable
19 | import java.text.SimpleDateFormat
20 | import java.util.Calendar
21 | import java.util.Locale
22 | import javax.inject.Inject
23 |
24 | /**
25 | * Largeウィジットの管理を担う
26 | */
27 | @AndroidEntryPoint
28 | class LargeWidgetProvider @Inject constructor() : AppWidgetProvider() {
29 | @Inject
30 | lateinit var scheduleDataStore: ScheduleDataStore
31 |
32 | /**
33 | * 設置されたLargeウィジットの数が 0 -> 1 になると呼び出される
34 | */
35 | override fun onEnabled(context: Context) {
36 | WidgetUpdater.schedule(context, this::class.java)
37 | }
38 |
39 | /**
40 | * Largeウィジットが全て無くなると呼び出される
41 | */
42 | override fun onDisabled(context: Context) {
43 | WidgetUpdater.cancel(context, this::class.java)
44 | }
45 |
46 | /**
47 | * ウィジットの更新依頼が来たら呼び出される
48 | */
49 | override fun onUpdate(
50 | context: Context,
51 | appWidgetManager: AppWidgetManager,
52 | appWidgetIds: IntArray,
53 | ) = runBlocking {
54 | Log.d("LargeWidgetProvider", "OnUpdate received")
55 | val (current) = WidgetUpdater.getShouldShowCurrentDate()
56 |
57 | try {
58 | val schedule = scheduleDataStore.getSchedule(current.time) ?: return@runBlocking
59 |
60 | appWidgetIds.forEach { appWidgetId ->
61 | val views = RemoteViews(
62 | context.packageName,
63 | R.layout.widget_large,
64 | )
65 |
66 | views.setTextViewText(R.id.date_textView, schedule.dateLabel(current))
67 | schedule.eventLabel().let { (label, attention) ->
68 | views.setTextViewText(R.id.event_textView, label)
69 | views.setTextColor(
70 | R.id.event_textView,
71 | context.getColor(if (attention) R.color.widget_text_danger else R.color.widget_text_main),
72 | )
73 | }
74 | views.setTextViewText(R.id.course_count_textView, schedule.courseCountLabel())
75 |
76 | if (TWINTE_DEBUG) {
77 | views.setTextViewText(
78 | R.id.debug_textView,
79 | "last update: " + SimpleDateFormat(
80 | "MM/dd HH:mm:ss",
81 | Locale.JAPAN,
82 | ).format(Calendar.getInstance().time),
83 | )
84 | }
85 |
86 | views.setRemoteAdapter(
87 | R.id.course_listView,
88 | Intent(context, LargeWidgetRemoteViewService::class.java).apply {
89 | putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
90 | },
91 | )
92 |
93 | views.setPendingIntentTemplate(
94 | R.id.course_listView,
95 | PendingIntent.getActivity(
96 | context,
97 | 0,
98 | Intent(context, MainActivity::class.java).apply {
99 | flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
100 | },
101 | PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
102 | ),
103 | )
104 |
105 | appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.course_listView)
106 | appWidgetManager.updateAppWidget(appWidgetId, views)
107 | }
108 | } catch (e: NotLoggedInException) {
109 | appWidgetIds.forEach { appWidgetId ->
110 | appWidgetManager.updateAppWidget(appWidgetId, errorView(context, appWidgetId, "ログインしてください"))
111 | }
112 | } catch (e: Throwable) {
113 | appWidgetIds.forEach { appWidgetId ->
114 | appWidgetManager.updateAppWidget(
115 | appWidgetId,
116 | errorView(context, appWidgetId, "エラーが発生しました", e.stackTraceToString()),
117 | )
118 | }
119 | }
120 | }
121 | }
122 |
123 | /**
124 | * ウィジット右側のリストを生成するサービス
125 | */
126 | @AndroidEntryPoint
127 | class LargeWidgetRemoteViewService @Inject constructor() : RemoteViewsService() {
128 | @Inject
129 | lateinit var scheduleDataStore: ScheduleDataStore
130 |
131 | override fun onGetViewFactory(intent: Intent?) = Factory(applicationContext, intent, scheduleDataStore)
132 |
133 | class Factory(
134 | val context: Context,
135 | val intent: Intent?,
136 | private val scheduleDataStore: ScheduleDataStore,
137 | ) : RemoteViewsFactory {
138 | var schedule: Timetable? = null
139 |
140 | override fun onCreate() {}
141 |
142 | override fun onDataSetChanged(): Unit = runBlocking {
143 | Log.d("LargeFactory", "onDataSetChanged")
144 | val (current, _) = WidgetUpdater.getShouldShowCurrentDate()
145 | kotlin.runCatching { scheduleDataStore.getSchedule(current.time) }
146 | .onSuccess { schedule = it }
147 | }
148 |
149 | override fun onDestroy() {}
150 |
151 | override fun getCount() = 6
152 |
153 | override fun getViewAt(position: Int): RemoteViews {
154 | val views = RemoteViews(
155 | context.packageName,
156 | R.layout.widget_period_item,
157 | )
158 |
159 | views.setTextViewText(R.id.period_number_textView, "${position + 1}")
160 | val course = schedule?.courseViewModel(position + 1)
161 | views.applyCourseItem(context, course)
162 |
163 | views.setOnClickFillInIntent(
164 | R.id.period_item_wrapper,
165 | Intent().apply {
166 | course?.id?.let {
167 | putExtra("REGISTERED_COURSE_ID", it)
168 | }
169 | },
170 | )
171 |
172 | return views
173 | }
174 |
175 | override fun getLoadingView() = null
176 |
177 | override fun getViewTypeCount() = 1
178 |
179 | override fun getItemId(position: Int) = position.toLong()
180 | override fun hasStableIds() = false
181 | }
182 | }
183 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/api/timetable/v1/TimetableServiceClient.kt:
--------------------------------------------------------------------------------
1 | // Code generated by connect-kotlin. DO NOT EDIT.
2 | //
3 | // Source: timetable/v1/service.proto
4 | //
5 | package net.twinte.api.timetable.v1
6 |
7 | import com.connectrpc.Headers
8 | import com.connectrpc.Idempotency
9 | import com.connectrpc.MethodSpec
10 | import com.connectrpc.ProtocolClientInterface
11 | import com.connectrpc.ResponseMessage
12 | import com.connectrpc.StreamType
13 |
14 | /**
15 | * The following error codes are not stated explicitly in the each rpc, but may be returned.
16 | * - shared.InvalidArgument
17 | * - shared.Unauthenticated
18 | * - shared.Unauthorized
19 | */
20 | public class TimetableServiceClient(
21 | private val client: ProtocolClientInterface,
22 | ) : TimetableServiceClientInterface {
23 | override suspend fun listCoursesByCodes(request: Service.ListCoursesByCodesRequest, headers: Headers): ResponseMessage = client.unary(
24 | request,
25 | headers,
26 | MethodSpec(
27 | "timetable.v1.TimetableService/ListCoursesByCodes",
28 | net.twinte.api.timetable.v1.Service.ListCoursesByCodesRequest::class,
29 | net.twinte.api.timetable.v1.Service.ListCoursesByCodesResponse::class,
30 | StreamType.UNARY,
31 | idempotency = Idempotency.NO_SIDE_EFFECTS,
32 | ),
33 | )
34 |
35 |
36 | override suspend fun searchCourses(request: Service.SearchCoursesRequest, headers: Headers): ResponseMessage = client.unary(
37 | request,
38 | headers,
39 | MethodSpec(
40 | "timetable.v1.TimetableService/SearchCourses",
41 | net.twinte.api.timetable.v1.Service.SearchCoursesRequest::class,
42 | net.twinte.api.timetable.v1.Service.SearchCoursesResponse::class,
43 | StreamType.UNARY,
44 | idempotency = Idempotency.NO_SIDE_EFFECTS,
45 | ),
46 | )
47 |
48 |
49 | override suspend fun createRegisteredCoursesByCodes(request: Service.CreateRegisteredCoursesByCodesRequest, headers: Headers): ResponseMessage = client.unary(
50 | request,
51 | headers,
52 | MethodSpec(
53 | "timetable.v1.TimetableService/CreateRegisteredCoursesByCodes",
54 | net.twinte.api.timetable.v1.Service.CreateRegisteredCoursesByCodesRequest::class,
55 | net.twinte.api.timetable.v1.Service.CreateRegisteredCoursesByCodesResponse::class,
56 | StreamType.UNARY,
57 | ),
58 | )
59 |
60 |
61 | override suspend fun createRegisteredCourseManually(request: Service.CreateRegisteredCourseManuallyRequest, headers: Headers): ResponseMessage = client.unary(
62 | request,
63 | headers,
64 | MethodSpec(
65 | "timetable.v1.TimetableService/CreateRegisteredCourseManually",
66 | net.twinte.api.timetable.v1.Service.CreateRegisteredCourseManuallyRequest::class,
67 | net.twinte.api.timetable.v1.Service.CreateRegisteredCourseManuallyResponse::class,
68 | StreamType.UNARY,
69 | ),
70 | )
71 |
72 |
73 | override suspend fun listRegisteredCourses(request: Service.ListRegisteredCoursesRequest, headers: Headers): ResponseMessage = client.unary(
74 | request,
75 | headers,
76 | MethodSpec(
77 | "timetable.v1.TimetableService/ListRegisteredCourses",
78 | net.twinte.api.timetable.v1.Service.ListRegisteredCoursesRequest::class,
79 | net.twinte.api.timetable.v1.Service.ListRegisteredCoursesResponse::class,
80 | StreamType.UNARY,
81 | idempotency = Idempotency.NO_SIDE_EFFECTS,
82 | ),
83 | )
84 |
85 |
86 | override suspend fun updateRegisteredCourse(request: Service.UpdateRegisteredCourseRequest, headers: Headers): ResponseMessage = client.unary(
87 | request,
88 | headers,
89 | MethodSpec(
90 | "timetable.v1.TimetableService/UpdateRegisteredCourse",
91 | net.twinte.api.timetable.v1.Service.UpdateRegisteredCourseRequest::class,
92 | net.twinte.api.timetable.v1.Service.UpdateRegisteredCourseResponse::class,
93 | StreamType.UNARY,
94 | ),
95 | )
96 |
97 |
98 | override suspend fun deleteRegisteredCourse(request: Service.DeleteRegisteredCourseRequest, headers: Headers): ResponseMessage = client.unary(
99 | request,
100 | headers,
101 | MethodSpec(
102 | "timetable.v1.TimetableService/DeleteRegisteredCourse",
103 | net.twinte.api.timetable.v1.Service.DeleteRegisteredCourseRequest::class,
104 | net.twinte.api.timetable.v1.Service.DeleteRegisteredCourseResponse::class,
105 | StreamType.UNARY,
106 | ),
107 | )
108 |
109 |
110 | override suspend fun createTag(request: Service.CreateTagRequest, headers: Headers): ResponseMessage = client.unary(
111 | request,
112 | headers,
113 | MethodSpec(
114 | "timetable.v1.TimetableService/CreateTag",
115 | net.twinte.api.timetable.v1.Service.CreateTagRequest::class,
116 | net.twinte.api.timetable.v1.Service.CreateTagResponse::class,
117 | StreamType.UNARY,
118 | ),
119 | )
120 |
121 |
122 | override suspend fun listTags(request: Service.ListTagsRequest, headers: Headers): ResponseMessage = client.unary(
123 | request,
124 | headers,
125 | MethodSpec(
126 | "timetable.v1.TimetableService/ListTags",
127 | net.twinte.api.timetable.v1.Service.ListTagsRequest::class,
128 | net.twinte.api.timetable.v1.Service.ListTagsResponse::class,
129 | StreamType.UNARY,
130 | idempotency = Idempotency.NO_SIDE_EFFECTS,
131 | ),
132 | )
133 |
134 |
135 | override suspend fun updateTag(request: Service.UpdateTagRequest, headers: Headers): ResponseMessage = client.unary(
136 | request,
137 | headers,
138 | MethodSpec(
139 | "timetable.v1.TimetableService/UpdateTag",
140 | net.twinte.api.timetable.v1.Service.UpdateTagRequest::class,
141 | net.twinte.api.timetable.v1.Service.UpdateTagResponse::class,
142 | StreamType.UNARY,
143 | ),
144 | )
145 |
146 |
147 | override suspend fun deleteTag(request: Service.DeleteTagRequest, headers: Headers): ResponseMessage = client.unary(
148 | request,
149 | headers,
150 | MethodSpec(
151 | "timetable.v1.TimetableService/DeleteTag",
152 | net.twinte.api.timetable.v1.Service.DeleteTagRequest::class,
153 | net.twinte.api.timetable.v1.Service.DeleteTagResponse::class,
154 | StreamType.UNARY,
155 | ),
156 | )
157 |
158 |
159 | override suspend fun rearrangeTags(request: Service.RearrangeTagsRequest, headers: Headers): ResponseMessage = client.unary(
160 | request,
161 | headers,
162 | MethodSpec(
163 | "timetable.v1.TimetableService/RearrangeTags",
164 | net.twinte.api.timetable.v1.Service.RearrangeTagsRequest::class,
165 | net.twinte.api.timetable.v1.Service.RearrangeTagsResponse::class,
166 | StreamType.UNARY,
167 | ),
168 | )
169 |
170 | }
171 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/SubWebViewFragment.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android
2 |
3 | import android.annotation.SuppressLint
4 | import android.app.Dialog
5 | import android.graphics.Bitmap
6 | import android.os.Bundle
7 | import android.view.LayoutInflater
8 | import android.view.View
9 | import android.view.ViewGroup
10 | import android.webkit.CookieManager
11 | import android.webkit.JsResult
12 | import android.webkit.WebChromeClient
13 | import android.webkit.WebResourceRequest
14 | import android.webkit.WebView
15 | import android.widget.FrameLayout
16 | import androidx.appcompat.app.AlertDialog
17 | import androidx.fragment.app.FragmentManager
18 | import androidx.webkit.WebViewClientCompat
19 | import com.google.android.material.bottomsheet.BottomSheetBehavior
20 | import com.google.android.material.bottomsheet.BottomSheetDialog
21 | import com.google.android.material.bottomsheet.BottomSheetDialogFragment
22 | import dagger.hilt.android.AndroidEntryPoint
23 | import net.twinte.android.databinding.FragmentSubWebviewBinding
24 | import net.twinte.android.network.serversettings.ServerSettings
25 | import javax.inject.Inject
26 |
27 | @AndroidEntryPoint
28 | class SubWebViewFragment : BottomSheetDialogFragment() {
29 | var callback: Callback? = null
30 |
31 | @Inject
32 | lateinit var cookieManager: CookieManager
33 |
34 | @Inject
35 | lateinit var serverSettings: ServerSettings
36 |
37 | private var _binding: FragmentSubWebviewBinding? = null
38 |
39 | // This property is only valid between onCreateView and onDestroyView.
40 | private val binding get() = _binding!!
41 |
42 | @SuppressLint("SetJavaScriptEnabled")
43 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
44 | super.onViewCreated(view, savedInstanceState)
45 |
46 | (dialog as? BottomSheetDialog)?.behavior?.let { behavior ->
47 | behavior.addBottomSheetCallback(
48 | object : BottomSheetBehavior.BottomSheetCallback() {
49 |
50 | override fun onSlide(bottomSheet: View, slideOffset: Float) {}
51 | override fun onStateChanged(bottomSheet: View, newState: Int) {
52 | if (newState == BottomSheetBehavior.STATE_DRAGGING && binding.subWebview.scrollY > 0) {
53 | behavior.state = BottomSheetBehavior.STATE_EXPANDED
54 | }
55 | }
56 | },
57 | )
58 | }
59 | binding.subWebview.apply {
60 | settings.javaScriptEnabled = true
61 | cookieManager.setAcceptThirdPartyCookies(this, true)
62 | webViewClient = object : WebViewClientCompat() {
63 | override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest) =
64 | // Twin:teのアプリケーションページに飛ぶときはダイアログを閉じてメインで表示
65 | if (
66 | request.url.host == serverSettings.twinteBackendApiEndpointHost &&
67 | request.url.path?.startsWith("/api/v4") != true &&
68 | request.url.path?.startsWith("/auth/v4") != true
69 | ) {
70 | callback?.subWebViewCallback(request.url.toString())
71 | dismiss()
72 | true
73 | } else {
74 | false
75 | }
76 |
77 | override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
78 | binding.subWebviewProgressBar.visibility = View.VISIBLE
79 | }
80 |
81 | override fun onPageFinished(view: WebView, url: String) {
82 | view.layoutParams =
83 | FrameLayout.LayoutParams(
84 | FrameLayout.LayoutParams.MATCH_PARENT,
85 | if (view.height < 200.toPx()) 300.toPx() else FrameLayout.LayoutParams.MATCH_PARENT,
86 | )
87 | binding.subWebviewProgressBar.visibility = View.GONE
88 | // Twinsからインポート
89 | if (url.startsWith("https://twins.tsukuba.ac.jp")) {
90 | view.evaluateJavascript(
91 | """
92 | var script = document.createElement('script');
93 | script.src = 'https://scripts.twinte.net/sp.js';
94 | document.head.appendChild(script);
95 | """.trimIndent(),
96 | ) {}
97 | }
98 | }
99 | }
100 | webChromeClient = object : WebChromeClient() {
101 | override fun onJsConfirm(view: WebView, url: String, message: String, result: JsResult): Boolean {
102 | AlertDialog.Builder(context)
103 | .setMessage(message)
104 | .setPositiveButton("OK") { _, _ -> result.confirm() }
105 | .setNegativeButton("Cancel") { _, _ -> result.cancel() }
106 | .show()
107 | return true
108 | }
109 |
110 | override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean {
111 | AlertDialog.Builder(context)
112 | .setMessage(message)
113 | .setPositiveButton("OK") { _, _ -> result.confirm() }
114 | .show()
115 | return true
116 | }
117 | }
118 | loadUrl(arguments?.getString("url", "") ?: "")
119 | }
120 | }
121 |
122 | override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
123 | object : BottomSheetDialog(requireContext(), theme) {
124 | @Deprecated("Deprecated in Java")
125 | override fun onBackPressed() {
126 | if (binding.subWebview.canGoBack()) {
127 | // ダイアログで表示されているページから一つ前のページに戻れる場合、そこに戻る
128 | binding.subWebview.goBack()
129 | } else {
130 | // ダイアログで表示されているページの前にはページが無い場合、ダイアログを閉じる
131 | super.onBackPressed()
132 | }
133 | }
134 | }
135 |
136 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
137 | _binding = FragmentSubWebviewBinding.inflate(inflater, container, false)
138 | return binding.root
139 | }
140 |
141 | override fun onDestroyView() {
142 | super.onDestroyView()
143 | binding.root.removeView(binding.subWebview)
144 | binding.subWebview.destroy()
145 | _binding = null
146 | }
147 |
148 | interface Callback {
149 | fun subWebViewCallback(url: String)
150 | }
151 |
152 | fun Int.toPx() = ((context?.resources?.displayMetrics?.density ?: 1f) * this).toInt()
153 |
154 | companion object {
155 | fun open(url: String, manager: FragmentManager) = SubWebViewFragment().apply {
156 | arguments = Bundle().apply { putString("url", url) }
157 | show(manager, "sub_webview")
158 | }
159 | }
160 | }
161 |
--------------------------------------------------------------------------------
/app/src/main/java/net/twinte/android/widget/MediumWidgetProvider.kt:
--------------------------------------------------------------------------------
1 | package net.twinte.android.widget
2 |
3 | import android.app.PendingIntent
4 | import android.appwidget.AppWidgetManager
5 | import android.appwidget.AppWidgetProvider
6 | import android.content.Context
7 | import android.content.Intent
8 | import android.util.Log
9 | import android.widget.RemoteViews
10 | import android.widget.RemoteViewsService
11 | import dagger.hilt.android.AndroidEntryPoint
12 | import kotlinx.coroutines.runBlocking
13 | import net.twinte.android.MainActivity
14 | import net.twinte.android.NotLoggedInException
15 | import net.twinte.android.R
16 | import net.twinte.android.TWINTE_DEBUG
17 | import net.twinte.android.datastore.schedule.ScheduleDataStore
18 | import net.twinte.android.model.Timetable
19 | import java.text.SimpleDateFormat
20 | import java.util.Calendar
21 | import java.util.Locale
22 | import javax.inject.Inject
23 |
24 | /**
25 | * Mediumウィジットの管理を担う
26 | */
27 | @AndroidEntryPoint
28 | class MediumWidgetProvider @Inject constructor() : AppWidgetProvider() {
29 | @Inject
30 | lateinit var scheduleDataStore: ScheduleDataStore
31 |
32 | /**
33 | * 設置されたMediumウィジットの数が 0 -> 1 になると呼び出される
34 | */
35 | override fun onEnabled(context: Context) {
36 | WidgetUpdater.schedule(context, this::class.java)
37 | }
38 |
39 | /**
40 | * Mediumウィジットが全て無くなると呼び出される
41 | */
42 | override fun onDisabled(context: Context) {
43 | WidgetUpdater.cancel(context, this::class.java)
44 | }
45 |
46 | /**
47 | * ウィジットの更新依頼が来たら呼び出される
48 | */
49 | override fun onUpdate(
50 | context: Context,
51 | appWidgetManager: AppWidgetManager,
52 | appWidgetIds: IntArray,
53 | ) = runBlocking {
54 | Log.d("MediumWidgetProvider", "OnUpdate received")
55 | val (current) = WidgetUpdater.getShouldShowCurrentDate()
56 | try {
57 | val schedule = scheduleDataStore.getSchedule(current.time) ?: return@runBlocking
58 |
59 | appWidgetIds.forEach { appWidgetId ->
60 | val views = RemoteViews(
61 | context.packageName,
62 | R.layout.widget_medium,
63 | )
64 |
65 | views.setTextViewText(R.id.date_textView, schedule.dateLabel(current))
66 | schedule.eventLabel().let { (label, attention) ->
67 | views.setTextViewText(R.id.event_textView, label)
68 | views.setTextColor(
69 | R.id.event_textView,
70 | context.getColor(if (attention) R.color.widget_text_danger else R.color.widget_text_main),
71 | )
72 | }
73 | views.setTextViewText(R.id.course_count_textView, schedule.courseCountLabel())
74 |
75 | if (TWINTE_DEBUG) {
76 | views.setTextViewText(
77 | R.id.debug_textView,
78 | "last update: " + SimpleDateFormat(
79 | "MM/dd HH:mm:ss",
80 | Locale.JAPAN,
81 | ).format(Calendar.getInstance().time),
82 | )
83 | }
84 |
85 | views.setRemoteAdapter(
86 | R.id.course_listView,
87 | Intent(context, MediumWidgetRemoteViewService::class.java).apply {
88 | putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
89 | },
90 | )
91 |
92 | views.setPendingIntentTemplate(
93 | R.id.course_listView,
94 | PendingIntent.getActivity(
95 | context,
96 | 0,
97 | Intent(context, MainActivity::class.java).apply {
98 | flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
99 | },
100 | PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
101 | ),
102 | )
103 |
104 | appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.course_listView)
105 | appWidgetManager.updateAppWidget(appWidgetId, views)
106 | }
107 | } catch (e: NotLoggedInException) {
108 | appWidgetIds.forEach { appWidgetId ->
109 | appWidgetManager.updateAppWidget(appWidgetId, errorView(context, appWidgetId, "ログインしてください"))
110 | }
111 | } catch (e: Throwable) {
112 | appWidgetIds.forEach { appWidgetId ->
113 | appWidgetManager.updateAppWidget(
114 | appWidgetId,
115 | errorView(context, appWidgetId, "エラーが発生しました", e.stackTraceToString()),
116 | )
117 | }
118 | }
119 | }
120 | }
121 |
122 | /**
123 | * ウィジット右側のリストを生成するサービス
124 | */
125 | @AndroidEntryPoint
126 | class MediumWidgetRemoteViewService @Inject constructor() : RemoteViewsService() {
127 | @Inject
128 | lateinit var scheduleDataStore: ScheduleDataStore
129 |
130 | override fun onGetViewFactory(intent: Intent?) = Factory(applicationContext, intent, scheduleDataStore)
131 |
132 | class Factory(
133 | val context: Context,
134 | val intent: Intent?,
135 | val scheduleDataStore: ScheduleDataStore,
136 | ) : RemoteViewsFactory {
137 | var schedule: Timetable? = null
138 |
139 | override fun onCreate() {}
140 |
141 | override fun onDataSetChanged(): Unit = runBlocking {
142 | Log.d("MediumFactory", "onDataSetChanged")
143 | val (current, _) = WidgetUpdater.getShouldShowCurrentDate()
144 | kotlin.runCatching { scheduleDataStore.getSchedule(current.time) }
145 | .onSuccess { schedule = it }
146 | }
147 |
148 | override fun onDestroy() {}
149 |
150 | override fun getCount() = 2
151 |
152 | override fun getViewAt(position: Int): RemoteViews {
153 | val (_, period) = WidgetUpdater.getShouldShowCurrentDate()
154 | val views = RemoteViews(
155 | context.packageName,
156 | R.layout.widget_course_item_with_header,
157 | )
158 |
159 | val course = if (position == 0) schedule?.courseViewModel(period) else schedule?.nextCourseViewModel(period)
160 | val headerLabel = if (position == 0) "現在の授業" else "次の授業"
161 | views.setTextViewText(R.id.course_header_textView, headerLabel)
162 | views.applyCourseItem(context, course)
163 |
164 | views.setOnClickFillInIntent(
165 | R.id.course_item_with_header_wrapper,
166 | Intent().apply {
167 | course?.id?.let {
168 | putExtra("REGISTERED_COURSE_ID", it)
169 | }
170 | },
171 | )
172 |
173 | return views
174 | }
175 |
176 | override fun getLoadingView() = null
177 |
178 | override fun getViewTypeCount() = 1
179 |
180 | override fun getItemId(position: Int) = position.toLong()
181 | override fun hasStableIds() = false
182 | }
183 | }
184 |
--------------------------------------------------------------------------------