Working SSE
This commit is contained in:
S1m 2021-11-22 09:27:58 +01:00
commit 993ffaf8f9
55 changed files with 1904 additions and 0 deletions

7
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,7 @@
version: 2
updates:
- package-ecosystem: gradle
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10

38
.github/workflows/main.yml vendored Normal file
View File

@ -0,0 +1,38 @@
on: [push, pull_request]
name: Build
jobs:
check:
name: Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v1
with:
java-version: 11
- run: ./gradlew build --stacktrace
- uses: actions/upload-artifact@v2
with:
name: build
path: app/build/outputs/apk/debug/app-debug.apk
- if: startsWith(github.ref, 'refs/tags/')
run: |
cd app/build/outputs/apk/release
echo $RELEASE_KEY | base64 -d > release-key.jks
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore release-key.jks -storepass $STOREPASS -keypass $KEYPASS app-release-unsigned.apk nextpush
jarsigner -verify app-release-unsigned.apk
sudo apt-get install zipalign -y
zipalign -v 4 app-release-unsigned.apk nextpush.apk
env:
RELEASE_KEY: ${{ secrets.RELEASE_KEY }}
KEYPASS: ${{ secrets.KEYPASS }}
STOREPASS: ${{ secrets.STOREPASS }}
- if: startsWith(github.ref, 'refs/tags/')
uses: svenstaro/upload-release-action@v2
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: app/build/outputs/apk/release/nextpush.apk
tag: ${{ github.ref }}
overwrite: true

15
.gitignore vendored Normal file
View File

@ -0,0 +1,15 @@
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties

1
app/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build

68
app/build.gradle Normal file
View File

