1
0
forked from firka/firka

wear: initial commit

based on 549b7e3e11
with some parts removed, and some parts backported
from the latest commit
This commit is contained in:
2025-08-27 17:01:13 +02:00
parent 509d1d2a2e
commit ad90b8baa0
135 changed files with 11771 additions and 0 deletions

4
.gitmodules vendored
View File

@@ -10,3 +10,7 @@
[submodule "firka/lib/l10n"]
path = firka/lib/l10n
url = https://github.com/QwIT-Development/firka-localization
[submodule "firka_wear/vendor/wear_plus"]
path = firka_wear/vendor/wear_plus
url = https://git.firka.app/firka/wear_plus

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 49 KiB

47
firka_wear/.gitignore vendored Normal file
View File

@@ -0,0 +1,47 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.pub-cache/
.pub/
/build/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
coverage

30
firka_wear/.metadata Normal file
View File

@@ -0,0 +1,30 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "d7b523b356d15fb81e7d340bbe52b47f93937323"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: d7b523b356d15fb81e7d340bbe52b47f93937323
base_revision: d7b523b356d15fb81e7d340bbe52b47f93937323
- platform: ios
create_revision: d7b523b356d15fb81e7d340bbe52b47f93937323
base_revision: d7b523b356d15fb81e7d340bbe52b47f93937323
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'

View File

@@ -0,0 +1,28 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/lints.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

14
firka_wear/android/.gitignore vendored Normal file
View File

@@ -0,0 +1,14 @@
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
.cxx/
# Remember to never publicly share your keystore.
# See https://flutter.dev/to/reference-keystore
key.properties
**/*.keystore
**/*.jks

View File