@ -0,0 +1,68 @@
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
configurations.all {
resolutionStrategy {
force 'androidx.core:core-ktx:1.6.0'
force 'androidx.core:core:1.6.0'
}
}
defaultConfig {
applicationId "org.unifiedpush.distributor.nextpush"
minSdkVersion 24
targetSdkVersion 30
versionCode 1
versionName "0.0.1"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
resValue "string", "app_name", "NextPush"
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
resValue "string", "app_name", "NextPush-dbg"
applicationIdSuffix ".debug"
debuggable true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
packagingOptions {
exclude("META-INF/*")
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
implementation(platform("com.squareup.okhttp3:okhttp-bom:4.9.1"))
implementation("com.squareup.okhttp3:okhttp")
implementation("com.squareup.okhttp3:logging-interceptor")
implementation("com.squareup.okhttp3:okhttp-sse")
implementation 'com.github.nextcloud:Android-SingleSignOn:0.6.0'
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "com.squareup.retrofit2:adapter-rxjava2:2.9.0"
}

21
app/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.unifiedpush.distributor.nextpush" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.NextPush"
android:networkSecurityConfig="@xml/network_security_config">
<activity
android:name=".activities.SettingsActivity"
android:label="@string/action_settings"
android:parentActivityName=".activities.MainActivity" />
<activity
android:name=".activities.MainActivity"
android:label="@string/app_name"
android:theme="@style/Theme.NextPush.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".services.StartService"
android:enabled="true" />
<receiver
android:name=".receivers.StartReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver
android:name=".receivers.RegisterBroadcastReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="org.unifiedpush.android.distributor.REGISTER" />
<action android:name="org.unifiedpush.android.distributor.UNREGISTER" />
</intent-filter>
</receiver>
</application>
</manifest>

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -0,0 +1,61 @@
package org.unifiedpush.distributor.nextpush.account
import android.app.Activity
import android.content.Context
import android.util.Log
import com.nextcloud.android.sso.AccountImporter
import com.nextcloud.android.sso.exceptions.AndroidGetAccountsPermissionNotGranted
import com.nextcloud.android.sso.exceptions.NextcloudFilesAppAccountNotFoundException
import com.nextcloud.android.sso.exceptions.NextcloudFilesAppNotInstalledException
import com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException
import com.nextcloud.android.sso.helper.SingleAccountHelper
import com.nextcloud.android.sso.model.SingleSignOnAccount
import com.nextcloud.android.sso.ui.UiExceptionManager
private const val TAG = "AccountUtils"
const val PREF_NAME = "NextPush"
const val PREF_DEVICE_ID = "deviceId"
lateinit var ssoAccount: SingleSignOnAccount
fun isConnected(context: Context) : Boolean {
try {
ssoAccount = SingleAccountHelper.getCurrentSingleSignOnAccount(context)
} catch (e: NextcloudFilesAppAccountNotFoundException) {
UiExceptionManager.showDialogForException(context, e)
} catch (e: NoCurrentAccountSelectedException) {
Log.d(TAG,"Device is not connected")
return false
}
return true
}
fun connect(activity: Activity) {
try {
AccountImporter.pickNewAccount(activity)
} catch (e: NextcloudFilesAppNotInstalledException) {
UiExceptionManager.showDialogForException(activity, e)
} catch (e: AndroidGetAccountsPermissionNotGranted) {
UiExceptionManager.showDialogForException(activity, e)
}
}
fun saveDeviceId(context: Context, deviceId: String) {
context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
.edit()
.putString(PREF_DEVICE_ID, deviceId)
.commit()
}
fun getDeviceId(context: Context) : String? {
return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
.getString(PREF_DEVICE_ID,null)
}
fun removeDeviceId(context: Context) {
context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
.edit()
.remove(PREF_DEVICE_ID)
.commit()
}

View File

@ -0,0 +1,220 @@
package org.unifiedpush.distributor.nextpush.activities
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.nextcloud.android.sso.AccountImporter
import com.nextcloud.android.sso.ui.UiExceptionManager
import org.unifiedpush.distributor.nextpush.services.StartService
import com.nextcloud.android.sso.AccountImporter.IAccountAccessGranted
import com.nextcloud.android.sso.api.NextcloudAPI.ApiConnectedListener
import com.nextcloud.android.sso.helper.SingleAccountHelper
import com.nextcloud.android.sso.model.SingleSignOnAccount
import java.lang.Exception
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import com.nextcloud.android.sso.AccountImporter.clearAllAuthTokens
import com.nextcloud.android.sso.exceptions.*
import org.unifiedpush.distributor.nextpush.R
import org.unifiedpush.distributor.nextpush.account.isConnected
import org.unifiedpush.distributor.nextpush.account.connect
import org.unifiedpush.distributor.nextpush.account.ssoAccount
import org.unifiedpush.distributor.nextpush.api.ApiUtils
import org.unifiedpush.distributor.nextpush.distributor.sendUnregistered
import org.unifiedpush.distributor.nextpush.distributor.MessagingDatabase
import java.lang.String.format
const val TAG = "NextPush-MainActivity"
class MainActivity : AppCompatActivity() {
private lateinit var listView : ListView
private var showLogout = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById(R.id.toolbar))
if (isConnected(this)) {
showMain()
} else {
findViewById<Button>(R.id.button_connection).setOnClickListener {
connect(this)
}
showStart()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
try {
AccountImporter.onActivityResult(
requestCode,
resultCode,
data,
this,
object : IAccountAccessGranted {
var callback: ApiConnectedListener = object : ApiConnectedListener {
override fun onConnected() {}
override fun onError(ex: Exception) {
Log.e(TAG, "Cannot get account access", ex)
}
}
override fun accountAccessGranted(account: SingleSignOnAccount) {
val context = applicationContext
// As this library supports multiple accounts we created some helper methods if you only want to use one.
// The following line stores the selected account as the "default" account which can be queried by using
// the SingleAccountHelper.getCurrentSingleSignOnAccount(context) method
SingleAccountHelper.setCurrentAccount(context, account.name)
// Get the "default" account
try {
ssoAccount = SingleAccountHelper.getCurrentSingleSignOnAccount(context)
} catch (e: NextcloudFilesAppAccountNotFoundException) {
UiExceptionManager.showDialogForException(context, e)
} catch (e: NoCurrentAccountSelectedException) {
UiExceptionManager.showDialogForException(context, e)
}
showMain()
}
})
} catch (e: AccountImportCancelledException) {}
}
private fun showMain() {
findViewById<ConstraintLayout>(R.id.sub_start).isVisible = false
findViewById<ConstraintLayout>(R.id.sub_main).isVisible = true
findViewById<TextView>(R.id.main_account_desc).text =
format(getString(R.string.main_account_desc), ssoAccount.name)
showLogout = true
invalidateOptionsMenu()
startListener()
}
private fun showStart() {
findViewById<ConstraintLayout>(R.id.sub_start).isVisible = true
findViewById<ConstraintLayout>(R.id.sub_main).isVisible = false
showLogout = false
invalidateOptionsMenu()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if(hasFocus) {
setListView()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
menu.findItem(R.id.action_logout).isVisible = showLogout
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> {
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
return true
}
R.id.action_restart -> {
restart()
return true
}
R.id.action_logout -> {
logout()
return true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun restart() {
Log.d(TAG, "Restarting the Listener")
val serviceIntent = Intent(this, StartService::class.java)
this.stopService(serviceIntent)
startListener()
}
private fun logout() {
val alert: android.app.AlertDialog.Builder = android.app.AlertDialog.Builder(
this)
alert.setTitle(getString(R.string.logout_alert_title))
alert.setMessage(R.string.logout_alert_content)
alert.setPositiveButton(R.string.ok) { dialog, _ ->
dialog.dismiss()
clearAllAuthTokens(this)
AccountImporter.getSharedPreferences(this)
.edit()
.remove("PREF_CURRENT_ACCOUNT_STRING")
.apply()
ApiUtils().deleteDevice(this)
showStart()
finish();
startActivity(intent);
}
alert.setNegativeButton(getString(R.string.discard)) { dialog, _ -> dialog.dismiss() }
alert.show()
}
private fun startListener(){
Log.d(TAG, "Starting the Listener")
val serviceIntent = Intent(this, StartService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
this.startForegroundService(serviceIntent)
}else{
this.startService(serviceIntent)
}
}
private fun setListView(){
listView = findViewById<ListView>(R.id.applications_list)
val db = MessagingDatabase(this)
val tokenList = db.listTokens().toMutableList()
val appList = emptyArray<String>().toMutableList()
tokenList.forEach {
appList.add(db.getPackageName(it))
}
db.close()
listView.adapter = ArrayAdapter(
this,
android.R.layout.simple_list_item_1,
appList
)
listView.setOnItemLongClickListener(
fun(parent: AdapterView<*>, v: View, position: Int, id: Long): Boolean {
val alert: android.app.AlertDialog.Builder = android.app.AlertDialog.Builder(
this)
alert.setTitle("Unregistering")
alert.setMessage("Are you sure to unregister ${appList[position]} ?")
alert.setPositiveButton("YES") { dialog, _ ->
sendUnregistered(this, tokenList[position])
val db = MessagingDatabase(this)
db.unregisterApp(tokenList[position])
db.close()
tokenList.removeAt(position)
appList.removeAt(position)
dialog.dismiss()
}
alert.setNegativeButton("NO") { dialog, _ -> dialog.dismiss() }
alert.show()
return true
}
)
}
}

View File

@ -0,0 +1,48 @@
package org.unifiedpush.distributor.nextpush.activities
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import org.unifiedpush.distributor.nextpush.R
import org.unifiedpush.distributor.nextpush.distributor.MessagingDatabase
import org.unifiedpush.distributor.nextpush.distributor.getEndpoint
import org.unifiedpush.distributor.nextpush.distributor.sendEndpoint
class SettingsActivity : AppCompatActivity() {
private var prefs: SharedPreferences? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
prefs = getSharedPreferences("Config", Context.MODE_PRIVATE)
setContentView(R.layout.activity_settings)
val address = prefs?.getString("address", "")
val proxy = prefs?.getString("proxy", "")
findViewById<EditText>(R.id.settings_address_value).setText(address)
findViewById<EditText>(R.id.settings_proxy_value).setText(proxy)
val btn = findViewById<View>(R.id.settings_save_button)
btn.setOnClickListener { v -> save(v) }
}
fun save(view: View){
val address = findViewById<EditText>(R.id.settings_address_value).text.toString()
val proxy = findViewById<EditText>(R.id.settings_proxy_value).text.toString()
Log.i("save",address)
val editor = prefs!!.edit()
editor.putString("address", address)
editor.putString("proxy", proxy)
editor.commit()
val db = MessagingDatabase(this)
val tokenList = db.listTokens()
db.close()
tokenList.forEach {
sendEndpoint(this, it, getEndpoint(this, it))
}
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}

View File

@ -0,0 +1,7 @@
package org.unifiedpush.distributor.nextpush.api
data class ApiResponse(
val success: Boolean = false,
val deviceId: String = "",
val token: String = "",
)

View File

@ -0,0 +1,163 @@
package org.unifiedpush.distributor.nextpush.api
import android.content.Context
import android.os.Build
import android.util.Log
import com.google.gson.GsonBuilder
import com.nextcloud.android.sso.api.NextcloudAPI
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.sse.EventSource
import okhttp3.sse.EventSources
import org.unifiedpush.distributor.nextpush.account.getDeviceId
import org.unifiedpush.distributor.nextpush.account.removeDeviceId
import org.unifiedpush.distributor.nextpush.account.saveDeviceId
import org.unifiedpush.distributor.nextpush.account.ssoAccount
import org.unifiedpush.distributor.nextpush.api.ProviderApi.Companion.mApiEndpoint
import org.unifiedpush.distributor.nextpush.services.SSEListener
import retrofit2.NextcloudRetrofitApiBuilder
import java.util.concurrent.TimeUnit
private const val TAG = "ApiUtils"
class ApiUtils {
private lateinit var mApi: ProviderApi
private lateinit var nextcloudAPI: NextcloudAPI
private lateinit var factory: EventSource.Factory
fun destroy() {
if (this::nextcloudAPI.isInitialized)
nextcloudAPI.stop()
}
private fun cApi(context: Context, callback: ()->Unit) {
if (this::mApi.isInitialized and this::nextcloudAPI.isInitialized) {
callback()
} else {
val callback = object : NextcloudAPI.ApiConnectedListener {
override fun onConnected() {
Log.d(TAG, "Api connected.")
callback()
}
override fun onError(ex: Exception) {
Log.d(TAG, "Cannot connect to API: ex = [$ex]")
}
}
nextcloudAPI = NextcloudAPI(context, ssoAccount, GsonBuilder().create(), callback)
mApi = NextcloudRetrofitApiBuilder(nextcloudAPI, mApiEndpoint)
.create(ProviderApi::class.java)
}
}
fun sync(context: Context) {
cApi(context) { cSync(context) }
}
private fun cSync(context: Context) {
var deviceId = getDeviceId(context)
// Register the device if it is not yet registered
if (deviceId.isNullOrEmpty()) {
Log.d(TAG, "No deviceId found.")
val parameters: MutableMap<String, String> = HashMap()
parameters["deviceName"] = Build.MODEL
mApi.createDevice(parameters)
?.subscribeOn(Schedulers.newThread())
?.observeOn(Schedulers.newThread())
?.subscribe(object : Observer<ApiResponse?> {
override fun onSubscribe(d: Disposable) {
Log.d(TAG, "onSubscribe")
}
override fun onNext(response: ApiResponse) {
val deviceIdentifier: String = response.deviceId
Log.d(TAG, "Device Identifier: $deviceIdentifier")
saveDeviceId(context,deviceIdentifier)
deviceId = deviceIdentifier
}
override fun onError(e: Throwable) {
e.printStackTrace()
}
override fun onComplete() {
// Sync once it is registered
cSync(deviceId!!)
Log.d(TAG, "mApi register: onComplete")
}
})
} else {
// Sync directly
Log.d(TAG, "Found deviceId: $deviceId")
cSync(deviceId!!)
}
}
private fun cSync(deviceId: String) {
val client = OkHttpClient.Builder()
.readTimeout(0, TimeUnit.SECONDS)
.retryOnConnectionFailure(false)
.build()
val url = "${ssoAccount.url}$mApiEndpoint/device/$deviceId"
val request = Request.Builder().url(url)
.get()
.build()
factory = EventSources.createFactory(client)
factory.newEventSource(request, SSEListener())
Log.d(TAG, "doConnect done.")
}
fun deleteDevice(context: Context) {
cApi(context) { cDeleteDevice(context) }
}
private fun cDeleteDevice(context: Context) {
var deviceId = getDeviceId(context)
mApi.deleteDevice(deviceId)
?.subscribeOn(Schedulers.newThread())
?.observeOn(Schedulers.newThread())
?.subscribe(object : Observer<ApiResponse?> {
override fun onSubscribe(d: Disposable) {
Log.d(TAG, "Subscribed to deleteDevice.")
}
override fun onNext(response: ApiResponse) {
if (response.success) {
Log.d(TAG, "Device successfully deleted.")
} else {
Log.d(TAG, "An error occurred while deleting the device registration.")
}
}
override fun onError(e: Throwable) {
e.printStackTrace()
}
override fun onComplete() {
}
})
removeDeviceId(context)
}
fun createApp(context: Context) {
cApi(context) { cCreateApp(context) }
}
private fun cCreateApp(context: Context) {
}
fun deleteApp(context: Context) {
cApi(context) { cDeleteApp(context) }
}
private fun cDeleteApp(context: Context) {
}
}

View File

@ -0,0 +1,34 @@
package org.unifiedpush.distributor.nextpush.api
import io.reactivex.Observable;
import retrofit2.http.PUT
import retrofit2.http.GET
import retrofit2.http.DELETE
import retrofit2.http.Body
import retrofit2.http.Path
interface ProviderApi {
@PUT("/device/")
fun createDevice(
@Body subscribeMap: MutableMap<String, String>?
): Observable<ApiResponse>?
@GET("/device/{deviceId}")
fun syncDevice(@Path("deviceId") devideId: String?): Observable<SSEResponse?>?
@DELETE("/device/{deviceId}")
fun deleteDevice(@Path("deviceId") devideId: String?): Observable<ApiResponse>?
@PUT("/app/")
fun createApp(
@Body authorizeMap: MutableMap<String, String>?
): Observable<ApiResponse>?
@DELETE("/app/{token}")
fun deleteApp(@Path("token") token: String?): Observable<ApiResponse>?
companion object {
const val mApiEndpoint = "/index.php/apps/uppush"
}
}

View File

@ -0,0 +1,7 @@
package org.unifiedpush.distributor.nextpush.api
data class SSEResponse (
val type: String = "",
val token: String = "",
val message: String = ""
)

View File

@ -0,0 +1,66 @@
package org.unifiedpush.distributor.nextpush.distributor
import android.content.Context
import android.content.Intent
import android.util.Log
/**
* These functions are used to send messages to other apps
*/
fun sendMessage(context: Context, token: String, message: String){
val application = getApp(context, token)
if (application.isNullOrBlank()) {
return
}
val broadcastIntent = Intent()
broadcastIntent.`package` = application
broadcastIntent.action = ACTION_MESSAGE
broadcastIntent.putExtra(EXTRA_TOKEN, token)
broadcastIntent.putExtra(EXTRA_MESSAGE, message)
context.sendBroadcast(broadcastIntent)
}
fun sendEndpoint(context: Context, token: String, endpoint: String) {
val application = getApp(context, token)
if (application.isNullOrBlank()) {
return
}
val broadcastIntent = Intent()
broadcastIntent.`package` = application
broadcastIntent.action = ACTION_NEW_ENDPOINT
broadcastIntent.putExtra(EXTRA_TOKEN, token)
broadcastIntent.putExtra(EXTRA_ENDPOINT, endpoint)
context.sendBroadcast(broadcastIntent)
}
fun sendUnregistered(context: Context, token: String) {
val application = getApp(context, token)
if (application.isNullOrBlank()) {
return
}
val broadcastIntent = Intent()
broadcastIntent.`package` = application
broadcastIntent.action = ACTION_UNREGISTERED
broadcastIntent.putExtra(EXTRA_TOKEN, token)
context.sendBroadcast(broadcastIntent)
}
fun getApp(context: Context, token: String): String?{
val db = MessagingDatabase(context)
val app = db.getPackageName(token)
db.close()
return if (app.isBlank()) {
Log.w("notifyClient", "No app found for $token")
null
} else {
app
}
}
fun getEndpoint(context: Context, appToken: String): String {
val settings = context.getSharedPreferences("Config", Context.MODE_PRIVATE)
val address = settings?.getString("address","")
return settings?.getString("proxy","") +
"/foo/$appToken/"
}

View File

@ -0,0 +1,100 @@
package org.unifiedpush.distributor.nextpush.distributor
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
private const val DB_NAME = "apps_db"
private const val DB_VERSION = 1
class MessagingDatabase(context: Context):
SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
private val CREATE_TABLE_APPS = "CREATE TABLE apps (" +
"package_name TEXT," +
"token TEXT," +
"PRIMARY KEY (token));"
private val TABLE_APPS = "apps"
private val FIELD_PACKAGE_NAME = "package_name"
private val FIELD_TOKEN = "token"
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(CREATE_TABLE_APPS)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
throw IllegalStateException("Upgrades not supported")
}
fun registerApp(packageName: String, token: String) {
val db = writableDatabase
val values = ContentValues().apply {
put(FIELD_PACKAGE_NAME, packageName)
put(FIELD_TOKEN, token)
}
db.insert(TABLE_APPS, null, values)
}
fun unregisterApp(token: String) {
val db = writableDatabase
val selection = "$FIELD_TOKEN = ?"
val selectionArgs = arrayOf(token)
db.delete(TABLE_APPS, selection, selectionArgs)
}
fun isRegistered(packageName: String, token: String): Boolean {
val db = readableDatabase
val selection = "$FIELD_PACKAGE_NAME = ? AND $FIELD_TOKEN = ?"
val selectionArgs = arrayOf(packageName, token)
return db.query(
TABLE_APPS,
null,
selection,
selectionArgs,
null,
null,
null
).use { cursor ->
(cursor != null && cursor.count > 0)
}
}
fun getPackageName(token: String): String {
val db = readableDatabase
val projection = arrayOf(FIELD_PACKAGE_NAME)
val selection = "$FIELD_TOKEN = ?"
val selectionArgs = arrayOf(token)
return db.query(
TABLE_APPS,
projection,
selection,
selectionArgs,
null,
null,
null
).use { cursor ->
val column = cursor.getColumnIndex(FIELD_PACKAGE_NAME)
if (cursor.moveToFirst() && column >= 0) cursor.getString(column) else ""
}
}
fun listTokens(): List<String> {
val db = readableDatabase
val projection = arrayOf(FIELD_TOKEN)
return db.query(
TABLE_APPS,
projection,
null,
null,
null,
null,
null
).use{ cursor ->
generateSequence { if (cursor.moveToNext()) cursor else null }
.mapNotNull{
val column = cursor.getColumnIndex(FIELD_TOKEN)
if (column >= 0) it.getString(column) else null }
.toList()
}
}
}

View File

@ -0,0 +1,22 @@
package org.unifiedpush.distributor.nextpush.distributor
/**
* Constants as defined on the specs
* https://github.com/UnifiedPush/UP-spec/blob/main/specifications.md
*/
const val ACTION_NEW_ENDPOINT = "org.unifiedpush.android.connector.NEW_ENDPOINT"
const val ACTION_REGISTRATION_FAILED = "org.unifiedpush.android.connector.REGISTRATION_FAILED"
const val ACTION_REGISTRATION_REFUSED = "org.unifiedpush.android.connector.REGISTRATION_REFUSED"
const val ACTION_UNREGISTERED = "org.unifiedpush.android.connector.UNREGISTERED"
const val ACTION_MESSAGE = "org.unifiedpush.android.connector.MESSAGE"
const val ACTION_REGISTER = "org.unifiedpush.android.distributor.REGISTER"
const val ACTION_UNREGISTER = "org.unifiedpush.android.distributor.UNREGISTER"
const val ACTION_MESSAGE_ACK = "org.unifiedpush.android.distributor.MESSAGE_ACK"
const val EXTRA_APPLICATION = "application"
const val EXTRA_TOKEN = "token"
const val EXTRA_ENDPOINT = "endpoint"
const val EXTRA_MESSAGE = "message"
const val EXTRA_MESSAGE_ID = "id"

View File

@ -0,0 +1,65 @@
package org.unifiedpush.distributor.nextpush.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import org.unifiedpush.distributor.nextpush.distributor.*
import kotlin.concurrent.thread
/**
* THIS SERVICE IS USED BY OTHER APPS TO REGISTER
*/
class RegisterBroadcastReceiver : BroadcastReceiver() {
private fun unregisterApp(db: MessagingDatabase, application: String, token: String) {
Log.i("RegisterService","Unregistering $application token: $token")
db.unregisterApp(token)
}
private fun registerApp(context: Context?, db: MessagingDatabase, application: String, token: String) {
if (application.isBlank()) {
Log.w("RegisterService","Trying to register an app without packageName")
return
}
Log.i("RegisterService","registering $application token: $token")
// The app is registered with the same token : we re-register it
// the client may need its endpoint again
if (db.isRegistered(application, token)) {
Log.i("RegisterService","$application already registered")
return
}
db.registerApp(application, token)
}
override fun onReceive(context: Context?, intent: Intent?) {
when (intent!!.action) {
ACTION_REGISTER ->{
Log.i("Register","REGISTER")
val token = intent.getStringExtra(EXTRA_TOKEN)?: ""
val application = intent.getStringExtra(EXTRA_APPLICATION)?: ""
thread(start = true) {
val db = MessagingDatabase(context!!)
registerApp(context, db, application, token)
db.close()
Log.i("RegisterService","Registration is finished")
}.join()
sendEndpoint(context!!, token, getEndpoint(context, token))
}
ACTION_UNREGISTER ->{
Log.i("Register","UNREGISTER")
val token = intent.getStringExtra(EXTRA_TOKEN)?: ""
val application = intent.getStringExtra(EXTRA_APPLICATION)?: ""
thread(start = true) {
val db = MessagingDatabase(context!!)
unregisterApp(db,application, token)
db.close()
Log.i("RegisterService","Unregistration is finished")
}
sendUnregistered(context!!, token)
}
}
}
}

View File

@ -0,0 +1,23 @@
package org.unifiedpush.distributor.nextpush.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import org.unifiedpush.distributor.nextpush.services.StartService
class StartReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
Intent(context, StartService::class.java).also {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(it)
return
}
context.startService(it)
}
}
}
}

View File

@ -0,0 +1,55 @@
package org.unifiedpush.distributor.nextpush.services
import okhttp3.sse.EventSourceListener
import okhttp3.sse.EventSource
import android.util.Log
import okhttp3.Response
import java.lang.Exception
private const val TAG = "SSEListener"
class SSEListener : EventSourceListener() {
private var pingtime = 0.toLong()
private val networkConnected = false
override fun onOpen(eventSource: EventSource, response: Response) {
pingtime = System.currentTimeMillis()
try {
Log.d(TAG, "onOpen: " + response.code)
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onEvent(eventSource: EventSource, id: String?, eventType: String?, data: String) {
Log.d(TAG, "New SSE message event=$eventType message=$data")
pingtime = System.currentTimeMillis()
if (eventType == "warning") {
Log.d(TAG, "Warning event received.")
// Notification warning
}
if (eventType == "ping") {
Log.d(TAG, "SSE ping received.")
}
if (eventType != "notification") return
Log.d(TAG, "Notification event received.")
// handle notification
}
override fun onClosed(eventSource: EventSource) {
Log.d(TAG, "onClosed: $eventSource")
if (!networkConnected) return
}
override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
t?.let {
Log.d(TAG, "An error occurred: $t")
return
}
response?.let {
Log.d(TAG, "onFailure: ${it.code}")
if (!networkConnected) return
return
}
}
}

View File

@ -0,0 +1,106 @@
package org.unifiedpush.distributor.nextpush.services
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.util.Log
import com.nextcloud.android.sso.exceptions.NextcloudFilesAppAccountNotFoundException
import com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException
import com.nextcloud.android.sso.helper.SingleAccountHelper
import com.nextcloud.android.sso.ui.UiExceptionManager
import org.unifiedpush.distributor.nextpush.R
import org.unifiedpush.distributor.nextpush.api.ApiUtils
import org.unifiedpush.distributor.nextpush.account.ssoAccount
private const val TAG = "StartService"
class StartService: Service(){
private var isServiceStarted = false
private var wakeLock: PowerManager.WakeLock? = null
private var api = ApiUtils()
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onCreate(){
super.onCreate()
Log.i(TAG,"Starting")
val notification = createNotification()
startForeground(51115, notification)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startService()
// by returning this we make sure the service is restarted if the system kills the service
return START_STICKY
}
override fun onDestroy() {
api.destroy()
super.onDestroy()
}
private fun createNotification(): Notification {
val appName = getString(R.string.app_name)
val notificationChannelId = "$appName.Listener"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager;
val channel = NotificationChannel(
notificationChannelId,
appName,
NotificationManager.IMPORTANCE_LOW
).let {
it.description = getString(R.string.listening_notif_description)
it
}
notificationManager.createNotificationChannel(channel)
}
val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(
this,
notificationChannelId
) else Notification.Builder(this)
return builder
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.listening_notif_description))
.setSmallIcon(R.drawable.ic_launcher_notification)
.setTicker("Listening")
.setPriority(Notification.PRIORITY_LOW) // for under android 26 compatibility
.build()
}
private fun startService() {
if (isServiceStarted) return
isServiceStarted = true
try {
ssoAccount = SingleAccountHelper.getCurrentSingleSignOnAccount(this)
} catch (e: NextcloudFilesAppAccountNotFoundException) {
UiExceptionManager.showDialogForException(this, e)
} catch (e: NoCurrentAccountSelectedException) {
return
}
// we need this lock so our service gets not affected by Doze Mode
wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "EndlessService::lock").apply {
acquire()
}
}
api.sync(this)
}
}