@@ -0,0 +1,883 @@
import org.apache.commons.io.FileUtils
import java.io.FileInputStream
import java.security.MessageDigest
import java.util.Properties
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream
import java.util.zip.ZipOutputStream.DEFLATED
import java.util.zip.ZipOutputStream.STORED
plugins {
id("com.android.application")
id("kotlin-android")
id("org.jetbrains.kotlin.plugin.compose") version "2.2.0"
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
fun loadProperties(file: File): Properties {
val properties = Properties()
FileInputStream(file).use { inputStream ->
properties.load(inputStream)
}
return properties
}
android {
namespace = "app.firka.naplo"
compileSdk = flutter.compileSdkVersion
ndkVersion = "27.0.12077973"
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
buildFeatures {
compose = true
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_17.toString()
}
defaultConfig {
applicationId = "app.firka.naplo"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = 29
targetSdk = 36
versionCode = flutter.versionCode
versionName = flutter.versionName
}
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
val propsFile = File(secretsDir, "keystore.properties")
if (propsFile.exists()) {
val props = loadProperties(propsFile)
val store = File(secretsDir, props["storeFile"].toString())
signingConfigs {
create("release") {
storeFile = store
storePassword = props["storePassword"] as String
keyPassword = props["keyPassword"] as String
keyAlias = props["keyAlias"] as String
}
}
}
buildTypes {
getByName("debug") {
applicationIdSuffix = ".debug"
versionNameSuffix = "-debug"
}
release {
val config = signingConfigs.findByName("release")
if (config != null) {
signingConfig = config
}
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
}
dependencies {
implementation("androidx.wear:wear-ongoing:1.0.0")
implementation("androidx.glance:glance-appwidget:1.1.1")
}
flutter {
source = "../.."
}
tasks.register("transformAndResignDebugApk") {
group = "build"
description = "Transform and resign APK with debug key"
dependsOn("assembleDebug")
doLast {
transformApks(true)
}
}
tasks.register("transformAndResignReleaseApk") {
group = "build"
description = "Transform and resign APK with release key"
dependsOn("assembleRelease")
doLast {
checkReleaseKey()
if (System.getenv("TRANSFORM_APK") != null
&& System.getenv("TRANSFORM_APK") == "true") {
transformApks(false)
}
}
}
tasks.register("transformAndResignReleaseBundle") {
group = "build"
description = "Transform and resign bundle with release key"
dependsOn("bundleRelease")
doLast {
if (System.getenv("TRANSFORM_AAB") != null
&& System.getenv("TRANSFORM_AAB") == "true") {
transformAppBundle()
}
}
}
afterEvaluate {
tasks.findByName("assembleDebug")?.finalizedBy("transformAndResignDebugApk")
tasks.findByName("assembleRelease")?.finalizedBy("transformAndResignReleaseApk")
tasks.findByName("bundleRelease")?.finalizedBy("transformAndResignReleaseBundle")
}
fun checkReleaseKey() {
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
val propsFile = File(secretsDir, "keystore.properties")
if (propsFile.exists()) {
val props = loadProperties(propsFile)
val store = File(secretsDir, props["storeFile"].toString())
println(
"Signing with:\n" +
"\t- store: ${store.name}\n" +
"\t- key: ${props["keyAlias"]}"
)
} else {
throw Exception("Release keystore not found!")
}
}
fun transformApks(debug: Boolean, i : Int = 0) {
try {
_transformApks(debug)
} catch (e: Exception) {
if (i < 5) {
e.printStackTrace()
println("Retrying: ${i + 1}")
transformApks(debug, i + 1)
} else {
throw e
}
}
}
fun _transformApks(debug: Boolean) {
println("Starting APK transformation process...")
val buildDir = project.buildDir
val apkDir = File(buildDir, "outputs/flutter-apk")
val apks = getApks(debug)
var c = 0
apks
.forEach { c++; transformAndSignApk(apkDir, it.nameWithoutExtension, debug) }
println("Transformed: $c apks")
}
fun transformAndSignApk(apkDir: File, name: String, debug: Boolean) {
val originalApk = File(apkDir, "$name.apk")
val transformedApk = File(apkDir, "$name-transformed.apk")
val finalApk = File(apkDir, "$name-resigned.apk")
val finalIdsig = File(apkDir, "$name-resigned.apk.idsig")
if (!originalApk.exists()) {
throw GradleException("Original APK not found at: ${originalApk.absolutePath}")
}
if (transformedApk.exists()) transformedApk.delete()
if (finalApk.exists()) finalApk.delete()
println("Original APK: ${originalApk.absolutePath}")
try {
println("Transforming APK...")
transformApk(originalApk, transformedApk, if (debug) { "6" } else {"Z"})
if (debug) {
println("Signing with debug key...")
signWithDebugKey(transformedApk, finalApk)
} else {
println("Signing with release key...")
signWithReleaseKey(transformedApk, finalApk)
}
if (finalApk.exists()) {
originalApk.delete()
finalIdsig.delete()
finalApk.renameTo(originalApk)
println("APK successfully transformed")
println("Final APK: ${originalApk.absolutePath}")
}
transformedApk.delete()
} catch (e: Exception) {
throw GradleException("Failed to transform and resign APK: ${e.message}", e)
}
}
fun transformApk(input: File, output: File, compressionLevel: String = "Z") {
val tempDir = File(project.buildDir, "tmp/apk-transform")
val cacheDir = File(project.buildDir, "cache")
val optipngCacheDir = File(cacheDir, "optipng")
val assetCompressionDir = File(cacheDir, "assets")
tempDir.deleteRecursively()
tempDir.mkdirs()
if (!optipngCacheDir.exists()) optipngCacheDir.mkdirs()
if (!assetCompressionDir.exists()) assetCompressionDir.mkdirs()
val brotli = findToolInPath("brotli")
?: throw Exception("Brotli not found in path")
val optipng = findToolInPath("optipng")
if (optipng == null || optipng.isEmpty()) {
println("Optipng was not found in PATH, optimizing images will be skipped.")
}
copy {
from(zipTree(input))
into(tempDir)
}
val metaInf = File(tempDir, "META-INF")
val metaInfFiles = metaInf.listFiles()
for (file in metaInfFiles!!) {
if (file.name.endsWith("MF") || file.name.endsWith("SF")
|| file.name.endsWith("RSA")) {
file.delete()
}
}
val arches = File(tempDir, "lib").listFiles()
val compressedLibs = mutableMapOf<String, String>()
for (arch in arches!!) {
val libFlutter = File(arch, "libflutter.so")
if (!libFlutter.exists()) continue
val compressedFlutter = File(arch, "libflutter-br.so")
compressedLibs["libflutter.so"] = libFlutter.sha256()
println("Compressing ${arch.name}/libflutter.so with brotli")
exec {
commandLine(
brotli,
"-$compressionLevel",
libFlutter.absolutePath,
"-o", compressedFlutter.absolutePath
)
}
libFlutter.delete()
val json = groovy.json.JsonBuilder(compressedLibs)
File(arch, "index.so").writeText(json.toString())
}
val topDirL = tempDir.absolutePath.length + 1
val zos = ZipOutputStream(output.outputStream())
val coreCount = Runtime.getRuntime().availableProcessors()
val flutterResources = tempDir.walkTopDown().filter{f -> f.absolutePath.contains("flutter_assets")}
val pngFiles = tempDir.walkTopDown().filter{f -> f.name.endsWith(".png")}
val assetIndex = mutableMapOf<String, String>()
val indexReadWriteLock = ReentrantReadWriteLock()
if (compressionLevel == "Z") {
if (optipng != null) {
val executor = Executors.newFixedThreadPool(coreCount)
val futures = mutableListOf<Future<*>>()
pngFiles.forEach { pngFile ->
val cacheFile = File(optipngCacheDir, pngFile.sha256())
if (cacheFile.exists()) {
cacheFile.copyTo(pngFile, true)
} else {
val future = executor.submit {
exec {
commandLine(
optipng,
"-zm", "9",
"-zw", "32k",
"-o9",
pngFile.absolutePath
)
}
pngFile.copyTo(cacheFile, true)
}
futures.add(future)
}
}
futures.forEach { it.get() }
executor.shutdown()
}
val executor = Executors.newFixedThreadPool(coreCount)
val futures = mutableListOf<Future<*>>()
val blacklist = listOf(
// "AssetManifest.bin",
"AssetManifest.json",
"FontManifest.json",
"isolate_snapshot_data",
"kernel_blob.bin",
"NativeAssetsManifest.json",
"NOTICES.Z",
"vm_snapshot_data",
"fonts",
"shaders"
)
flutterResources.forEach { f ->
val relName = f.absolutePath.substring(topDirL).replace("\\", "/")
if (f.isDirectory) return@forEach
val cacheFileRaw = File(assetCompressionDir, f.sha256()+".r")
val cacheFileGz = File(assetCompressionDir, f.sha256()+".gz")
val cacheFileBr = File(assetCompressionDir, f.sha256()+".br")
if (cacheFileRaw.exists() || cacheFileGz.exists() || cacheFileBr.exists()) {
if (cacheFileRaw.exists()) {
cacheFileRaw.copyTo(f, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "r"
indexReadWriteLock.writeLock().unlock()
} else if (cacheFileGz.exists()) {
cacheFileGz.copyTo(f, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "g"
indexReadWriteLock.writeLock().unlock()
} else {
cacheFileBr.copyTo(f, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "b"
indexReadWriteLock.writeLock().unlock()
}
} else {
val future = executor.submit {
val brTmp = File(f.absolutePath + ".br.tmp")
val gzTmp = File(f.absolutePath + ".gz.tmp")
var blacklisted = false
for (f in blacklist) {
if (relName.contains(f)) {
blacklisted = true
break
}
}
if (!blacklisted) {
println("$relName: Testing with brotli")
exec {
commandLine(
brotli,
"-$compressionLevel",
f.absolutePath,
"-o", brTmp.absolutePath
)
}
println("$relName: Testing with gzip")
ant.invokeMethod(
"gzip", mapOf(
"src" to f.absolutePath,
"destfile" to gzTmp.absolutePath,
)
)
println("$brTmp: ${brTmp.length()}")
println("$gzTmp: ${gzTmp.length()}")
if (f.length() < gzTmp.length() && f.length() < brTmp.length()) {
println("$relName: Raw file wins")
f.copyTo(cacheFileRaw, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "r"
indexReadWriteLock.writeLock().unlock()
} else {
if (brTmp.length() < gzTmp.length()) {
println("$relName: Brotli wins")
f.delete()
brTmp.copyTo(f, true)
brTmp.copyTo(cacheFileBr, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "b"
indexReadWriteLock.writeLock().unlock()
} else {
println("$relName: Gzip wins")
f.delete()
gzTmp.copyTo(f, true)
gzTmp.copyTo(cacheFileGz, true)
indexReadWriteLock.writeLock().lock()
assetIndex[relName] = "g"
indexReadWriteLock.writeLock().unlock()
}
}
brTmp.delete()
gzTmp.delete()
}
}
futures.add(future)
}
}
futures.forEach { it.get() }
executor.shutdown()
}
tempDir.walkTopDown().forEach { f ->
if (f.absolutePath == tempDir.absolutePath) return@forEach
var relName = f.absolutePath.substring(topDirL).replace("\\", "/")
if (f.isDirectory && !relName.endsWith("/")) relName += "/"
if (compressionLevel == "Z") {
if (relName == "assets/flutter_assets/assets/firka.i") return@forEach
}
println(relName)
val compress = !relName.endsWith(".so") && !relName.endsWith(".arsc")
zos.setMethod(if (compress) { DEFLATED } else { STORED })
val entry = ZipEntry(relName)
if (!compress) {
entry.size = f.length()
entry.crc = FileUtils.checksumCRC32(f)
}
zos.putNextEntry(entry)
if (f.isFile) {
zos.write(f.readBytes())
}
zos.closeEntry()
}
if (compressionLevel == "Z") {
zos.setMethod(DEFLATED)
zos.putNextEntry(ZipEntry("assets/flutter_assets/assets/firka.i"))
val indexUncompressed = File(tempDir, "index.json")
indexReadWriteLock.readLock().lock()
val json = groovy.json.JsonBuilder(assetIndex)
indexReadWriteLock.readLock().unlock()
indexUncompressed.writeText(json.toString())
val indexCompressed = File(tempDir, "index.json.br")
exec {
commandLine(
brotli,
"-$compressionLevel",
indexUncompressed.absolutePath,
"-o", indexCompressed.absolutePath
)
}
zos.write(indexCompressed.readBytes())
indexUncompressed.delete()
indexCompressed.delete()
zos.closeEntry()
}
zos.close()
tempDir.deleteRecursively()
println("APK transformed successfully")
}
fun transformAppBundle() {
val buildDir = project.buildDir
val bundle = File(buildDir, "outputs/bundle/release/app-release.aab")
val bundleTmp = File(buildDir, "outputs/bundle/release/tmp.zip")
val apks = getApks(false)
val apkCount = apks.count { it.name.startsWith("app-") && it.name.endsWith("-release.apk") }
if (!bundle.exists()) {
throw Exception("Bundle not found at: $bundle")
}
if (apkCount < 3) {
throw Exception("Excepected 3 apks per abi but only found $apkCount")
}
val aabTempDir = File(project.buildDir, "tmp/aab-transform")
aabTempDir.deleteRecursively()
aabTempDir.mkdirs()
val apksUnzipped = File(project.buildDir, "tmp/apks-unzipped")
apksUnzipped.deleteRecursively()
val arm32TempDir = File(apksUnzipped, "armeabi-v7a")
arm32TempDir.mkdirs()
val arm64TempDir = File(apksUnzipped, "arm64-v8a")
arm64TempDir.mkdirs()
val x86TempDir = File(apksUnzipped, "x86_64")
x86TempDir.mkdirs()
copy {
from(zipTree(bundle))
into(aabTempDir)
}
copy {
from(zipTree(apks.first { it.name.contains("armeabi-v7a") }))
into(arm32TempDir)
}
copy {
from(zipTree(apks.first { it.name.contains("arm64-v8a") }))
into(arm64TempDir)
}
copy {
from(zipTree(apks.first { it.name.contains("x86_64") }))
into(x86TempDir)
}
val libs = File(aabTempDir, "base/lib").listFiles()!!
for (dstLibs in libs) {
println("Copying lib: ${dstLibs.name}")
val srcDir = File(apksUnzipped, dstLibs.name)
if (!srcDir.exists()) {
continue
}
val srcLibs = File(srcDir, "lib/${dstLibs.name}/")
dstLibs.listFiles()!!.forEach { it.delete() }
srcLibs.listFiles()!!.forEach { it.copyTo(File(dstLibs, it.name)) }
}
val zos = ZipOutputStream(bundleTmp.outputStream())
val bundleZip = ZipFile(bundle)
val bundleEntries = bundleZip.entries()
val brotli = findToolInPath("brotli")
?: throw Exception("Brotli not found in path")
val optipng = findToolInPath("optipng")
?: throw Exception("Optipng not found in path")
val indexReadWriteLock = ReentrantReadWriteLock()
val assetIndex = mutableMapOf<String, String>()
while (bundleEntries.hasMoreElements()) {
val entry = bundleEntries.nextElement()
/*
if (entry.name == "base/assets/flutter_assets/assets/firka.i") {
println("Patching: ${entry.name}")
zos.putNextEntry(ZipEntry("assets/flutter_assets/assets/firka.i"))
val indexUncompressed = File(aabTempDir, "index.json")
indexReadWriteLock.readLock().lock()
val json = groovy.json.JsonBuilder(assetIndex)
indexReadWriteLock.readLock().unlock()
indexUncompressed.writeText(json.toString())
val indexCompressed = File(aabTempDir, "index.json.br")
exec {
commandLine(
brotli,
"-Z",
indexUncompressed.absolutePath,
"-o", indexCompressed.absolutePath
)
}
zos.write(indexCompressed.readBytes())
indexUncompressed.delete()
indexCompressed.delete()
zos.closeEntry()
continue
}
if (entry.name.startsWith("base/lib")) {
println("Patching: ${entry.name}")
zos.putNextEntry(ZipEntry(entry.name))
zos.closeEntry()
continue
}
*/
println("Adding: ${entry.name}")
zos.putNextEntry(ZipEntry(entry.name))
if (!entry.isDirectory) {
val data = bundleZip.getInputStream(entry).readAllBytes()
zos.write(data)
}
zos.closeEntry()
}
bundleZip.close()
zos.close()
bundle.delete()
signBundle(bundleTmp, bundle)
bundleTmp.delete()
aabTempDir.deleteRecursively()
println("AAB transformed successfully")
}
fun File.sha256(): String {
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(this.readBytes())
return digest.fold("") { str, it -> str + "%02x".format(it) }
}
fun getApks(debug: Boolean): List<File> {
val buildDir = project.buildDir
val apkDir = File(buildDir, "outputs/flutter-apk")
val apks = apkDir.listFiles()!!
val flavor = if (debug) { "debug" } else { "release" }
return apks
.filter { apk -> apk.name.startsWith("app-") && apk.name.endsWith("-$flavor.apk") }
.toList()
}
fun getDebugKeystorePath(): String {
val userHome = System.getProperty("user.home")
val debugKeystore = File(userHome, ".android/debug.keystore")
if (!debugKeystore.exists()) {
throw GradleException("Debug keystore not found at: ${debugKeystore.absolutePath}")
}
return debugKeystore.absolutePath
}
fun getDefaultAndroidSdkPath(): String? {
val os = System.getProperty("os.name").lowercase()
val userHome = System.getProperty("user.home")
return when {
os.contains("win") ->
"$userHome\\AppData\\Local\\Android\\Sdk"
os.contains("mac") ->
"$userHome/Library/Android/sdk"
os.contains("linux") ->
"$userHome/Android/Sdk"
else -> null
}
}
fun findToolInPath(toolName: String): String? {
val pathEnvironment = System.getenv("PATH")
val pathDirs = pathEnvironment.split(File.pathSeparator)
val executableNames = when {
System.getProperty("os.name").lowercase().contains("win") ->
listOf("$toolName.exe", toolName)
else ->
listOf(toolName)
}
for (pathDir in pathDirs) {
for (execName in executableNames) {
val possibleTool = File(pathDir, execName)
if (possibleTool.exists() && possibleTool.canExecute()) {
return possibleTool.absolutePath
}
}
}
return null
}
fun findToolInSdkPath(toolName: String): String? {
var androidHome : String? = System.getenv("ANDROID_HOME")
?: System.getenv("ANDROID_SDK_ROOT")
if (androidHome == null) androidHome = getDefaultAndroidSdkPath()
if (androidHome != null) {
val buildTools = File(androidHome, "build-tools")
if (buildTools.exists()) {
val latestVersion = buildTools.listFiles()
?.filter { it.isDirectory }
?.filter { it.name != "debian" }
?.maxByOrNull { it.name }
if (latestVersion != null) {
val toolExec = File(latestVersion, toolName)
if (toolExec.exists()) {
return toolExec.absolutePath
}
}
}
}
if (!toolName.contains(".exe")) {
val exeTool = findToolInSdkPath("$toolName.exe")
if (exeTool != null) return exeTool
}
if (!toolName.contains(".sh")) {
val shTool = findToolInSdkPath("$toolName.sh")
if (shTool != null) return shTool
}
if (!toolName.contains(".bat")) {
val batTool = findToolInSdkPath("$toolName.bat")
if (batTool != null) return batTool
}
return null
}
fun signWithDebugKey(input: File, output: File) {
val debugKeystore = getDebugKeystorePath()
val debugKeystorePassword = "android"
val debugKeyAlias = "androiddebugkey"
val debugKeyPassword = "android"
val zipAlign: String = findToolInSdkPath("zipalign")
?: throw Exception("Could not find zipalign in ANDROID_SDK")
val apksigner: String = findToolInSdkPath("apksigner")
?: throw Exception("Could not find zipalign in ANDROID_SDK")
exec {
commandLine(
zipAlign,
"-v", "4",
input.absolutePath,
output.absolutePath
)
}
exec {
commandLine(
apksigner, "sign",
"--ks", debugKeystore,
"--ks-pass", "pass:$debugKeystorePassword",
"--ks-key-alias", debugKeyAlias,
"--key-pass", "pass:$debugKeyPassword",
output.absolutePath
)
}
println("APK signed and aligned successfully")
}
fun signWithReleaseKey(input: File, output: File) {
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
val propsFile = File(secretsDir, "keystore.properties")
if (!propsFile.exists()) {
throw Exception("Release keystore not found!")
}
val props = loadProperties(propsFile)
val releaseKeystore = File(secretsDir, props["storeFile"].toString())
val releaseKeystorePassword = props["storePassword"] as String
val releaseKeyAlias = props["keyAlias"] as String
val releaseKeyPassword = props["keyPassword"] as String
val zipAlign: String = findToolInSdkPath("zipalign")
?: throw Exception("Could not find zipalign either in ANDROID_SDK")
val apksigner: String = findToolInSdkPath("apksigner")
?: throw Exception("Could not find zipalign either in ANDROID_SDK")
exec {
commandLine(
zipAlign,
"-v", "4",
input.absolutePath,
output.absolutePath
)
}
exec {
commandLine(
apksigner, "sign",
"--ks", releaseKeystore,
"--ks-pass", "pass:$releaseKeystorePassword",
"--ks-key-alias", releaseKeyAlias,
"--key-pass", "pass:$releaseKeyPassword",
output.absolutePath
)
}
println("APK signed and aligned successfully")
}
fun signBundle(input: File, output: File) {
val secretsDir = File(projectDir.absolutePath, "../../../secrets/")
val propsFile = File(secretsDir, "keystore.properties")
if (!propsFile.exists()) {
throw Exception("Release keystore not found!")
}
val props = loadProperties(propsFile)
val releaseKeystore = File(secretsDir, props["storeFile"].toString())
val releaseKeystorePassword = props["storePassword"] as String
val releaseKeyAlias = props["keyAlias"] as String
val releaseKeyPassword = props["keyPassword"] as String
// val zipAlign: String = findToolInSdkPath("zipalign")
// ?: throw Exception("Could not find zipalign in ANDROID_SDK")
val jarsigner: String = findToolInPath("jarsigner")
?: throw Exception("Could not find jarsigner in PATH")
/*
exec {
commandLine(
zipAlign,
"-v", "4",
input.absolutePath,
output.absolutePath
)
}
*/
input.copyTo(output, true)
exec {
// -keystore $KEYSTORE -storetype $STORETYPE -storepass $STOREPASS -digestalg SHA1 -sigalg SHA256withRSA application.zip $KEYALIAS
commandLine(
jarsigner,
"-verbose",
"-sigalg", "SHA256withRSA",
"-digestalg", "SHA-256",
"-keystore", releaseKeystore,
"-storepass", releaseKeystorePassword,
output.absolutePath,
releaseKeyAlias
)
}
println("AAB signed and aligned successfully")
}

View File

@@ -0,0 +1 @@
-keep class org.brotli.** { *; }

View File

@@ -0,0 +1,9 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application android:label="Firka Debug"
android:usesCleartextTraffic="true" />
</manifest>

View File

@@ -0,0 +1,56 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:name=".AppMain"
android:icon="@mipmap/launcher_icon">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<meta-data
android:name="com.google.android.wearable.standalone"
android:value="true" />
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT" />
<data android:mimeType="text/plain" />
</intent>
</queries>
</manifest>

View File

@@ -0,0 +1,15 @@
/* Copyright 2018 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.common;
/** POJO enum that mirrors C BrotliSharedDictionaryType. */
public class SharedDictionaryType {
// Disallow instantiation.
private SharedDictionaryType() {}
public static final int RAW = 0;
public static final int SERIALIZED = 1;
}

View File

@@ -0,0 +1,289 @@
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.dec;
/**
* Bit reading helpers.
*/
final class BitReader {
// Possible values: {5, 6}. 5 corresponds to 32-bit build, 6 to 64-bit. This value is used for
// JIT conditional compilation.
private static final int LOG_BITNESS = Utils.getLogBintness();
// Not only Java compiler prunes "if (const false)" code, but JVM as well.
// Code under "if (DEBUG != 0)" have zero performance impact (outside unit tests).
private static final int DEBUG = Utils.isDebugMode();
static final int BITNESS = 1 << LOG_BITNESS;
private static final int BYTENESS = BITNESS / 8;
private static final int CAPACITY = 4096;
// After encountering the end of the input stream, this amount of zero bytes will be appended.
private static final int SLACK = 64;
private static final int BUFFER_SIZE = CAPACITY + SLACK;
// Don't bother to replenish the buffer while this number of bytes is available.
private static final int SAFEGUARD = 36;
private static final int WATERLINE = CAPACITY - SAFEGUARD;
// "Half" refers to "half of native integer type", i.e. on 64-bit machines it is 32-bit type,
// on 32-bit machines it is 16-bit.
private static final int HALF_BITNESS = BITNESS / 2;
private static final int HALF_SIZE = BYTENESS / 2;
private static final int HALVES_CAPACITY = CAPACITY / HALF_SIZE;
private static final int HALF_BUFFER_SIZE = BUFFER_SIZE / HALF_SIZE;
private static final int HALF_WATERLINE = WATERLINE / HALF_SIZE;
private static final int LOG_HALF_SIZE = LOG_BITNESS - 4;
/**
* Fills up the input buffer.
*
* <p> No-op if there are at least 36 bytes present after current position.
*
* <p> After encountering the end of the input stream, 64 additional zero bytes are copied to the
* buffer.
*/
static void readMoreInput(State s) {
if (s.halfOffset > HALF_WATERLINE) {
doReadMoreInput(s);
}
}
static void doReadMoreInput(State s) {
if (s.endOfStreamReached != 0) {
if (halfAvailable(s) >= -2) {
return;
}
throw new BrotliRuntimeException("No more input");
}
final int readOffset = s.halfOffset << LOG_HALF_SIZE;
int bytesInBuffer = CAPACITY - readOffset;
// Move unused bytes to the head of the buffer.
Utils.copyBytesWithin(s.byteBuffer, 0, readOffset, CAPACITY);
s.halfOffset = 0;
while (bytesInBuffer < CAPACITY) {
final int spaceLeft = CAPACITY - bytesInBuffer;
final int len = Utils.readInput(s.input, s.byteBuffer, bytesInBuffer, spaceLeft);
// EOF is -1 in Java, but 0 in C#.
if (len <= 0) {
s.endOfStreamReached = 1;
s.tailBytes = bytesInBuffer;
bytesInBuffer += HALF_SIZE - 1;
break;
}
bytesInBuffer += len;
}
bytesToNibbles(s, bytesInBuffer);
}
static void checkHealth(State s, int endOfStream) {
if (s.endOfStreamReached == 0) {
return;
}
final int byteOffset = (s.halfOffset << LOG_HALF_SIZE) + ((s.bitOffset + 7) >> 3) - BYTENESS;
if (byteOffset > s.tailBytes) {
throw new BrotliRuntimeException("Read after end");
}
if ((endOfStream != 0) && (byteOffset != s.tailBytes)) {
throw new BrotliRuntimeException("Unused bytes after end");
}
}
static void assertAccumulatorHealthy(State s) {
if (s.bitOffset > BITNESS) {
throw new IllegalStateException("Accumulator underloaded: " + s.bitOffset);
}
}
static void fillBitWindow(State s) {
if (DEBUG != 0) {
assertAccumulatorHealthy(s);
}
if (s.bitOffset >= HALF_BITNESS) {
// Same as doFillBitWindow. JVM fails to inline it.
if (BITNESS == 64) {
s.accumulator64 = ((long) s.intBuffer[s.halfOffset++] << HALF_BITNESS)
| (s.accumulator64 >>> HALF_BITNESS);
} else {
s.accumulator32 = ((int) s.shortBuffer[s.halfOffset++] << HALF_BITNESS)
| (s.accumulator32 >>> HALF_BITNESS);
}
s.bitOffset -= HALF_BITNESS;
}
}
static void doFillBitWindow(State s) {
if (DEBUG != 0) {
assertAccumulatorHealthy(s);
}
if (BITNESS == 64) {
s.accumulator64 = ((long) s.intBuffer[s.halfOffset++] << HALF_BITNESS)
| (s.accumulator64 >>> HALF_BITNESS);
} else {
s.accumulator32 = ((int) s.shortBuffer[s.halfOffset++] << HALF_BITNESS)
| (s.accumulator32 >>> HALF_BITNESS);
}
s.bitOffset -= HALF_BITNESS;
}
static int peekBits(State s) {
if (BITNESS == 64) {
return (int) (s.accumulator64 >>> s.bitOffset);
} else {
return s.accumulator32 >>> s.bitOffset;
}
}
/**
* Fetches bits from accumulator.
*
* WARNING: accumulator MUST contain at least the specified amount of bits,
* otherwise BitReader will become broken.
*/
static int readFewBits(State s, int n) {
final int val = peekBits(s) & ((1 << n) - 1);
s.bitOffset += n;
return val;
}
static int readBits(State s, int n) {
if (HALF_BITNESS >= 24) {
return readFewBits(s, n);
} else {
return (n <= 16) ? readFewBits(s, n) : readManyBits(s, n);
}
}
private static int readManyBits(State s, int n) {
final int low = readFewBits(s, 16);
doFillBitWindow(s);
return low | (readFewBits(s, n - 16) << 16);
}
static void initBitReader(State s) {
s.byteBuffer = new byte[BUFFER_SIZE];
if (BITNESS == 64) {
s.accumulator64 = 0;
s.intBuffer = new int[HALF_BUFFER_SIZE];
} else {
s.accumulator32 = 0;
s.shortBuffer = new short[HALF_BUFFER_SIZE];
}
s.bitOffset = BITNESS;
s.halfOffset = HALVES_CAPACITY;
s.endOfStreamReached = 0;
prepare(s);
}
private static void prepare(State s) {
readMoreInput(s);
checkHealth(s, 0);
doFillBitWindow(s);
doFillBitWindow(s);
}
static void reload(State s) {
if (s.bitOffset == BITNESS) {
prepare(s);
}
}
static void jumpToByteBoundary(State s) {
final int padding = (BITNESS - s.bitOffset) & 7;
if (padding != 0) {
final int paddingBits = readFewBits(s, padding);
if (paddingBits != 0) {
throw new BrotliRuntimeException("Corrupted padding bits");
}
}
}
static int halfAvailable(State s) {
int limit = HALVES_CAPACITY;
if (s.endOfStreamReached != 0) {
limit = (s.tailBytes + (HALF_SIZE - 1)) >> LOG_HALF_SIZE;
}
return limit - s.halfOffset;
}
static void copyRawBytes(State s, byte[] data, int offset, int length) {
if ((s.bitOffset & 7) != 0) {
throw new BrotliRuntimeException("Unaligned copyBytes");
}
// Drain accumulator.
while ((s.bitOffset != BITNESS) && (length != 0)) {
data[offset++] = (byte) peekBits(s);
s.bitOffset += 8;
length--;
}
if (length == 0) {
return;
}
// Get data from shadow buffer with "sizeof(int)" granularity.
final int copyNibbles = Math.min(halfAvailable(s), length >> LOG_HALF_SIZE);
if (copyNibbles > 0) {
final int readOffset = s.halfOffset << LOG_HALF_SIZE;
final int delta = copyNibbles << LOG_HALF_SIZE;
System.arraycopy(s.byteBuffer, readOffset, data, offset, delta);
offset += delta;
length -= delta;
s.halfOffset += copyNibbles;
}
if (length == 0) {
return;
}
// Read tail bytes.
if (halfAvailable(s) > 0) {
// length = 1..3
fillBitWindow(s);
while (length != 0) {
data[offset++] = (byte) peekBits(s);
s.bitOffset += 8;
length--;
}
checkHealth(s, 0);
return;
}
// Now it is possible to copy bytes directly.
while (length > 0) {
final int len = Utils.readInput(s.input, data, offset, length);
if (len == -1) {
throw new BrotliRuntimeException("Unexpected end of input");
}
offset += len;
length -= len;
}
}
/**
* Translates bytes to halves (int/short).
*/
static void bytesToNibbles(State s, int byteLen) {
final byte[] byteBuffer = s.byteBuffer;
final int halfLen = byteLen >> LOG_HALF_SIZE;
if (BITNESS == 64) {
final int[] intBuffer = s.intBuffer;
for (int i = 0; i < halfLen; ++i) {
intBuffer[i] = ((byteBuffer[i * 4] & 0xFF))
| ((byteBuffer[(i * 4) + 1] & 0xFF) << 8)
| ((byteBuffer[(i * 4) + 2] & 0xFF) << 16)
| ((byteBuffer[(i * 4) + 3] & 0xFF) << 24);
}
} else {
final short[] shortBuffer = s.shortBuffer;
for (int i = 0; i < halfLen; ++i) {
shortBuffer[i] = (short) ((byteBuffer[i * 2] & 0xFF)
| ((byteBuffer[(i * 2) + 1] & 0xFF) << 8));
}
}
}
}

View File

@@ -0,0 +1,172 @@
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.dec;
import java.io.IOException;
import java.io.InputStream;
/**
* {@link InputStream} decorator that decompresses brotli data.
*
* <p> Not thread-safe.
*/
public class BrotliInputStream extends InputStream {
public static final int DEFAULT_INTERNAL_BUFFER_SIZE = 256;
/**
* Value expected by InputStream contract when stream is over.
*
* In Java it is -1.
* In C# it is 0 (should be patched during transpilation).
*/
private static final int END_OF_STREAM_MARKER = -1;
/**
* Internal buffer used for efficient byte-by-byte reading.
*/
private byte[] buffer;
/**
* Number of decoded but still unused bytes in internal buffer.
*/
private int remainingBufferBytes;
/**
* Next unused byte offset.
*/
private int bufferOffset;
/**
* Decoder state.
*/
private final State state = new State();
/**
* Creates a {@link InputStream} wrapper that decompresses brotli data.
*
* <p> For byte-by-byte reading ({@link #read()}) internal buffer with
* {@link #DEFAULT_INTERNAL_BUFFER_SIZE} size is allocated and used.
*
* <p> Will block the thread until first {@link BitReader#CAPACITY} bytes of data of source
* are available.
*
* @param source underlying data source
* @throws IOException in case of corrupted data or source stream problems
*/
public BrotliInputStream(InputStream source) throws IOException {
this(source, DEFAULT_INTERNAL_BUFFER_SIZE);
}
/**
* Creates a {@link InputStream} wrapper that decompresses brotli data.
*
* <p> For byte-by-byte reading ({@link #read()}) internal buffer of specified size is
* allocated and used.
*
* <p> Will block the thread until first {@link BitReader#CAPACITY} bytes of data of source
* are available.
*
* @param source compressed data source
* @param byteReadBufferSize size of internal buffer used in case of
* byte-by-byte reading
* @throws IOException in case of corrupted data or source stream problems
*/
public BrotliInputStream(InputStream source, int byteReadBufferSize) throws IOException {
if (byteReadBufferSize <= 0) {
throw new IllegalArgumentException("Bad buffer size:" + byteReadBufferSize);
} else if (source == null) {
throw new IllegalArgumentException("source is null");
}
this.buffer = new byte[byteReadBufferSize];
this.remainingBufferBytes = 0;
this.bufferOffset = 0;
try {
Decode.initState(state, source);
} catch (BrotliRuntimeException ex) {
throw new IOException("Brotli decoder initialization failed", ex);
}
}
public void attachDictionaryChunk(byte[] data) {
Decode.attachDictionaryChunk(state, data);
}
public void enableEagerOutput() {
Decode.enableEagerOutput(state);
}
public void enableLargeWindow() {
Decode.enableLargeWindow(state);
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws IOException {
Decode.close(state);
}
/**
* {@inheritDoc}
*/
@Override
public int read() throws IOException {
if (bufferOffset >= remainingBufferBytes) {
remainingBufferBytes = read(buffer, 0, buffer.length);
bufferOffset = 0;
if (remainingBufferBytes == END_OF_STREAM_MARKER) {
// Both Java and C# return the same value for EOF on single-byte read.
return -1;
}
}
return buffer[bufferOffset++] & 0xFF;
}
/**
* {@inheritDoc}
*/
@Override
public int read(byte[] destBuffer, int destOffset, int destLen) throws IOException {
if (destOffset < 0) {
throw new IllegalArgumentException("Bad offset: " + destOffset);
} else if (destLen < 0) {
throw new IllegalArgumentException("Bad length: " + destLen);
} else if (destOffset + destLen > destBuffer.length) {
throw new IllegalArgumentException(
"Buffer overflow: " + (destOffset + destLen) + " > " + destBuffer.length);
} else if (destLen == 0) {
return 0;
}
int copyLen = Math.max(remainingBufferBytes - bufferOffset, 0);
if (copyLen != 0) {
copyLen = Math.min(copyLen, destLen);
System.arraycopy(buffer, bufferOffset, destBuffer, destOffset, copyLen);
bufferOffset += copyLen;
destOffset += copyLen;
destLen -= copyLen;
if (destLen == 0) {
return copyLen;
}
}
try {
state.output = destBuffer;
state.outputOffset = destOffset;
state.outputLength = destLen;
state.outputUsed = 0;
Decode.decompress(state);
copyLen += state.outputUsed;
copyLen = (copyLen > 0) ? copyLen : END_OF_STREAM_MARKER;
return copyLen;
} catch (BrotliRuntimeException ex) {
throw new IOException("Brotli stream decoding failed", ex);
}
// <{[INJECTED CODE]}>
}
}

View File

@@ -0,0 +1,21 @@
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.dec;
/**
* Unchecked exception used internally.
*/
class BrotliRuntimeException extends RuntimeException {
BrotliRuntimeException(String message) {
super(message);
}
BrotliRuntimeException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -0,0 +1,58 @@
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.dec;
/**
* Common context lookup table for all context modes.
*/
final class Context {
static final int[] LOOKUP = new int[2048];
private static final String UTF_MAP = " !! ! \"#$##%#$&'##(#)#+++++++++"
+ "+((&*'##,---,---,-----,-----,-----&#'###.///.///./////./////./////&#'# ";
private static final String UTF_RLE = "A/* ': & : $ \u0081 @";
private static void unpackLookupTable(int[] lookup, String map, String rle) {
// LSB6, MSB6, SIGNED
for (int i = 0; i < 256; ++i) {
lookup[i] = i & 0x3F;
lookup[512 + i] = i >> 2;
lookup[1792 + i] = 2 + (i >> 6);
}
// UTF8
for (int i = 0; i < 128; ++i) {
lookup[1024 + i] = 4 * (map.charAt(i) - 32);
}
for (int i = 0; i < 64; ++i) {
lookup[1152 + i] = i & 1;
lookup[1216 + i] = 2 + (i & 1);
}
int offset = 1280;
for (int k = 0; k < 19; ++k) {
final int value = k & 3;
final int rep = rle.charAt(k) - 32;
for (int i = 0; i < rep; ++i) {
lookup[offset++] = value;
}
}
// SIGNED
for (int i = 0; i < 16; ++i) {
lookup[1792 + i] = 1;
lookup[2032 + i] = 6;
}
lookup[1792] = 0;
lookup[2047] = 7;
for (int i = 0; i < 256; ++i) {
lookup[1536 + i] = lookup[1792 + i] << 3;
}
}
static {
unpackLookupTable(LOOKUP, UTF_MAP, UTF_RLE);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,72 @@
package org.brotli.dec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Decoder {
private static long decodeBytes(InputStream input, OutputStream output, byte[] buffer)
throws IOException {
long totalOut = 0;
int readBytes;
BrotliInputStream in = new BrotliInputStream(input);
in.enableLargeWindow();
try {
while ((readBytes = in.read(buffer)) >= 0) {
output.write(buffer, 0, readBytes);
totalOut += readBytes;
}
} finally {
in.close();
}
return totalOut;
}
private static void decompress(String fromPath, String toPath, byte[] buffer) throws IOException {
long start;
long bytesDecoded;
long end;
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(fromPath);
out = new FileOutputStream(toPath);
start = System.nanoTime();
bytesDecoded = decodeBytes(in, out, buffer);
end = System.nanoTime();
} finally {
if (in != null) {
in.close(); // Hopefully, does not throw exception.
}
if (out != null) {
out.close();
}
}
double timeDelta = (end - start) / 1000000000.0;
if (timeDelta <= 0) {
return;
}
double mbDecoded = bytesDecoded / (1024.0 * 1024.0);
System.out.println(mbDecoded / timeDelta + " MiB/s");
}
public static void main(String... args) throws IOException {
if (args.length != 2 && args.length != 3) {
System.out.println("Usage: decoder <compressed_in> <decompressed_out> [repeat]");
return;
}
int repeat = 1;
if (args.length == 3) {
repeat = Integer.parseInt(args[2]);
}
byte[] buffer = new byte[1024 * 1024];
for (int i = 0; i < repeat; ++i) {
decompress(args[0], args[1], buffer);
}
}
}

View File

@@ -0,0 +1,94 @@
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.dec;
import java.nio.ByteBuffer;
/**
* Collection of static dictionary words.
*
* <p>Dictionary content is loaded from binary resource when {@link #getData()} is executed for the
* first time. Consequently, it saves memory and CPU in case dictionary is not required.
*
* <p>One possible drawback is that multiple threads that need dictionary data may be blocked (only
* once in each classworld). To avoid this, it is enough to call {@link #getData()} proactively.
*/
public final class Dictionary {
static final int MIN_DICTIONARY_WORD_LENGTH = 4;
static final int MAX_DICTIONARY_WORD_LENGTH = 31;
private static ByteBuffer data = ByteBuffer.allocateDirect(0);
static final int[] offsets = new int[32];
static final int[] sizeBits = new int[32];
private static class DataLoader {
static final boolean OK;
static {
boolean ok = true;
try {
Class.forName(Dictionary.class.getPackage().getName() + ".DictionaryData");
} catch (Throwable ex) {
ok = false;
}
OK = ok;
}
}
public static void setData(ByteBuffer newData, int[] newSizeBits) {
if ((Utils.isDirect(newData) == 0) || (Utils.isReadOnly(newData) == 0)) {
throw new BrotliRuntimeException("newData must be a direct read-only byte buffer");
}
// TODO: is that so?
if (newSizeBits.length > MAX_DICTIONARY_WORD_LENGTH) {
throw new BrotliRuntimeException(
"sizeBits length must be at most " + String.valueOf(MAX_DICTIONARY_WORD_LENGTH));
}
for (int i = 0; i < MIN_DICTIONARY_WORD_LENGTH; ++i) {
if (newSizeBits[i] != 0) {
throw new BrotliRuntimeException(
"first " + String.valueOf(MIN_DICTIONARY_WORD_LENGTH) + " must be 0");
}
}
final int[] dictionaryOffsets = Dictionary.offsets;
final int[] dictionarySizeBits = Dictionary.sizeBits;
System.arraycopy(newSizeBits, 0, dictionarySizeBits, 0, newSizeBits.length);
int pos = 0;
final int limit = newData.capacity();
for (int i = 0; i < newSizeBits.length; ++i) {
dictionaryOffsets[i] = pos;
final int bits = dictionarySizeBits[i];
if (bits != 0) {
if (bits >= 31) {
throw new BrotliRuntimeException("newSizeBits values must be less than 31");
}
pos += i << bits;
if (pos <= 0 || pos > limit) {
throw new BrotliRuntimeException("newSizeBits is inconsistent: overflow");
}
}
}
for (int i = newSizeBits.length; i < 32; ++i) {
dictionaryOffsets[i] = pos;
}
if (pos != limit) {
throw new BrotliRuntimeException("newSizeBits is inconsistent: underflow");
}
Dictionary.data = newData;
}
public static ByteBuffer getData() {
if (data.capacity() != 0) {
return data;
}
if (!DataLoader.OK) {
throw new BrotliRuntimeException("brotli dictionary is not set");
}
/* Might have been set when {@link DictionaryData} was loaded.*/
return data;
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,137 @@
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.dec;
/**
* Utilities for building Huffman decoding tables.
*/
final class Huffman {
private static final int MAX_LENGTH = 15;
/**
* Returns reverse(reverse(key, len) + 1, len).
*
* <p> reverse(key, len) is the bit-wise reversal of the len least significant bits of key.
*/
private static int getNextKey(int key, int len) {
int step = 1 << (len - 1);
while ((key & step) != 0) {
step >>= 1;
}
return (key & (step - 1)) + step;
}
/**
* Stores {@code item} in {@code table[0], table[step], table[2 * step] .., table[end]}.
*
* <p> Assumes that end is an integer multiple of step.
*/
private static void replicateValue(int[] table, int offset, int step, int end, int item) {
do {
end -= step;
table[offset + end] = item;
} while (end > 0);
}
/**
* @param count histogram of bit lengths for the remaining symbols,
* @param len code length of the next processed symbol.
* @return table width of the next 2nd level table.
*/
private static int nextTableBitSize(int[] count, int len, int rootBits) {
int left = 1 << (len - rootBits);
while (len < MAX_LENGTH) {
left -= count[len];
if (left <= 0) {
break;
}
len++;
left <<= 1;
}
return len - rootBits;
}
/**
* Builds Huffman lookup table assuming code lengths are in symbol order.
*
* @return number of slots used by resulting Huffman table
*/
static int buildHuffmanTable(int[] tableGroup, int tableIdx, int rootBits, int[] codeLengths,
int codeLengthsSize) {
final int tableOffset = tableGroup[tableIdx];
int key; // Reversed prefix code.
final int[] sorted = new int[codeLengthsSize]; // Symbols sorted by code length.
// TODO(eustas): fill with zeroes?
final int[] count = new int[MAX_LENGTH + 1]; // Number of codes of each length.
final int[] offset = new int[MAX_LENGTH + 1]; // Offsets in sorted table for each length.
int symbol;
// Build histogram of code lengths.
for (symbol = 0; symbol < codeLengthsSize; symbol++) {
count[codeLengths[symbol]]++;
}
// Generate offsets into sorted symbol table by code length.
offset[1] = 0;
for (int len = 1; len < MAX_LENGTH; len++) {
offset[len + 1] = offset[len] + count[len];
}
// Sort symbols by length, by symbol order within each length.
for (symbol = 0; symbol < codeLengthsSize; symbol++) {
if (codeLengths[symbol] != 0) {
sorted[offset[codeLengths[symbol]]++] = symbol;
}
}
int tableBits = rootBits;
int tableSize = 1 << tableBits;
int totalSize = tableSize;
// Special case code with only one value.
if (offset[MAX_LENGTH] == 1) {
for (key = 0; key < totalSize; key++) {
tableGroup[tableOffset + key] = sorted[0];
}
return totalSize;
}
// Fill in root table.
key = 0;
symbol = 0;
for (int len = 1, step = 2; len <= rootBits; len++, step <<= 1) {
for (; count[len] > 0; count[len]--) {
replicateValue(tableGroup, tableOffset + key, step, tableSize,
len << 16 | sorted[symbol++]);
key = getNextKey(key, len);
}
}
// Fill in 2nd level tables and add pointers to root table.
final int mask = totalSize - 1;
int low = -1;
int currentOffset = tableOffset;
for (int len = rootBits + 1, step = 2; len <= MAX_LENGTH; len++, step <<= 1) {
for (; count[len] > 0; count[len]--) {
if ((key & mask) != low) {
currentOffset += tableSize;
tableBits = nextTableBitSize(count, len, rootBits);
tableSize = 1 << tableBits;
totalSize += tableSize;
low = key & mask;
tableGroup[tableOffset + low] =
(tableBits + rootBits) << 16 | (currentOffset - tableOffset - low);
}
replicateValue(tableGroup, currentOffset + (key >> rootBits), step, tableSize,
(len - rootBits) << 16 | sorted[symbol++]);
key = getNextKey(key, len);
}
}
return totalSize;
}
}

View File

@@ -0,0 +1,100 @@
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.dec;
import java.io.InputStream;
final class State {
byte[] ringBuffer;
byte[] contextModes;
byte[] contextMap;
byte[] distContextMap;
byte[] distExtraBits;
byte[] output;
byte[] byteBuffer; // BitReader
short[] shortBuffer; // BitReader
int[] intBuffer; // BitReader
int[] rings;
int[] blockTrees;
int[] literalTreeGroup;
int[] commandTreeGroup;
int[] distanceTreeGroup;
int[] distOffset;
long accumulator64; // BitReader: pre-fetched bits.
int runningState; // Default value is 0 == Decode.UNINITIALIZED
int nextRunningState;
int accumulator32; // BitReader: pre-fetched bits.
int bitOffset; // BitReader: bit-reading position in accumulator.
int halfOffset; // BitReader: offset of next item in intBuffer/shortBuffer.
int tailBytes; // BitReader: number of bytes in unfinished half.
int endOfStreamReached; // BitReader: input stream is finished.
int metaBlockLength;
int inputEnd;
int isUncompressed;
int isMetadata;
int literalBlockLength;
int numLiteralBlockTypes;
int commandBlockLength;
int numCommandBlockTypes;
int distanceBlockLength;
int numDistanceBlockTypes;
int pos;
int maxDistance;
int distRbIdx;
int trivialLiteralContext;
int literalTreeIdx;
int commandTreeIdx;
int j;
int insertLength;
int contextMapSlice;
int distContextMapSlice;
int contextLookupOffset1;
int contextLookupOffset2;
int distanceCode;
int numDirectDistanceCodes;
int distancePostfixBits;
int distance;
int copyLength;
int maxBackwardDistance;
int maxRingBufferSize;
int ringBufferSize;
int expectedTotalSize;
int outputOffset;
int outputLength;
int outputUsed;
int ringBufferBytesWritten;
int ringBufferBytesReady;
int isEager;
int isLargeWindow;
// Compound dictionary
int cdNumChunks;
int cdTotalSize;
int cdBrIndex;
int cdBrOffset;
int cdBrLength;
int cdBrCopied;
byte[][] cdChunks;
int[] cdChunkOffsets;
int cdBlockBits;
byte[] cdBlockMap;
InputStream /* @Nullable */ input; // BitReader
State() {
this.ringBuffer = new byte[0];
this.rings = new int[10];
this.rings[0] = 16;
this.rings[1] = 15;
this.rings[2] = 11;
this.rings[3] = 4;
}
}

View File

@@ -0,0 +1,236 @@
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.dec;
import java.nio.ByteBuffer;
/**
* Transformations on dictionary words.
*
* Transform descriptor is a triplet: {prefix, operator, suffix}.
* "prefix" and "suffix" are short strings inserted before and after transformed dictionary word.
* "operator" is applied to dictionary word itself.
*
* Some operators has "built-in" parameters, i.e. parameter is defined by operator ordinal. Other
* operators have "external" parameters, supplied via additional table encoded in shared dictionary.
*
* Operators:
* - IDENTITY (0): dictionary word is inserted "as is"
* - OMIT_LAST_N (1 - 9): last N octets of dictionary word are not inserted; N == ordinal
* - OMIT_FIRST_M (12-20): first M octets of dictionary word are not inserted; M == ordinal - 11
* - UPPERCASE_FIRST (10): first "scalar" is XOR'ed with number 32
* - UPPERCASE_ALL (11): all "scalars" are XOR'ed with number 32
* - SHIFT_FIRST (21): first "scalar" is shifted by number form parameter table
* - SHIFT_ALL (22): all "scalar" is shifted by number form parameter table
*
* Here "scalar" is a variable length character coding similar to UTF-8 encoding.
* UPPERCASE_XXX / SHIFT_XXX operators were designed to change the case of UTF-8 encoded characters.
* While UPPERCASE_XXX works well only on ASCII charset, SHIFT is much more generic and could be
* used for most (all?) alphabets.
*/
final class Transform {
static final class Transforms {
final int numTransforms;
final int[] triplets;
final byte[] prefixSuffixStorage;
final int[] prefixSuffixHeads;
final short[] params;
Transforms(int numTransforms, int prefixSuffixLen, int prefixSuffixCount) {
this.numTransforms = numTransforms;
this.triplets = new int[numTransforms * 3];
this.params = new short[numTransforms];
this.prefixSuffixStorage = new byte[prefixSuffixLen];
this.prefixSuffixHeads = new int[prefixSuffixCount + 1];
}
}
static final int NUM_RFC_TRANSFORMS = 121;
static final Transforms RFC_TRANSFORMS = new Transforms(NUM_RFC_TRANSFORMS, 167, 50);
private static final int OMIT_FIRST_LAST_LIMIT = 9;
private static final int IDENTITY = 0;
private static final int OMIT_LAST_BASE = IDENTITY + 1 - 1; // there is no OMIT_LAST_0.
private static final int UPPERCASE_FIRST = OMIT_LAST_BASE + OMIT_FIRST_LAST_LIMIT + 1;
private static final int UPPERCASE_ALL = UPPERCASE_FIRST + 1;
private static final int OMIT_FIRST_BASE = UPPERCASE_ALL + 1 - 1; // there is no OMIT_FIRST_0.
private static final int SHIFT_FIRST = OMIT_FIRST_BASE + OMIT_FIRST_LAST_LIMIT + 1;
private static final int SHIFT_ALL = SHIFT_FIRST + 1;
// Bundle of 0-terminated strings.
private static final String PREFIX_SUFFIX_SRC = "# #s #, #e #.# the #.com/#\u00C2\u00A0# of # and"
+ " # in # to #\"#\">#\n#]# for # a # that #. # with #'# from # by #. The # on # as # is #ing"
+ " #\n\t#:#ed #(# at #ly #=\"# of the #. This #,# not #er #al #='#ful #ive #less #est #ize #"
+ "ous #";
private static final String TRANSFORMS_SRC = " !! ! , *! &! \" ! ) * * - ! # ! #!*! "
+ "+ ,$ ! - % . / # 0 1 . \" 2 3!* 4% ! # / 5 6 7 8 0 1 & $ 9 + : "
+ " ; < ' != > ?! 4 @ 4 2 & A *# ( B C& ) % ) !*# *-% A +! *. D! %' & E *6 F "
+ " G% ! *A *% H! D I!+! J!+ K +- *4! A L!*4 M N +6 O!*% +.! K *G P +%( ! G *D +D "
+ " Q +# *K!*G!+D!+# +G +A +4!+% +K!+4!*D!+K!*K";
private static void unpackTransforms(byte[] prefixSuffix,
int[] prefixSuffixHeads, int[] transforms, String prefixSuffixSrc, String transformsSrc) {
final int n = prefixSuffixSrc.length();
int index = 1;
int j = 0;
for (int i = 0; i < n; ++i) {
final char c = prefixSuffixSrc.charAt(i);
if (c == 35) { // == #
prefixSuffixHeads[index++] = j;
} else {
prefixSuffix[j++] = (byte) c;
}
}
for (int i = 0; i < NUM_RFC_TRANSFORMS * 3; ++i) {
transforms[i] = transformsSrc.charAt(i) - 32;
}
}
static {
unpackTransforms(RFC_TRANSFORMS.prefixSuffixStorage, RFC_TRANSFORMS.prefixSuffixHeads,
RFC_TRANSFORMS.triplets, PREFIX_SUFFIX_SRC, TRANSFORMS_SRC);
}
static int transformDictionaryWord(byte[] dst, int dstOffset, ByteBuffer src, int srcOffset,
int len, Transforms transforms, int transformIndex) {
int offset = dstOffset;
final int[] triplets = transforms.triplets;
final byte[] prefixSuffixStorage = transforms.prefixSuffixStorage;
final int[] prefixSuffixHeads = transforms.prefixSuffixHeads;
final int transformOffset = 3 * transformIndex;
final int prefixIdx = triplets[transformOffset];
final int transformType = triplets[transformOffset + 1];
final int suffixIdx = triplets[transformOffset + 2];
int prefix = prefixSuffixHeads[prefixIdx];
final int prefixEnd = prefixSuffixHeads[prefixIdx + 1];
int suffix = prefixSuffixHeads[suffixIdx];
final int suffixEnd = prefixSuffixHeads[suffixIdx + 1];
int omitFirst = transformType - OMIT_FIRST_BASE;
int omitLast = transformType - OMIT_LAST_BASE;
if (omitFirst < 1 || omitFirst > OMIT_FIRST_LAST_LIMIT) {
omitFirst = 0;
}
if (omitLast < 1 || omitLast > OMIT_FIRST_LAST_LIMIT) {
omitLast = 0;
}
// Copy prefix.
while (prefix != prefixEnd) {
dst[offset++] = prefixSuffixStorage[prefix++];
}
// Copy trimmed word.
if (omitFirst > len) {
omitFirst = len;
}
srcOffset += omitFirst;
len -= omitFirst;
len -= omitLast;
int i = len;
while (i > 0) {
dst[offset++] = src.get(srcOffset++);
i--;
}
// Ferment.
if (transformType == UPPERCASE_FIRST || transformType == UPPERCASE_ALL) {
int uppercaseOffset = offset - len;
if (transformType == UPPERCASE_FIRST) {
len = 1;
}
while (len > 0) {
final int c0 = dst[uppercaseOffset] & 0xFF;
if (c0 < 0xC0) {
if (c0 >= 97 && c0 <= 122) { // in [a..z] range
dst[uppercaseOffset] ^= (byte) 32;
}
uppercaseOffset += 1;
len -= 1;
} else if (c0 < 0xE0) {
dst[uppercaseOffset + 1] ^= (byte) 32;
uppercaseOffset += 2;
len -= 2;
} else {
dst[uppercaseOffset + 2] ^= (byte) 5;
uppercaseOffset += 3;
len -= 3;
}
}
} else if (transformType == SHIFT_FIRST || transformType == SHIFT_ALL) {
int shiftOffset = offset - len;
final short param = transforms.params[transformIndex];
/* Limited sign extension: scalar < (1 << 24). */
int scalar = (param & 0x7FFF) + (0x1000000 - (param & 0x8000));
while (len > 0) {
int step = 1;
final int c0 = dst[shiftOffset] & 0xFF;
if (c0 < 0x80) {
/* 1-byte rune / 0sssssss / 7 bit scalar (ASCII). */
scalar += c0;
dst[shiftOffset] = (byte) (scalar & 0x7F);
} else if (c0 < 0xC0) {
/* Continuation / 10AAAAAA. */
} else if (c0 < 0xE0) {
/* 2-byte rune / 110sssss AAssssss / 11 bit scalar. */
if (len >= 2) {
final byte c1 = dst[shiftOffset + 1];
scalar += (c1 & 0x3F) | ((c0 & 0x1F) << 6);
dst[shiftOffset] = (byte) (0xC0 | ((scalar >> 6) & 0x1F));
dst[shiftOffset + 1] = (byte) ((c1 & 0xC0) | (scalar & 0x3F));
step = 2;
} else {
step = len;
}
} else if (c0 < 0xF0) {
/* 3-byte rune / 1110ssss AAssssss BBssssss / 16 bit scalar. */
if (len >= 3) {
final byte c1 = dst[shiftOffset + 1];
final byte c2 = dst[shiftOffset + 2];
scalar += (c2 & 0x3F) | ((c1 & 0x3F) << 6) | ((c0 & 0x0F) << 12);
dst[shiftOffset] = (byte) (0xE0 | ((scalar >> 12) & 0x0F));
dst[shiftOffset + 1] = (byte) ((c1 & 0xC0) | ((scalar >> 6) & 0x3F));
dst[shiftOffset + 2] = (byte) ((c2 & 0xC0) | (scalar & 0x3F));
step = 3;
} else {
step = len;
}
} else if (c0 < 0xF8) {
/* 4-byte rune / 11110sss AAssssss BBssssss CCssssss / 21 bit scalar. */
if (len >= 4) {
final byte c1 = dst[shiftOffset + 1];
final byte c2 = dst[shiftOffset + 2];
final byte c3 = dst[shiftOffset + 3];
scalar += (c3 & 0x3F) | ((c2 & 0x3F) << 6) | ((c1 & 0x3F) << 12) | ((c0 & 0x07) << 18);
dst[shiftOffset] = (byte) (0xF0 | ((scalar >> 18) & 0x07));
dst[shiftOffset + 1] = (byte) ((c1 & 0xC0) | ((scalar >> 12) & 0x3F));
dst[shiftOffset + 2] = (byte) ((c2 & 0xC0) | ((scalar >> 6) & 0x3F));
dst[shiftOffset + 3] = (byte) ((c3 & 0xC0) | (scalar & 0x3F));
step = 4;
} else {
step = len;
}
}
shiftOffset += step;
len -= step;
if (transformType == SHIFT_FIRST) {
len = 0;
}
}
}
// Copy suffix.
while (suffix != suffixEnd) {
dst[offset++] = prefixSuffixStorage[suffix++];
}
return offset - dstOffset;
}
}

View File

@@ -0,0 +1,119 @@
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.dec;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
/**
* A set of utility methods.
*/
final class Utils {
private static final byte[] BYTE_ZEROES = new byte[1024];
private static final int[] INT_ZEROES = new int[1024];
/**
* Fills byte array with zeroes.
*
* <p> Current implementation uses {@link System#arraycopy}, so it should be used for length not
* less than 16.
*
* @param dest array to fill with zeroes
* @param offset the first byte to fill
* @param length number of bytes to change
*/
static void fillBytesWithZeroes(byte[] dest, int start, int end) {
int cursor = start;
while (cursor < end) {
int step = Math.min(cursor + 1024, end) - cursor;
System.arraycopy(BYTE_ZEROES, 0, dest, cursor, step);
cursor += step;
}
}
/**
* Fills int array with zeroes.
*
* <p> Current implementation uses {@link System#arraycopy}, so it should be used for length not
* less than 16.
*
* @param dest array to fill with zeroes
* @param offset the first item to fill
* @param length number of item to change
*/
static void fillIntsWithZeroes(int[] dest, int start, int end) {
int cursor = start;
while (cursor < end) {
int step = Math.min(cursor + 1024, end) - cursor;
System.arraycopy(INT_ZEROES, 0, dest, cursor, step);
cursor += step;
}
}
static void copyBytes(byte[] dst, int target, byte[] src, int start, int end) {
System.arraycopy(src, start, dst, target, end - start);
}
static void copyBytesWithin(byte[] bytes, int target, int start, int end) {
System.arraycopy(bytes, start, bytes, target, end - start);
}
static int readInput(InputStream src, byte[] dst, int offset, int length) {
try {
return src.read(dst, offset, length);
} catch (IOException e) {
throw new BrotliRuntimeException("Failed to read input", e);
}
}
static void closeInput(InputStream src) throws IOException {
src.close();
}
static byte[] toUsAsciiBytes(String src) {
try {
// NB: String#getBytes(String) is present in JDK 1.1, while other variants require JDK 1.6 and
// above.
return src.getBytes("US-ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // cannot happen
}
}
static ByteBuffer asReadOnlyBuffer(ByteBuffer src) {
return src.asReadOnlyBuffer();
}
static int isReadOnly(ByteBuffer src) {
return src.isReadOnly() ? 1 : 0;
}
static int isDirect(ByteBuffer src) {
return src.isDirect() ? 1 : 0;
}
// Crazy pills factory: code compiled for JDK8 does not work on JRE9.
static void flipBuffer(Buffer buffer) {
buffer.flip();
}
static int isDebugMode() {
boolean assertsEnabled = Boolean.parseBoolean(System.getProperty("BROTLI_ENABLE_ASSERTS"));
return assertsEnabled ? 1 : 0;
}
// See BitReader.LOG_BITNESS
static int getLogBintness() {
boolean isLongExpensive = Boolean.parseBoolean(System.getProperty("BROTLI_32_BIT_CPU"));
return isLongExpensive ? 5 : 6;
}
}

View File

@@ -0,0 +1,16 @@
/* Copyright 2018 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.enc;
import java.nio.ByteBuffer;
/**
* Prepared dictionary data provider.
*/
public interface PreparedDictionary {
ByteBuffer getData();
}

View File

@@ -0,0 +1,185 @@
/* Copyright 2017 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.enc;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
/**
* Java prepared (raw) dictionary producer.
*/
public class PreparedDictionaryGenerator {
private static final int MAGIC = 0xDEBCEDE0;
private static final long HASH_MULTIPLIER = 0x1fe35a7bd3579bd3L;
private static class PreparedDictionaryImpl implements PreparedDictionary {
private final ByteBuffer data;
private PreparedDictionaryImpl(ByteBuffer data) {
this.data = data;
}
@Override
public ByteBuffer getData() {
return data;
}
}
// Disallow instantiation.
private PreparedDictionaryGenerator() { }
public static PreparedDictionary generate(ByteBuffer src) {
return generate(src, 17, 3, 40, 5);
}
public static PreparedDictionary generate(ByteBuffer src,
int bucketBits, int slotBits, int hashBits, int blockBits) {
((Buffer) src).clear(); // Just in case...
if (blockBits > 12) {
throw new IllegalArgumentException("blockBits is too big");
}
if (bucketBits >= 24) {
throw new IllegalArgumentException("bucketBits is too big");
}
if (bucketBits - slotBits >= 16) {
throw new IllegalArgumentException("slotBits is too small");
}
int bucketLimit = 1 << blockBits;
int numBuckets = 1 << bucketBits;
int numSlots = 1 << slotBits;
int slotMask = numSlots - 1;
int hashShift = 64 - bucketBits;
long hashMask = (~0L) >>> (64 - hashBits);
int sourceSize = src.capacity();
if (sourceSize < 8) {
throw new IllegalArgumentException("src is too short");
}
/* Step 1: create "bloated" hasher. */
short[] num = new short[numBuckets];
int[] bucketHeads = new int[numBuckets];
int[] nextBucket = new int[sourceSize];
long accumulator = 0;
for (int i = 0; i < 7; ++i) {
accumulator |= (src.get(i) & 0xFFL) << (8 * i);
}
accumulator <<= 8;
/* TODO(eustas): apply custom "store" order. */
for (int i = 0; i + 7 < sourceSize; ++i) {
accumulator = (accumulator >>> 8) | ((src.get(i + 7) & 0xFFL) << 56);
long h = (accumulator & hashMask) * HASH_MULTIPLIER;
int key = (int) (h >>> hashShift);
int count = num[key];
nextBucket[i] = (count == 0) ? -1 : bucketHeads[key];
bucketHeads[key] = i;
count++;
if (count > bucketLimit) {
count = bucketLimit;
}
num[key] = (short) count;
}
/* Step 2: find slot limits. */
int[] slotLimit = new int[numSlots];
int[] slotSize = new int[numSlots];
int totalItems = 0;
for (int i = 0; i < numSlots; ++i) {
boolean overflow = false;
slotLimit[i] = bucketLimit;
while (true) {
overflow = false;
int limit = slotLimit[i];
int count = 0;
for (int j = i; j < numBuckets; j += numSlots) {
int size = num[j];
/* Last chain may span behind 64K limit; overflow happens only if
we are about to use 0xFFFF+ as item offset. */
if (count >= 0xFFFF) {
overflow = true;
break;
}
if (size > limit) {
size = limit;
}
count += size;
}
if (!overflow) {
slotSize[i] = count;
totalItems += count;
break;
}
slotLimit[i]--;
}
}
/* Step 3: transfer data to "slim" hasher. */
int part0 = 6 * 4;
int part1 = numSlots * 4;
int part2 = numBuckets * 2;
int part3 = totalItems * 4;
int allocSize = part0 + part1 + part2 + part3 + sourceSize;
ByteBuffer flat = ByteBuffer.allocateDirect(allocSize);
ByteBuffer pointer = flat.slice();
pointer.order(ByteOrder.nativeOrder());
IntBuffer struct = pointer.asIntBuffer();
pointer.position(pointer.position() + part0);
IntBuffer slotOffsets = pointer.asIntBuffer();
pointer.position(pointer.position() + part1);
ShortBuffer heads = pointer.asShortBuffer();
pointer.position(pointer.position() + part2);
IntBuffer items = pointer.asIntBuffer();
pointer.position(pointer.position() + part3);
ByteBuffer sourceCopy = pointer.slice();
/* magic */ struct.put(0, MAGIC);
/* source_offset */ struct.put(1, totalItems);
/* source_size */ struct.put(2, sourceSize);
/* hash_bits */ struct.put(3, hashBits);
/* bucket_bits */ struct.put(4, bucketBits);
/* slot_bits */ struct.put(5, slotBits);
totalItems = 0;
for (int i = 0; i < numSlots; ++i) {
slotOffsets.put(i, totalItems);
totalItems += slotSize[i];
slotSize[i] = 0;
}
for (int i = 0; i < numBuckets; ++i) {
int slot = i & slotMask;
int count = num[i];
if (count > slotLimit[slot]) {
count = slotLimit[slot];
}
if (count == 0) {
heads.put(i, (short) 0xFFFF);
continue;
}
int cursor = slotSize[slot];
heads.put(i, (short) cursor);
cursor += slotOffsets.get(slot);
slotSize[slot] += count;
int pos = bucketHeads[i];
for (int j = 0; j < count; j++) {
items.put(cursor++, pos);
pos = nextBucket[pos];
}
cursor--;
items.put(cursor, items.get(cursor) | 0x80000000);
}
sourceCopy.put(src);
return new PreparedDictionaryImpl(flat);
}
}

View File

@@ -0,0 +1,88 @@
package app.firka.naplo
import android.annotation.SuppressLint
import android.app.Application
import android.os.Build
import android.util.Log
import org.brotli.dec.BrotliInputStream
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.security.MessageDigest
import java.util.zip.ZipFile
class AppMain : Application() {
private fun File.sha256(): String {
if (!exists()) return "0000000000000000000000000000000000000000000000000000000000000000"
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(this.readBytes())
return digest.fold("") { str, it -> str + "%02x".format(it) }
}
@SuppressLint("UnsafeDynamicallyLoadedCode")
override fun onCreate() {
super.onCreate()
val abi = Build.SUPPORTED_ABIS[0]
val apks = File(applicationInfo.nativeLibraryDir, "../..").absoluteFile
.listFiles()!!
.filter { file -> file.name.endsWith(".apk") }
.toList()
var nativesApkN: ZipFile? = null
for (apk in apks) {
if (nativesApkN != null) break
val zip = ZipFile(apk)
val entries = zip.entries()
while (entries.hasMoreElements()) {
val entry = entries.nextElement()
entry.name.endsWith("$abi/index.so")
zip.close()
nativesApkN = ZipFile(apk)
break
}
zip.close()
}
if (nativesApkN == null) {
throw Exception("Can't find native libraries")
}
val nativesApk: ZipFile = nativesApkN
val compressedLibsIndex = nativesApk.getInputStream(
nativesApk.getEntry("lib/$abi/index.so")
)
val compressedLibs = JSONObject(compressedLibsIndex.readBytes().toString(Charsets.UTF_8))
for (so in compressedLibs.keys()) {
val soFile = File(cacheDir, so)
if (soFile.sha256() == compressedLibs.getString(so)) {
System.load(soFile.absolutePath)
return
}
Log.d("AppMain", "Decompressing: $so")
val brInput = nativesApk.getInputStream(
nativesApk.getEntry("lib/$abi/${so.replace(".so", "-br.so")}")
)
val soOutput = FileOutputStream(soFile)
val brIn = BrotliInputStream(brInput)
brIn.copyTo(soOutput)
brInput.close()
soOutput.close()
System.load(soFile.absolutePath)
}
}
}

View File

@@ -0,0 +1,92 @@
package app.firka.naplo
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.core.app.NotificationCompat
import androidx.wear.ongoing.OngoingActivity
import androidx.wear.ongoing.Status
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
private val channel = "firka.app/main"
private val channelId = "ongoing_activity"
private val notificationId = 1000
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE)
as NotificationManager
notificationManager.createNotificationChannel(
NotificationChannel(
channelId,
"Ongoing Activity",
NotificationManager.IMPORTANCE_DEFAULT
)
)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setOngoing(true)
val ongoingActivityStatus = Status.Builder()
// Sets the text used across various surfaces.
.addTemplate("Firka")
.build()
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)!!
val activityPendingIntent = PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val ongoingActivity = OngoingActivity.Builder(applicationContext,
notificationId, notificationBuilder)
.setStaticIcon(R.drawable.ic_notification)
.setTouchIntent(activityPendingIntent)
.setStatus(ongoingActivityStatus)
.build()
ongoingActivity.apply(applicationContext)
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channel).setMethodCallHandler {
call, result ->
when (call.method) {
"get_info" -> {
result.success("${Build.MODEL};" +
"${Build.VERSION.RELEASE};" +
"${Build.VERSION.SDK_INT}")
}
"activity_update" -> {
notificationManager.notify(notificationId, notificationBuilder.build())
result.success(null)
}
"activity_cancel" -> {
notificationManager.cancel(notificationId)
result.success(null)
}
else -> {
result.notImplemented()
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE)
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 668 B

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="?android:colorBackground" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground>
<inset
android:drawable="@drawable/ic_launcher_foreground"
android:inset="0%" />
</foreground>
<monochrome>
<inset
android:drawable="@drawable/ic_launcher_monochrome"
android:inset="0%" />
</monochrome>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 544 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 721 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>

View File

@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

View File

@@ -0,0 +1,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application android:label="Firka" />
</manifest>

View File

@@ -0,0 +1,49 @@
import com.android.build.gradle.BaseExtension
import org.jetbrains.kotlin.gradle.plugin.extraProperties
allprojects {
repositories {
google()
mavenCentral()
}
}
val newBuildDir: Directory = rootProject.layout.buildDirectory.dir("../../build").get()
rootProject.layout.buildDirectory.value(newBuildDir)
subprojects {
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
// fix for verifyReleaseResources
// note(4831c0): taken from https://github.com/isar/isar/issues/1662
// note(4831c0): and adapted to kotlin
afterEvaluate {
if (plugins.hasPlugin("com.android.application") || plugins.hasPlugin("com.android.library")) {
val androidExtension = extensions.getByName("android") as BaseExtension
androidExtension.apply {
compileSdkVersion(35)
buildToolsVersion = "35.0.0"
}
}
if (hasProperty("android")) {
val androidExtension = extensions.getByName("android") as BaseExtension
androidExtension.apply {
// Set namespace if it's not already set
if (!extraProperties.has("namespace")) {
extraProperties["namespace"] = project.group.toString()
}
}
}
}
// ===============================
project.layout.buildDirectory.value(newSubprojectBuildDir)
}
subprojects {
project.evaluationDependsOn(":app")
}
tasks.register<Delete>("clean") {
delete(rootProject.layout.buildDirectory)
}

View File

@@ -0,0 +1,3 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
android.enableJetifier=true

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip

View File

@@ -0,0 +1,25 @@
pluginManagement {
val flutterSdkPath = run {
val properties = java.util.Properties()
file("local.properties").inputStream().use { properties.load(it) }
val flutterSdkPath = properties.getProperty("flutter.sdk")
require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
flutterSdkPath
}
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "8.7.0" apply false
id("org.jetbrains.kotlin.android") version "1.8.22" apply false
}
include(":app")

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><path fill="currentColor" d="M4 5h12v7a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4V5z"/><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 5H4v7a4 4 0 0 0 4 4h4a4 4 0 0 0 4-4V5zm0 0h2v0a2 2 0 0 1 2 2v4M4 19h14"/></svg>

After

Width:  |  Height:  |  Size: 324 B

View File

@@ -0,0 +1,7 @@
<svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M8.5 21.9995C8.5 21.4473 8.94772 20.9995 9.5 20.9995L11.5 20.9995H13.5L15.5 20.9995C16.0523 20.9995 16.5 21.4473 16.5 21.9995C16.5 22.5518 16.0523 22.9995 15.5 22.9995H9.5C8.94772 22.9995 8.5 22.5518 8.5 21.9995Z" fill="#FFFFFF"/>
<path d="M13.5 4.34104V6.37796C13.5088 6.37356 13.518 6.36939 13.5276 6.36552C13.592 6.33978 13.9921 6.19612 14.9453 6.8316C16.2421 7.69612 17.342 7.83978 18.2151 7.49052C18.6227 7.32751 18.9079 7.08279 19.091 6.87945C19.1827 6.77745 19.2516 6.68292 19.3003 6.60832C19.3249 6.57083 19.3447 6.53777 19.3602 6.51055C19.3679 6.49692 19.3746 6.48469 19.3803 6.47402L19.3881 6.45918L19.3915 6.45266L19.393 6.44963L19.3937 6.44818C19.3937 6.44818 19.3944 6.44676 18.5 5.99955L19.3944 6.44676C19.4639 6.30791 19.5 6.15479 19.5 5.99955V2.99955C19.5 2.53577 19.1811 2.13285 18.7298 2.0263C18.2911 1.92276 17.8393 2.12547 17.6238 2.51764C17.6204 2.52235 17.6139 2.53089 17.6044 2.54152C17.5764 2.57255 17.5336 2.60908 17.4724 2.63357C17.408 2.65931 17.0079 2.80297 16.0547 2.1675C14.7579 1.30297 13.658 1.15931 12.7849 1.50857C12.3773 1.67158 12.0921 1.9163 11.909 2.11964C11.8173 2.22164 11.7484 2.31618 11.6997 2.39077C11.6751 2.42827 11.6553 2.46132 11.6398 2.48854C11.6355 2.49615 11.6315 2.50333 11.6278 2.51003C11.5464 2.65473 11.5 2.82172 11.5 2.99955V5.99955C11.5 6.46332 11.8189 6.86624 12.2702 6.9728C12.3436 6.99011 12.4173 6.99886 12.4903 6.9996C12.4968 6.99966 12.5034 6.99966 12.51 6.9996C12.8658 6.99611 13.2 6.80212 13.3762 6.48146C13.3796 6.47675 13.3861 6.4682 13.3956 6.45757C13.4192 6.43144 13.4533 6.40141 13.5 6.37796V4.34104V3.37796C13.5088 3.37356 13.518 3.36939 13.5276 3.36552C13.592 3.33978 13.9921 3.19612 14.9453 3.8316C15.9099 4.47466 16.7656 4.71888 17.5 4.65806V5.62114C17.4912 5.62554 17.482 5.6297 17.4724 5.63357C17.408 5.65931 17.0079 5.80297 16.0547 5.1675C15.0901 4.52443 14.2344 4.28021 13.5 4.34104Z" fill="#FFFFFF"/>
<path d="M13.0547 7.1675L13.5 7.46436V6.37796C13.4533 6.40141 13.4192 6.43144 13.3956 6.45757C13.3861 6.4682 13.3796 6.47675 13.3762 6.48146C13.2 6.80212 12.8658 6.99611 12.51 6.9996C12.7 7.00149 12.8896 7.05746 13.0547 7.1675Z" fill="#FFFFFF"/>
<path d="M11.5 7.46436L11.9453 7.1675C12.1104 7.05741 12.3001 7.00145 12.4903 6.9996C12.4173 6.99886 12.3436 6.99011 12.2702 6.9728C11.8189 6.86624 11.5 6.46332 11.5 5.99955V7.46436Z" fill="#FFFFFF"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.4903 6.9996C12.3001 7.00145 12.1104 7.05741 11.9453 7.1675L11.5 7.46436L5.9453 11.1675C5.6671 11.353 5.5 11.6652 5.5 11.9995V14.4995H3.5C2.96957 14.4995 2.46086 14.7103 2.08579 15.0853C1.71071 15.4604 1.5 15.9691 1.5 16.4995V21.9995C1.5 22.5518 1.94772 22.9995 2.5 22.9995H10.5H14.5H21.5C22.0304 22.9995 22.5391 22.7888 22.9142 22.4138C23.2893 22.0387 23.5 21.53 23.5 20.9995V16.4995C23.5 15.9691 23.2893 15.4604 22.9142 15.0853C22.5391 14.7103 22.0304 14.4995 21.5 14.4995H19.5V11.9995C19.5 11.6652 19.3329 11.353 19.0547 11.1675L13.5 7.46436L13.0547 7.1675C12.8896 7.05746 12.7 7.00149 12.51 6.9996L12.4903 6.9996ZM15.5 15.4995V20.9995L13.5 20.9995V16.4995H11.5V20.9995L9.5 20.9995V15.4995C9.5 14.9473 9.94771 14.4995 10.5 14.4995H14.5C15.0523 14.4995 15.5 14.9473 15.5 15.4995Z" fill="#FFFFFF"/>
</svg>

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

@@ -0,0 +1,3 @@
<svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M13.5 3C13.5 2.73478 13.3946 2.48043 13.2071 2.29289C13.0196 2.10536 12.7652 2 12.5 2C12.2348 2 11.9804 2.10536 11.7929 2.29289C11.6054 2.48043 11.5 2.73478 11.5 3V4C11.5 4.26522 11.6054 4.51957 11.7929 4.70711C11.9804 4.89464 12.2348 5 12.5 5C12.7652 5 13.0196 4.89464 13.2071 4.70711C13.3946 4.51957 13.5 4.26522 13.5 4V3ZM6.207 4.293C6.0184 4.11084 5.7658 4.01005 5.5036 4.01233C5.2414 4.0146 4.99059 4.11977 4.80518 4.30518C4.61977 4.49059 4.5146 4.7414 4.51233 5.0036C4.51005 5.2658 4.61084 5.5184 4.793 5.707L5.793 6.707C5.9816 6.88916 6.2342 6.98995 6.4964 6.98767C6.7586 6.9854 7.00941 6.88023 7.19482 6.69482C7.38023 6.50941 7.4854 6.2586 7.48767 5.9964C7.48995 5.7342 7.38916 5.4816 7.207 5.293L6.207 4.293ZM20.207 4.293C20.0195 4.10553 19.7652 4.00021 19.5 4.00021C19.2348 4.00021 18.9805 4.10553 18.793 4.293L17.793 5.293C17.6108 5.4816 17.51 5.7342 17.5123 5.9964C17.5146 6.2586 17.6198 6.50941 17.8052 6.69482C17.9906 6.88023 18.2414 6.9854 18.5036 6.98767C18.7658 6.98995 19.0184 6.88916 19.207 6.707L20.207 5.707C20.3945 5.51947 20.4998 5.26516 20.4998 5C20.4998 4.73484 20.3945 4.48053 20.207 4.293ZM12.5 7C11.1739 7 9.90215 7.52678 8.96447 8.46447C8.02678 9.40215 7.5 10.6739 7.5 12C7.5 13.3261 8.02678 14.5979 8.96447 15.5355C9.90215 16.4732 11.1739 17 12.5 17C13.8261 17 15.0979 16.4732 16.0355 15.5355C16.9732 14.5979 17.5 13.3261 17.5 12C17.5 10.6739 16.9732 9.40215 16.0355 8.46447C15.0979 7.52678 13.8261 7 12.5 7ZM3.5 11C3.23478 11 2.98043 11.1054 2.79289 11.2929C2.60536 11.4804 2.5 11.7348 2.5 12C2.5 12.2652 2.60536 12.5196 2.79289 12.7071C2.98043 12.8946 3.23478 13 3.5 13H4.5C4.76522 13 5.01957 12.8946 5.20711 12.7071C5.39464 12.5196 5.5 12.2652 5.5 12C5.5 11.7348 5.39464 11.4804 5.20711 11.2929C5.01957 11.1054 4.76522 11 4.5 11H3.5ZM20.5 11C20.2348 11 19.9804 11.1054 19.7929 11.2929C19.6054 11.4804 19.5 11.7348 19.5 12C19.5 12.2652 19.6054 12.5196 19.7929 12.7071C19.9804 12.8946 20.2348 13 20.5 13H21.5C21.7652 13 22.0196 12.8946 22.2071 12.7071C22.3946 12.5196 22.5 12.2652 22.5 12C22.5 11.7348 22.3946 11.4804 22.2071 11.2929C22.0196 11.1054 21.7652 11 21.5 11H20.5ZM7.207 18.707C7.30251 18.6148 7.37869 18.5044 7.4311 18.3824C7.48351 18.2604 7.5111 18.1292 7.51225 17.9964C7.5134 17.8636 7.4881 17.7319 7.43782 17.609C7.38754 17.4862 7.31329 17.3745 7.2194 17.2806C7.1255 17.1867 7.01385 17.1125 6.89095 17.0622C6.76806 17.0119 6.63638 16.9866 6.5036 16.9877C6.37082 16.9889 6.2396 17.0165 6.1176 17.0689C5.99559 17.1213 5.88525 17.1975 5.793 17.293L4.793 18.293C4.69749 18.3852 4.62131 18.4956 4.5689 18.6176C4.51649 18.7396 4.4889 18.8708 4.48775 19.0036C4.4866 19.1364 4.5119 19.2681 4.56218 19.391C4.61246 19.5138 4.68671 19.6255 4.7806 19.7194C4.8745 19.8133 4.98615 19.8875 5.10905 19.9378C5.23194 19.9881 5.36362 20.0134 5.4964 20.0123C5.62918 20.0111 5.7604 19.9835 5.8824 19.9311C6.00441 19.8787 6.11475 19.8025 6.207 19.707L7.207 18.707ZM19.207 17.293C19.0184 17.1108 18.7658 17.01 18.5036 17.0123C18.2414 17.0146 17.9906 17.1198 17.8052 17.3052C17.6198 17.4906 17.5146 17.7414 17.5123 18.0036C17.51 18.2658 17.6108 18.5184 17.793 18.707L18.793 19.707C18.9816 19.8892 19.2342 19.99 19.4964 19.9877C19.7586 19.9854 20.0094 19.8802 20.1948 19.6948C20.3802 19.5094 20.4854 19.2586 20.4877 18.9964C20.49 18.7342 20.3892 18.4816 20.207 18.293L19.207 17.293ZM13.5 20C13.5 19.7348 13.3946 19.4804 13.2071 19.2929C13.0196 19.1054 12.7652 19 12.5 19C12.2348 19 11.9804 19.1054 11.7929 19.2929C11.6054 19.4804 11.5 19.7348 11.5 20V21C11.5 21.2652 11.6054 21.5196 11.7929 21.7071C11.9804 21.8946 12.2348 22 12.5 22C12.7652 22 13.0196 21.8946 13.2071 21.7071C13.3946 21.5196 13.5 21.2652 13.5 21V20Z" fill="#FFFFFF"/>
</svg>

After

Width:  |  Height:  |  Size: 3.7 KiB

View File

@@ -0,0 +1,3 @@
description: This file stores settings for Dart & Flutter DevTools.
documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states
extensions:

View File

@@ -0,0 +1,11 @@
flutter_launcher_icons:
generate: true
android: "launcher_icon"
image_path: "assets/images/logos/colored_logo.png"
adaptive_icon_monochrome: "assets/images/logos/monochrome_logo.png"
adaptive_icon_background: "assets/images/logos/colored_logo_without_mustache.png"
adaptive_icon_foreground: "assets/images/logos/colored_logo_only_mustache.png"
adaptive_icon_foreground_inset: 0
min_sdk_android: 21
ios: true
remove_alpha_channel_ios: true

3
firka_wear/l10n.yml Normal file
View File

@@ -0,0 +1,3 @@
arb-dir: lib/l10n
template-arb-file: app_hu.arb
output-localization-file: app_localizations.dart

View File

@@ -0,0 +1,519 @@
import 'dart:convert';
import 'dart:math';
import 'package:dio/dio.dart';
import 'package:firka_wear/helpers/api/model/homework.dart';
import 'package:firka_wear/helpers/api/model/timetable.dart';
import 'package:firka_wear/helpers/db/models/generic_cache_model.dart';
import 'package:firka_wear/helpers/db/models/homework_cache_model.dart';
import 'package:firka_wear/helpers/db/models/timetable_cache_model.dart';
import 'package:intl/intl.dart';
import 'package:isar/isar.dart';
import '../../../main.dart';
import '../../db/models/token_model.dart';
import '../../db/util.dart';
import '../../debug_helper.dart';
import '../consts.dart';
import '../model/grade.dart';
import '../model/notice_board.dart';
import '../model/omission.dart';
import '../model/student.dart';
import '../model/test.dart';
import '../token_grant.dart';
class ApiResponse<T> {
T? response;
int statusCode;
String? err;
bool cached;
ApiResponse(
this.response,
this.statusCode,
this.err,
this.cached,
);
@override
String toString() {
return "ApiResponse("
"response: $response, "
"statusCode: $statusCode, "
"err: \"$err\", "
"cached: $cached"
")";
}
}
class KretaClient {
bool _tokenMutex = false;
TokenModel model;
Isar isar;
KretaClient(this.model, this.isar);
Future<T> _mutexCallback<T>(Future<T> Function() callback) async {
while (_tokenMutex) {
await Future.delayed(const Duration(milliseconds: 50));
}
_tokenMutex = true;
try {
return callback();
} finally {
_tokenMutex = false;
}
}
Future<Response> _authReq(String method, String url, [Object? data]) async {
var localToken = await _mutexCallback<String>(() async {
var now = timeNow();
if (now.millisecondsSinceEpoch >=
model.expiryDate!.millisecondsSinceEpoch) {
var extended = await extendToken(model);
var tokenModel = TokenModel.fromResp(extended);
await isar.writeTxn(() async {
await isar.tokenModels.put(tokenModel);
});
model = tokenModel;
}
return model.accessToken!;
});
final headers = <String, String>{
// "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"accept": "*/*",
"user-agent": "eKretaStudent/264745 CFNetwork/1494.0.7 Darwin/23.4.0",
"authorization": "Bearer $localToken",
"apiKey": "21ff6c25-d1da-4a68-a811-c881a6057463"
};
return await dio.get(url,
options: Options(method: method, headers: headers), data: data);
}
Future<(dynamic, int)> _authJson(String method, String url,
[Object? data]) async {
var resp = await _authReq(method, url, data);
return (resp.data, resp.statusCode!);
}
Future<(dynamic, int, Object?, bool)> _cachingGet(
CacheId id, String url, bool forceCache) async {
// it would be *ideal* to use xor and left shift here, however
// binary operations seem to round the number down to
// 32 bits for some reason???
var cacheKey = model.studentId! + ((id.index + 1) * pow(10, 11));
var cache = await isar.genericCacheModels.get(cacheKey as int);
dynamic resp;
int statusCode;
try {
if (forceCache && cache != null) {
return (jsonDecode(cache.cacheData!), 200, null, true);
}
(resp, statusCode) = await _authJson("GET", url);
if (statusCode >= 400) {
if (cache != null) {
return (jsonDecode(cache.cacheData!), statusCode, null, true);
}
}
} catch (ex) {
if (cache != null) {
return (jsonDecode(cache.cacheData!), 0, ex, true);
} else {
return (null, 0, ex, false);
}
}
await isar.writeTxn(() async {
var cache = GenericCacheModel();
cache.cacheKey = cacheKey;
cache.cacheData = jsonEncode(resp);
isar.genericCacheModels.put(cache);
});
return (resp, statusCode, null, false);
}
ApiResponse<Student>? studentCache;
Future<ApiResponse<Student>> getStudent({bool forceCache = true}) async {
if (forceCache && studentCache != null) return studentCache!;
var (resp, status, ex, cached) = await _cachingGet(CacheId.getStudent,
KretaEndpoints.getStudentUrl(model.iss!), forceCache);
Student? student;
String? err;
try {
student = Student.fromJson(resp);
} catch (ex) {
err = ex.toString();
}
if (ex != null) {
err = ex.toString();
}
if (ex == null) studentCache = ApiResponse(student, 200, null, true);
return ApiResponse(student, status, err, cached);
}
ApiResponse<List<NoticeBoardItem>>? noticeBoardCache;
Future<ApiResponse<List<NoticeBoardItem>>> getNoticeBoard(
{bool forceCache = true}) async {
if (forceCache && noticeBoardCache != null) return noticeBoardCache!;
var (resp, status, ex, cached) = await _cachingGet(CacheId.getNoticeBoard,
KretaEndpoints.getNoticeBoard(model.iss!), forceCache);
var items = List<NoticeBoardItem>.empty(growable: true);
String? err;
try {
List<dynamic> rawItems = resp;
for (var item in rawItems) {
items.add(NoticeBoardItem.fromJson(item));
}
} catch (ex) {
err = ex.toString();
}
if (ex != null) {
err = ex.toString();
}
if (err == null) noticeBoardCache = ApiResponse(items, 200, null, true);
return ApiResponse(items, status, err, cached);
}
ApiResponse<List<Grade>>? gradeCache;
Future<ApiResponse<List<Grade>>> getGrades({bool forceCache = true}) async {
if (forceCache && gradeCache != null) {
return gradeCache!;
}
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getGrades, KretaEndpoints.getGrades(model.iss!), forceCache);
var items = List<Grade>.empty(growable: true);
String? err;
try {
List<dynamic> rawItems = resp;
for (var item in rawItems) {
items.add(Grade.fromJson(item));
}
} catch (ex) {
err = ex.toString();
}
if (ex != null) {
err = ex.toString();
}
items.sort((a, b) => b.recordDate.compareTo(a.recordDate));
if (ex == null) gradeCache = ApiResponse(items, 200, null, true);
return ApiResponse(items, status, err, cached);
}
Future<(List<dynamic>, int, Object?, bool)>
_timedCachingGet<T extends DatedCacheEntry>(
IsarCollection<T> cacheModel,
String endpoint,
DateTime from,
DateTime? to,
bool forceCache,
Future<void> Function(dynamic, int) storeCache) async {
var cacheKey = genCacheKey(from, model.studentId!);
var cache = await cacheModel.get(cacheKey);
var formatter = DateFormat('yyyy-MM-dd');
var fromStr = formatter.format(from);
var toStr = to != null ? formatter.format(to) : null;
var now = timeNow();
if (cache != null && (cache as dynamic).values == null) {
(cache as dynamic).values = List<String>.empty(growable: true);
}
List<dynamic> resp;
int statusCode;
try {
if (forceCache && cache != null) {
var items = List<dynamic>.empty(growable: true);
for (var item in (cache as dynamic).values) {
items.add(jsonDecode(item));
}
return (items, 200, null, true);
}
if (toStr == null) {
(resp, statusCode) = await _authJson(
"GET",
"$endpoint?"
"datumTol=$fromStr");
} else {
(resp, statusCode) = await _authJson(
"GET",
"$endpoint?"
"datumTol=$fromStr&datumIg=$toStr");
}
if (statusCode >= 400) {
if (cache != null) {
var items = List<dynamic>.empty(growable: true);
for (var item in (cache as dynamic).values) {
items.add(jsonDecode(item));
}
return (items, statusCode, null, true);
}
}
} catch (ex) {
if (cache != null) {
var items = List<dynamic>.empty(growable: true);
for (var item in (cache as dynamic).values) {
items.add(jsonDecode(item));
}
return (items, 0, ex, true);
} else {
return (List<dynamic>.empty(growable: true), 0, ex, false);
}
}
// only cache stuff in a 1 month frame
if (from.millisecondsSinceEpoch >=
now.subtract(Duration(days: 30)).millisecondsSinceEpoch) {
if (to == null ||
to.millisecondsSinceEpoch <=
now.add(Duration(days: 30)).millisecondsSinceEpoch) {
await isar.writeTxn(() async {
await storeCache(resp, cacheKey);
});
}
}
return (resp, statusCode, null, false);
}
/// Expects from and to to be 7 days apart
Future<ApiResponse<List<Lesson>>> _getTimeTable(
DateTime from, DateTime to, bool forceCache) async {
var (resp, status, ex, cached) =
await _timedCachingGet<TimetableCacheModel>(
isar.timetableCacheModels,
KretaEndpoints.getTimeTable(model.iss!),
from,
to,
forceCache, (dynamic resp, int cacheKey) async {
TimetableCacheModel cache = TimetableCacheModel();
var rawClasses = List<String>.empty(growable: true);
for (var obj in resp) {
rawClasses.add(jsonEncode(obj));
}
cache.cacheKey = cacheKey;
cache.values = rawClasses;
await isar.timetableCacheModels.put(cache as dynamic);
});
var items = List<Lesson>.empty(growable: true);
String? err;
try {
List<dynamic> rawItems = resp;
for (var item in rawItems) {
items.add(Lesson.fromJson(item));
}
} catch (ex) {
err = ex.toString();
}
if (ex != null) {
err = ex.toString();
}
return ApiResponse(items, status, err, cached);
}
/// Expects from and to to be 7 days apart
Future<ApiResponse<List<Homework>>> _getHomework(
DateTime from, DateTime to, bool forceCache) async {
var (resp, status, ex, cached) = await _timedCachingGet<HomeworkCacheModel>(
isar.homeworkCacheModels,
KretaEndpoints.getHomework(model.iss!),
from,
null,
forceCache, (dynamic resp, int cacheKey) async {
HomeworkCacheModel cache = HomeworkCacheModel();
var rawClasses = List<String>.empty(growable: true);
for (var obj in resp) {
rawClasses.add(jsonEncode(obj));
}
cache.cacheKey = cacheKey;
cache.values = rawClasses;
await isar.homeworkCacheModels.put(cache as dynamic);
});
var items = List<Homework>.empty(growable: true);
String? err;
try {
List<dynamic> rawItems = resp;
for (var item in rawItems) {
items.add(Homework.fromJson(item));
}
} catch (ex) {
err = ex.toString();
}
if (ex != null) {
err = ex.toString();
}
return ApiResponse(items, status, err, cached);
}
/// Automatically aligns requests to start at Monday and end at Sunday
Future<ApiResponse<List<Homework>>> getHomework(DateTime from, DateTime to,
{bool forceCache = true}) async {
var homework = List<Homework>.empty(growable: true);
String? err;
bool cached = true;
for (var i = from.millisecondsSinceEpoch;
i < to.millisecondsSinceEpoch;
i += 604800000) {
var from = DateTime.fromMillisecondsSinceEpoch(i);
var start = from.subtract(Duration(days: from.weekday - 1));
var end = start.add(Duration(days: 6));
var resp = await _getHomework(start, end, forceCache);
if (resp.err != null) {
err = resp.err;
if (!resp.cached) {
return resp;
} else {
homework.addAll(resp.response!);
}
} else {
homework.addAll(resp.response!);
}
if (!resp.cached) cached = false;
}
homework.sort((a, b) => a.startDate.compareTo(b.startDate));
homework = homework.where((h) => h.dueDate.isAfter(timeNow())).toList();
return ApiResponse(homework, 200, err, cached);
}
/// Automatically aligns requests to start at Monday and end at Sunday
Future<ApiResponse<List<Lesson>>> getTimeTable(DateTime from, DateTime to,
{bool forceCache = true}) async {
var lessons = List<Lesson>.empty(growable: true);
String? err;
bool cached = true;
for (var i = from.millisecondsSinceEpoch;
i < to.millisecondsSinceEpoch;
i += 604800000) {
var from = DateTime.fromMillisecondsSinceEpoch(i);
var start = from.subtract(Duration(days: from.weekday - 1));
var end = start.add(Duration(days: 6));
var resp = await _getTimeTable(start, end, forceCache);
if (resp.err != null) {
err = resp.err;
if (!resp.cached) {
return resp;
} else {
lessons.addAll(resp.response!);
}
} else {
lessons.addAll(resp.response!);
}
if (!resp.cached) cached = false;
}
lessons.sort((a, b) => a.start.compareTo(b.start));
lessons = lessons
.where(
(lesson) => lesson.start.isAfter(from) && lesson.end.isBefore(to))
.toList();
return ApiResponse(lessons, 200, err, cached);
}
Future<ApiResponse<List<Test>>> getTests({bool forceCache = true}) async {
var (resp, status, ex, cached) = await _cachingGet(
CacheId.getTests, KretaEndpoints.getTests(model.iss!), forceCache);
var items = List<Test>.empty(growable: true);
String? err;
try {
List<dynamic> rawItems = resp;
for (var item in rawItems) {
items.add(Test.fromJson(item));
}
} catch (ex) {
err = ex.toString();
}
if (ex != null) {
err = ex.toString();
}
// items.sort((a, b) => a.date.compareTo(b.date));
return ApiResponse(items, status, err, cached);
}
ApiResponse<List<Omission>>? omissionsCache;
Future<ApiResponse<List<Omission>>> getOmissions(
{bool forceCache = true}) async {
if (omissionsCache != null) return omissionsCache!;
var (resp, status, ex, cached) = await _cachingGet(CacheId.getOmissions,
KretaEndpoints.getOmissions(model.iss!), forceCache);
var items = List<Omission>.empty(growable: true);
String? err;
try {
List<dynamic> rawItems = resp;
for (var item in rawItems) {
items.add(Omission.fromJson(item));
}
} catch (ex) {
err = ex.toString();
}
if (ex != null) {
err = ex.toString();
}
items.sort((a, b) => a.date.compareTo(b.date));
if (ex == null) omissionsCache = ApiResponse(items, 200, null, true);
return ApiResponse(items, status, err, cached);
}
void evictMemCache() {
studentCache = null;
noticeBoardCache = null;
gradeCache = null;
omissionsCache = null;
}
}

View File

@@ -0,0 +1,52 @@
/*
Firka, alternative e-Kréta client.
Copyright (C) 2025 QwIT Development
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
class Constants {
static const clientId = "kreta-ellenorzo-student-mobile-ios";
}
class KretaEndpoints {
static String kretaBase = "e-kreta.hu";
static String kreta(String iss) {
if (iss == "firka-test") {
return kretaBase;
} else {
return "https://$iss.$kretaBase";
}
}
static String kretaIdp = "https://idp.e-kreta.hu";
static String kretaLoginUrl =
"$kretaIdp/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fprompt%3Dlogin%26nonce%3DwylCrqT4oN6PPgQn2yQB0euKei9nJeZ6_ffJ-VpSKZU%26response_type%3Dcode%26code_challenge_method%3DS256%26scope%3Dopenid%2520email%2520offline_access%2520kreta-ellenorzo-webapi.public%2520kreta-eugyintezes-webapi.public%2520kreta-fileservice-webapi.public%2520kreta-mobile-global-webapi.public%2520kreta-dkt-webapi.public%2520kreta-ier-webapi.public%26code_challenge%3DHByZRRnPGb-Ko_wTI7ibIba1HQ6lor0ws4bcgReuYSQ%26redirect_uri%3Dhttps%253A%252F%252Fmobil.e-kreta.hu%252Fellenorzo-student%252Fprod%252Foauthredirect%26client_id%3Dkreta-ellenorzo-student-mobile-ios%26state%3Dkreta_student_mobile%26suppressed_prompt%3Dlogin";
static String tokenGrantUrl = "$kretaIdp/connect/token";
static String getStudentUrl(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/TanuloAdatlap";
static String getNoticeBoard(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/FaliujsagElemek";
static String getGrades(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/Ertekelesek";
static String getTimeTable(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/OrarendElemek";
static String getOmissions(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/Mulasztasok";
static String getHomework(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/HaziFeladatok";
static String getTests(String iss) =>
"${kreta(iss)}/ellenorzo/v3/sajat/BejelentettSzamonkeresek";
}

View File

@@ -0,0 +1,58 @@
class NameUidDesc {
final String uid;
final String? name;
final String? description;
NameUidDesc(
{required this.uid, required this.name, required this.description});
factory NameUidDesc.fromJson(Map<String, dynamic> json) {
return NameUidDesc(
uid: json['Uid'], name: json['Nev'], description: json['Leiras']);
}
@override
String toString() {
return 'NameUidDesc('
'uid: "$uid", '
'name: "$name", '
'description: "$description"'
')';
}
}
class NameUid {
final String uid;
final String name;
NameUid({
required this.uid,
required this.name,
});
factory NameUid.fromJson(Map<String, dynamic> json) {
return NameUid(
uid: json['Uid'],
name: json['Nev'],
);
}
}
class UidObj {
final String uid;
UidObj({required this.uid});
factory UidObj.fromJson(Map<String, dynamic> json) {
return UidObj(
uid: json['Uid'],
);
}
@override
String toString() {
return 'UidObj('
'uid: "$uid"'
')';
}
}

View File

@@ -0,0 +1,90 @@
import 'package:firka_wear/helpers/api/model/generic.dart';
import 'package:firka_wear/helpers/api/model/subject.dart';
class Grade {
final String uid;
final DateTime recordDate;
final DateTime creationDate;
final DateTime? ackDate;
final Subject subject;
final String? topic;
final NameUidDesc type;
final NameUidDesc? mode;
NameUidDesc valueType;
final String teacher;
final String? kind;
int? numericValue;
final String strValue;
final int? weightPercentage;
final String? shortStrValue;
final UidObj? classGroup;
final int sortIndex;
Grade(
{required this.uid,
required this.recordDate,
required this.creationDate,
this.ackDate,
required this.subject,
this.topic,
required this.type,
this.mode,
required this.valueType,
required this.teacher,
this.kind,
this.numericValue,
required this.strValue,
this.weightPercentage,
this.shortStrValue,
this.classGroup,
required this.sortIndex});
factory Grade.fromJson(Map<String, dynamic> json) {
return Grade(
uid: json['Uid'],
recordDate: DateTime.parse(json['RogzitesDatuma']),
creationDate: DateTime.parse(json['KeszitesDatuma']),
ackDate: json['LattamozasDatuma'] != null
? DateTime.parse(json['LattamozasDatuma'])
: null,
subject: Subject.fromJson(json['Tantargy']),
topic: json['Tema'],
type: NameUidDesc.fromJson(json['Tipus']),
mode: json['Mod'] != null ? NameUidDesc.fromJson(json['Mod']) : null,
valueType: NameUidDesc.fromJson(json['ErtekFajta']),
teacher: json['ErtekeloTanarNeve'],
kind: json['Kind'],
numericValue: json['SzamErtek'],
strValue: json['SzovegesErtek'],
weightPercentage: json['SulySzazalekErteke'],
shortStrValue: json['SzovegesErtekelesRovidNev'],
classGroup: json['OsztalyCsoport'] != null
? UidObj.fromJson(json['OsztalyCsoport'])
: null,
sortIndex: json['SortIndex'],
);
}
@override
String toString() {
return 'Grade('
'uid: "$uid", '
'recordDate: "$recordDate", '
'creationDate: "$creationDate", '
'ackDate: "${ackDate ?? 'null'}", '
'subject: $subject, '
'topic: "${topic ?? 'null'}", '
'type: $type, '
'mode: ${mode ?? 'null'}, '
'valueType: $valueType, '
'teacher: "$teacher", '
'kind: "${kind ?? 'null'}", '
'numericValue: ${numericValue ?? 'null'}, '
'strValue: "$strValue", '
'weightPercentage: ${weightPercentage ?? 'null'}, '
'shortStrValue: "${shortStrValue ?? 'null'}", '
'classGroup: ${classGroup ?? 'null'}, '
'sortIndex: $sortIndex'
')';
}
}

View File

@@ -0,0 +1,52 @@
/*
Firka, alternative e-Kréta client.
Copyright (C) 2025 QwIT Development
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
class Guardian {
final String? email;
final bool isLegalRepresentative;
final String? name;
final String? phoneNumber;
final String uid;
Guardian(
{required this.email,
required this.isLegalRepresentative,
required this.name,
required this.phoneNumber,
required this.uid});
factory Guardian.fromJson(Map<String, dynamic> json) {
return Guardian(
email: json['EmailCim'],
isLegalRepresentative: json['IsTorvenyesKepviselo'],
name: json['Nev'],
phoneNumber: json['Telefonszam'],
uid: json['Uid']);
}
@override
String toString() {
return 'Guardian('
'email: "$email", '
'isLegalRepresentative: $isLegalRepresentative, '
'name: "$name", '
'phoneNumber: "$phoneNumber", '
'uid: "$uid"'
')';
}
}

View File

@@ -0,0 +1,70 @@
import 'package:firka_wear/helpers/api/model/subject.dart';
import 'generic.dart';
class Homework {
final String uid;
final Subject subject;
final String subjectName;
final String teacherName;
final String description;
final DateTime startDate;
final DateTime dueDate;
final DateTime creationDate;
final bool isCreatedByTeacher;
final bool isDone;
final bool canBeSubmitted;
final UidObj classGroup;
final bool canAttach;
Homework(
{required this.uid,
required this.subject,
required this.subjectName,
required this.teacherName,
required this.description,
required this.startDate,
required this.dueDate,
required this.creationDate,
required this.isCreatedByTeacher,
required this.isDone,
required this.canBeSubmitted,
required this.classGroup,
required this.canAttach});
factory Homework.fromJson(Map<String, dynamic> json) {
return Homework(
uid: json["Uid"],
subject: Subject.fromJson(json["Tantargy"]),
subjectName: json["TantargyNeve"],
teacherName: json["RogzitoTanarNeve"],
description: json["Szoveg"],
startDate: DateTime.parse(json["FeladasDatuma"]).toLocal(),
dueDate: DateTime.parse(json["HataridoDatuma"]).toLocal(),
creationDate: DateTime.parse(json["RogzitesIdopontja"]).toLocal(),
isCreatedByTeacher: json["IsTanarRogzitette"],
isDone: json["IsMegoldva"],
canBeSubmitted: json["IsBeadhato"],
classGroup: UidObj.fromJson(json["OsztalyCsoport"]),
canAttach: json["IsCsatolasEngedelyezes"]);
}
@override
String toString() {
return 'Homework('
'uid: "$uid", '
'subject: $subject, '
'subjectName: "$subjectName", '
'teacherName: "$teacherName", '
'description: "$description", '
'startDate: $startDate, '
'dueDate: $dueDate, '
'creationDate: $creationDate, '
'isCreatedByTeacher: $isCreatedByTeacher, '
'isDone: $isDone, '
'canBeSubmitted: $canBeSubmitted, '
'classGroup: $classGroup, '
'canAttach: $canAttach'
')';
}
}

View File

@@ -0,0 +1,100 @@
/*
Firka, alternative e-Kréta client.
Copyright (C) 2025 QwIT Development
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
class Institution {
final CustomizationSettings customizationSettings;
final String shortName;
final List<SystemModule> systemModuleList;
final String uid;
Institution(
{required this.customizationSettings,
required this.shortName,
required this.systemModuleList,
required this.uid});
factory Institution.fromJson(Map<String, dynamic> json) {
var systemModuleList = List<SystemModule>.empty(growable: true);
for (var item in json['Rendszermodulok']) {
systemModuleList.add(SystemModule.fromJson(item));
}
return Institution(
customizationSettings:
CustomizationSettings.fromJson(json['TestreszabasBeallitasok']),
shortName: json['RovidNev'],
systemModuleList: systemModuleList,
uid: json['Uid'],
);
}
}
class CustomizationSettings {
final int delayForNotifications;
final bool isClassAverageVisible;
final bool isLessonsThemeVisible;
final String nextServerDeployAsString;
CustomizationSettings(
{required this.delayForNotifications,
required this.isClassAverageVisible,
required this.isLessonsThemeVisible,
required this.nextServerDeployAsString});
factory CustomizationSettings.fromJson(Map<String, dynamic> json) {
return CustomizationSettings(
delayForNotifications:
json['ErtekelesekMegjelenitesenekKesleltetesenekMerteke'],
isClassAverageVisible: json['IsOsztalyAtlagMegjeleniteseEllenorzoben'],
isLessonsThemeVisible: json['IsTanorakTemajaMegtekinthetoEllenorzoben'],
nextServerDeployAsString: json['KovetkezoTelepitesDatuma']);
}
@override
String toString() {
return 'CustomizationSettings('
'delayForNotifications: $delayForNotifications, '
'isClassAverageVisible: $isClassAverageVisible, '
'isLessonsThemeVisible: $isLessonsThemeVisible, '
'nextServerDeployAsString: "$nextServerDeployAsString"'
')';
}
}
class SystemModule {
final bool isActive;
final String type;
final String? url;
SystemModule({required this.isActive, required this.type, required this.url});
factory SystemModule.fromJson(Map<String, dynamic> json) {
return SystemModule(
isActive: json['IsAktiv'], type: json['Tipus'], url: json['Url']);
}
@override
String toString() {
return 'SystemModule('
'isActive: $isActive, '
'type: "$type", '
'url: "$url"'
')';
}
}

View File

@@ -0,0 +1,42 @@
class NoticeBoardItem {
final String uid;
final String author;
final DateTime validFrom;
final DateTime validTo;
final String title;
final String contentHTML;
final String contentText;
NoticeBoardItem(
{required this.uid,
required this.author,
required this.validFrom,
required this.validTo,
required this.title,
required this.contentHTML,
required this.contentText});
factory NoticeBoardItem.fromJson(Map<String, dynamic> json) {
return NoticeBoardItem(
uid: json['Uid'],
author: json['RogzitoNeve'],
validFrom: DateTime.parse(json['ErvenyessegKezdete']),
validTo: DateTime.parse(json['ErvenyessegVege']),
title: json['Cim'],
contentHTML: json['Tartalom'],
contentText: json['TartalomText']);
}
@override
String toString() {
return 'NoticeBoardItem('
'uid: "$uid", '
'author: "$author", '
'validFrom: "$validFrom", '
'validTo: "$validTo", '
'title: "$title", '
'contentHTML: "$contentHTML", '
'contentText: "$contentText"'
')';
}
}

View File

@@ -0,0 +1,98 @@
import 'package:firka_wear/helpers/api/model/generic.dart';
import 'package:firka_wear/helpers/api/model/subject.dart';
class Omission {
final String uid;
final Subject subject;
final Class? c;
final DateTime date;
final String teacher;
final NameUidDesc? type;
final NameUidDesc? mode;
final int? lateForMin;
final DateTime createdAt;
final String state;
final NameUidDesc proofType;
final UidObj? classGroup;
Omission({
required this.uid,
required this.subject,
required this.c,
required this.date,
required this.teacher,
this.type,
this.mode,
this.lateForMin,
required this.createdAt,
required this.state,
required this.proofType,
this.classGroup,
});
factory Omission.fromJson(Map<String, dynamic> json) {
return Omission(
uid: json['Uid'],
subject: Subject.fromJson(json['Tantargy']),
c: json['Osztaly'] != null ? Class.fromJson(json['Osztaly']) : null,
date: DateTime.parse(json['Datum']),
teacher: json['RogzitoTanarNeve'],
type: json['Tipus'] != null ? NameUidDesc.fromJson(json['Tipus']) : null,
mode: json['Mod'] != null ? NameUidDesc.fromJson(json['Mod']) : null,
lateForMin: json['KesesPercben'],
createdAt: DateTime.parse(json['KeszitesDatuma']),
state: json['IgazolasAllapota'],
proofType: NameUidDesc.fromJson(json['IgazolasTipusa']),
classGroup: json['OsztalyCsoport'] != null
? UidObj.fromJson(json['OsztalyCsoport'])
: null,
);
}
@override
String toString() {
return 'Omission('
'uid: "$uid", '
'subject: $subject, '
'c: $c, '
'date: $date, '
'teacher: "$teacher", '
'type: $type, '
'mode: $mode, '
'lateForMin: $lateForMin, '
'createdAt: $createdAt, '
'state: "$state", '
'proofType: $proofType, '
'classGroup: $classGroup'
')';
}
}
class Class {
final DateTime start;
final DateTime end;
final int classNo;
Class({
required this.start,
required this.end,
required this.classNo,
});
factory Class.fromJson(Map<String, dynamic> json) {
return Class(
start: DateTime.parse(json['KezdoDatum']),
end: DateTime.parse(json['VegDatum']),
classNo: json['Oraszam'],
);
}
@override
String toString() {
return 'Class('
'start: "$start", '
'end: "$end", '
'classNo: $classNo'
')';
}
}

View File

@@ -0,0 +1,133 @@
/*
Firka, alternative e-Kréta client.
Copyright (C) 2025 QwIT Development
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'package:firka_wear/helpers/api/model/guardian.dart';
import 'package:firka_wear/helpers/api/model/institution.dart';
import 'package:firka_wear/helpers/json_helper.dart';
import 'package:intl/intl.dart';
class Student {
final List<String> addressDataList;
final BankAccount bankAccount;
// final int yearOfBirth;
// final int monthOfBirth;
// final int dayOfBirth;
final DateTime birthdate;
final String? emailAddress;
final String name;
final String? phoneNumber;
final String schoolYearUID;
final String uid;
final List<Guardian> guardianList;
final String instituteCode;
final String instituteName;
final Institution institution;
Student(
{required this.addressDataList,
required this.bankAccount,
// required this.yearOfBirth,
// required this.monthOfBirth,
// required this.dayOfBirth,
required this.birthdate,
required this.emailAddress,
required this.name,
required this.phoneNumber,
required this.schoolYearUID,
required this.uid,
required this.guardianList,
required this.instituteCode,
required this.instituteName,
required this.institution});
factory Student.fromJson(Map<String, dynamic> json) {
var guardianList = List<Guardian>.empty(growable: true);
for (var item in json['Gondviselok']) {
guardianList.add(Guardian.fromJson(item));
}
return Student(
addressDataList: listToTyped<String>(json['Cimek']),
bankAccount: BankAccount.fromJson(json['Bankszamla']),
birthdate: DateFormat('yyyy-M-d').parse(
"${json['SzuletesiEv']}-${json['SzuletesiHonap']}-${json['SzuletesiNap']}"),
emailAddress: json['EmailCim'],
name: json['Nev'],
phoneNumber: json['Telefonszam'],
schoolYearUID: json['TanevUid'],
uid: json['Uid'],
guardianList: guardianList,
instituteCode: json['IntezmenyAzonosito'],
instituteName: json['IntezmenyNev'],
institution: Institution.fromJson(json['Intezmeny']));
}
@override
String toString() {
return 'Student('
'addressDataList: [$addressDataList], '
'bankAccount: $bankAccount, '
'birthDate: $birthdate, '
'emailAddress: "$emailAddress", '
'name: "$name", '
'phoneNumber: "$phoneNumber", '
'schoolYearUID: "$schoolYearUID", '
'uid: "$uid", '
'guardianList: [$guardianList], '
'instituteCode: "$instituteCode", '
'instituteName: "$instituteName", '
')';
}
}
class BankAccount {
final String? accountNumber;
final bool? isReadOnly;
final String? ownerName;
final int? ownerType;
BankAccount(
{required this.accountNumber,
required this.isReadOnly,
required this.ownerName,
required this.ownerType});
factory BankAccount.fromJson(Map<String, dynamic> json) {
return BankAccount(
accountNumber: json['BankszamlaSzam'],
isReadOnly: json['IsReadOnly'],
ownerName: json['BankszamlaTulajdonosNeve'],
ownerType: json['BankszamlaTulajdonosTipusId']);
}
@override
String toString() {
return 'BankAccount('
'accountNumber: "$accountNumber", '
'isReadOnly: "$isReadOnly", '
'ownerName: "$ownerName", '
'ownerType: "$ownerType"'
')';
}
}

View File

@@ -0,0 +1,32 @@
import 'generic.dart';
class Subject {
final String uid;
final String name;
final NameUidDesc category;
final int sortIndex;
Subject(
{required this.uid,
required this.name,
required this.category,
required this.sortIndex});
factory Subject.fromJson(Map<String, dynamic> json) {
return Subject(
uid: json['Uid'],
name: json['Nev'],
category: NameUidDesc.fromJson(json['Kategoria']),
sortIndex: json['SortIndex']);
}
@override
String toString() {
return 'Subject('
'uid: "$uid", '
'name: "$name", '
'category: $category, '
'sortIndex: $sortIndex'
')';
}
}

View File

@@ -0,0 +1,60 @@
import 'package:firka_wear/helpers/api/model/subject.dart';
import 'generic.dart';
class Test {
final String uid;
final DateTime date;
final DateTime reportDate;
final String teacherName;
final int lessonNumber;
final Subject subject;
final String subjectName;
final String theme;
final NameUidDesc method;
final UidObj classGroup;
Test({
required this.uid,
required this.date,
required this.reportDate,
required this.teacherName,
required this.lessonNumber,
required this.subject,
required this.subjectName,
required this.theme,
required this.method,
required this.classGroup,
});
factory Test.fromJson(Map<String, dynamic> json) {
return Test(
uid: json['Uid'],
date: DateTime.parse(json['Datum']),
reportDate: DateTime.parse(json['BejelentesDatuma']),
teacherName: json['RogzitoTanarNeve'],
lessonNumber: json['OrarendiOraOraszama'],
subject: Subject.fromJson(json['Tantargy']),
subjectName: json['TantargyNeve'],
theme: json['Temaja'],
method: NameUidDesc.fromJson(json['Modja']),
classGroup: UidObj.fromJson(json['OsztalyCsoport']),
);
}
@override
String toString() {
return 'Test('
'uid: "$uid", '
'date: $date, '
'reportDate: $reportDate, '
'teacherName: "$teacherName", '
'lessonNumber: $lessonNumber, '
'subject: $subject, '
'subjectName: "$subjectName", '
'theme: "$theme", '
'method: $method, '
'classGroup: $classGroup'
')';
}
}

View File

@@ -0,0 +1,149 @@
import 'package:firka_wear/helpers/api/model/generic.dart';
import 'package:firka_wear/helpers/api/model/subject.dart';
class Lesson {
final String uid;
final String date;
final DateTime start;
final DateTime end;
final String name;
final int? lessonNumber;
final int? lessonSeqNumber;
final NameUid? classGroup;
final String? teacher;
final Subject? subject;
final String? theme;
final String? roomName;
final NameUidDesc type;
final NameUidDesc? studentPresence;
final NameUidDesc state;
final String? substituteTeacher;
final String? homeworkUid;
final String? taskGroupUid;
final String? languageTaskGroupUid;
final String? assessmentUid;
final bool canStudentEditHomework;
final bool isHomeworkComplete;
final List<NameUid> attachments;
final bool isDigitalLesson;
final String? digitalDeviceList;
final String? digitalPlatformType;
final List<String> digitalSupportDeviceTypeList;
final DateTime createdAt;
final DateTime lastModifiedAt;
Lesson({
required this.uid,
required this.date,
required this.start,
required this.end,
required this.name,
this.lessonNumber,
this.lessonSeqNumber,
this.classGroup,
this.teacher,
this.subject,
this.theme,
this.roomName,
required this.type,
this.studentPresence,
required this.state,
this.substituteTeacher,
this.homeworkUid,
this.taskGroupUid,
this.languageTaskGroupUid,
this.assessmentUid,
required this.canStudentEditHomework,
required this.isHomeworkComplete,
required this.attachments,
required this.isDigitalLesson,
this.digitalDeviceList,
this.digitalPlatformType,
required this.digitalSupportDeviceTypeList,
required this.createdAt,
required this.lastModifiedAt,
});
factory Lesson.fromJson(Map<String, dynamic> json) {
var attachments = List<NameUid>.empty(growable: true);
var rawAttachments = json['Csatolmanyok'];
for (var attachment in rawAttachments) {
attachments.add(NameUid.fromJson(attachment));
}
return Lesson(
uid: json['Uid'],
date: json['Datum'],
start: DateTime.parse(json['KezdetIdopont']),
end: DateTime.parse(json['VegIdopont']),
name: json['Nev'],
lessonNumber: json['Oraszam'],
lessonSeqNumber: json['OraEvesSorszama'],
classGroup: json['OsztalyCsoport'] != null
? NameUid.fromJson(json['OsztalyCsoport'])
: null,
teacher: json['TanarNeve'],
subject:
json['Tantargy'] != null ? Subject.fromJson(json['Tantargy']) : null,
theme: json['Tema'],
roomName: json['TeremNeve'],
type: NameUidDesc.fromJson(json['Tipus']),
studentPresence: json['TanuloJelenlet'] != null
? NameUidDesc.fromJson(json['TanuloJelenlet'])
: null,
state: NameUidDesc.fromJson(json['Allapot']),
substituteTeacher: json['HelyettesTanarNeve'],
homeworkUid: json['HaziFeladatUid'],
taskGroupUid: json['FeladatGroupUid'],
languageTaskGroupUid: json['NyelviFeladatGroupUid'],
assessmentUid: json['BejelentettSzamonkeresUid'],
canStudentEditHomework: json['IsTanuloHaziFeladatEnabled'],
isHomeworkComplete: json['IsHaziFeladatMegoldva'],
attachments: attachments,
isDigitalLesson: json['IsDigitalisOra'],
digitalDeviceList: json['DigitalisEszkozTipus'],
digitalPlatformType: json['DigitalisPlatformTipus'],
digitalSupportDeviceTypeList:
json['DigitalisTamogatoEszkozTipusList'] != null
? List<String>.from(json['DigitalisTamogatoEszkozTipusList'])
: List<String>.empty(),
createdAt: DateTime.parse(json['Letrehozas']),
lastModifiedAt: DateTime.parse(json['UtolsoModositas']),
);
}
@override
String toString() {
return 'Lesson('
'uid: "$uid", '
'date: "$date", '
'start: $start, '
'end: $end, '
'name: "$name", '
'lessonNumber: $lessonNumber, '
'lessonSeqNumber: $lessonSeqNumber, '
'classGroup: $classGroup, '
'teacher: "$teacher", '
'subject: $subject, '
'theme: "$theme", '
'roomName: "$roomName", '
'type: $type, '
'studentPresence: $studentPresence, '
'state: $state, '
'substituteTeacher: "$substituteTeacher", '
'homeworkUid: "$homeworkUid", '
'taskGroupUid: "$taskGroupUid", '
'languageTaskGroupUid: "$languageTaskGroupUid", '
'assessmentUid: "$assessmentUid", '
'canStudentEditHomework: $canStudentEditHomework, '
'isHomeworkComplete: $isHomeworkComplete, '
'attachments: $attachments, '
'isDigitalLesson: $isDigitalLesson, '
'digitalDeviceList: "$digitalDeviceList", '
'digitalPlatformType: "$digitalPlatformType", '
'digitalSupportDeviceTypeList: $digitalSupportDeviceTypeList, '
'create: $createdAt, '
'lastModified: $lastModifiedAt'
')';
}
}

View File

@@ -0,0 +1,54 @@
/*
Firka, alternative e-Kréta client.
Copyright (C) 2025 QwIT Development
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
class TokenGrantResponse {
final String idToken;
final String accessToken;
final int expiresIn;
final String tokenType;
final String refreshToken;
final String scope;
TokenGrantResponse(
{required this.idToken,
required this.accessToken,
required this.expiresIn,
required this.tokenType,
required this.refreshToken,
required this.scope});
factory TokenGrantResponse.fromJson(Map<String, dynamic> json) {
return TokenGrantResponse(
idToken: json['id_token'],
accessToken: json['access_token'],
expiresIn: json['expires_in'],
tokenType: json['token_type'],
refreshToken: json['refresh_token'],
scope: json['scope']);
}
@override
String toString() {
return 'TokenGrant(idToken: "$idToken", accessToken: "$accessToken", '
'expiresIn: $expiresIn, '
'tokenType: "$tokenType", '
'refreshToken: "$refreshToken", '
'scope: "$scope"'
')';
}
}

View File

@@ -0,0 +1,90 @@
/*
Firka, alternative e-Kréta client.
Copyright (C) 2025 QwIT Development
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'package:dio/dio.dart';
import 'package:firka_wear/helpers/api/resp/token_grant.dart';
import 'package:firka_wear/helpers/db/models/token_model.dart';
import '../../main.dart';
import 'consts.dart';
Future<TokenGrantResponse> getAccessToken(String code) async {
final headers = const <String, String>{
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"accept": "*/*",
"user-agent": "eKretaStudent/264745 CFNetwork/1494.0.7 Darwin/23.4.0",
};
final formData = <String, String>{
"code": code,
"code_verifier": "DSpuqj_HhDX4wzQIbtn8lr8NLE5wEi1iVLMtMK0jY6c",
"redirect_uri":
"https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect",
"client_id": Constants.clientId,
"grant_type": "authorization_code",
};
try {
final response = await dio.post(KretaEndpoints.tokenGrantUrl,
options: Options(headers: headers), data: formData);
switch (response.statusCode) {
case 200:
return TokenGrantResponse.fromJson(response.data);
case 401:
throw Exception("Invalid grant");
default:
throw Exception(
"Failed to get access token, response code: ${response.statusCode}");
}
} catch (e) {
rethrow;
}
}
Future<TokenGrantResponse> extendToken(TokenModel model) async {
final headers = const <String, String>{
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"accept": "*/*",
"user-agent": "eKretaStudent/264745 CFNetwork/1494.0.7 Darwin/23.4.0",
};
final formData = <String, String>{
"institute_code": model.iss!,
"refresh_token": model.refreshToken!,
"grant_type": "refresh_token",
"client_id": Constants.clientId,
};
try {
final response = await dio.post(KretaEndpoints.tokenGrantUrl,
options: Options(headers: headers), data: formData);
switch (response.statusCode) {
case 200:
return TokenGrantResponse.fromJson(response.data);
case 401:
throw Exception("Invalid grant");
default:
throw Exception(
"Failed to get access token, response code: ${response.statusCode}");
}
} catch (e) {
rethrow;
}
}

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