View File

@ -0,0 +1,20 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<group android:scaleX="4.2519684"
android:scaleY="4.2519684"
android:translateX="27"
android:translateY="27">
<path
android:pathData="M6.35,0.7937A5.5563,5.5563 0,0 0,0.7937 6.35,5.5563 5.5563,0 0,0 6.35,11.9063 5.5563,5.5563 0,0 0,11.9063 6.35,5.5563 5.5563,0 0,0 6.35,0.7937ZM6.35,2.1167A4.2333,4.2333 0,0 1,10.5833 6.35,4.2333 4.2333,0 0,1 6.35,10.5833 4.2333,4.2333 0,0 1,2.1167 6.35,4.2333 4.2333,0 0,1 6.35,2.1167Z"
android:strokeWidth="0.291905"
android:fillColor="#ffffff"/>
<path
android:pathData="M9.4115,7.816H3.2885L6.35,4.9012Z"
android:strokeWidth="0.0907924"
android:fillColor="#ffffff"
android:strokeColor="#ffffff"/>
</group>
</vector>

View File

@ -0,0 +1,20 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<group android:scaleX="8"
android:scaleY="8"
android:translateX="8"
android:translateY="8">
<path
android:pathData="M6.35,0.7937A5.5563,5.5563 0,0 0,0.7937 6.35,5.5563 5.5563,0 0,0 6.35,11.9063 5.5563,5.5563 0,0 0,11.9063 6.35,5.5563 5.5563,0 0,0 6.35,0.7937ZM6.35,2.1167A4.2333,4.2333 0,0 1,10.5833 6.35,4.2333 4.2333,0 0,1 6.35,10.5833 4.2333,4.2333 0,0 1,2.1167 6.35,4.2333 4.2333,0 0,1 6.35,2.1167Z"
android:strokeWidth="0.291905"
android:fillColor="#ffffff"/>
<path
android:pathData="M9.4115,7.816H3.2885L6.35,4.9012Z"
android:strokeWidth="0.0907924"
android:fillColor="#ffffff"
android:strokeColor="#ffffff"/>
</group>
</vector>

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="org.unifiedpush.distributor.nextpush.activities.MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/Theme.NextPush.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/Theme.NextPush.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include
android:id="@+id/sub_main"
layout="@layout/content_main" />
<include
android:id="@+id/sub_start"
layout="@layout/content_start" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View File

@ -0,0 +1,110 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="org.unifiedpush.distributor.nextpush.activities.SettingsActivity">
<TextView
android:id="@+id/settings_address_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="@string/settings_address_label"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/settings_address_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:hint="@string/settings_address_hint"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<TextView
android:id="@+id/settings_address_help"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="32dp"
android:clickable="true"
android:focusable="true"
android:text="@string/help"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
app:layout_constraintBottom_toBottomOf="@+id/settings_address_value"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/settings_address_value" />
<TextView
android:id="@+id/settings_gateway_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="@string/settings_gateway_label"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/settings_address_value" />
<EditText
android:id="@+id/settings_proxy_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:hint="@string/settings_gateway_hint"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
<Button
android:id="@+id/settings_save_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="@string/settings_save_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/settings_proxy_value" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:text="@string/settings_address_information"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/settings_address_label" />
<TextView
android:id="@+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:text="@string/settings_gateway_information"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/settings_gateway_label" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:id="@+id/main_account_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:text="@string/main_account_title"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/main_account_desc"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:text="@string/main_account_desc"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/main_account_title" />
<TextView
android:id="@+id/main_applications_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="@string/main_applications_title"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/main_account_desc" />
<ListView
android:id="@+id/applications_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/main_applications_title" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>