This commit is contained in:
Grishka 2022-01-14 15:02:10 +03:00
commit 42d5f52ff5
55 changed files with 2815 additions and 0 deletions

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
*.iml
.gradle
/local.properties
/.idea
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties

17
build.gradle Normal file
View File

@ -0,0 +1,17 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:7.0.4"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

19
gradle.properties Normal file
View File

@ -0,0 +1,19 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Thu Jan 13 11:33:43 MSK 2022
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

185
gradlew vendored Executable file
View File

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

1
mastodon/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build

38
mastodon/build.gradle Normal file
View File

@ -0,0 +1,38 @@
plugins {
id 'com.android.application'
}
android {
compileSdk 31
buildToolsVersion "32.0.0"
defaultConfig {
applicationId "org.joinmastodon.android"
minSdk 23
targetSdk 31
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_15
targetCompatibility JavaVersion.VERSION_15
coreLibraryDesugaringEnabled true
}
}
dependencies {
api 'androidx.annotation:annotation:1.3.0'
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
implementation 'me.grishka.litex:recyclerview:1.2.1'
implementation 'me.grishka.litex:swiperefreshlayout:1.1.0'
implementation 'me.grishka.litex:browser:1.4.0'
implementation 'me.grishka.appkit:appkit:1.0'
implementation 'com.google.code.gson:gson:2.8.9'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}

21
mastodon/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,31 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.joinmastodon.android">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name=".MastodonApp"
android:allowBackup="true"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Mastodon">
<activity android:name=".MainActivity" android:exported="true" android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".OAuthActivity" android:exported="true" android:configChanges="orientation|screenSize" android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="mastodon-android-auth" android:host="callback"/>
</intent-filter>
</activity>
</application>
</manifest>

View File

@ -0,0 +1,29 @@
package org.joinmastodon.android;
import android.os.Bundle;
import org.joinmastodon.android.api.session.AccountSessionManager;
import org.joinmastodon.android.fragments.HomeFragment;
import org.joinmastodon.android.fragments.SplashFragment;
import androidx.annotation.Nullable;
import me.grishka.appkit.FragmentStackActivity;
public class MainActivity extends FragmentStackActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(savedInstanceState==null){
if(AccountSessionManager.getInstance().getLoggedInAccounts().isEmpty()){
showFragmentClearingBackStack(new SplashFragment());
}else{
Bundle args=new Bundle();
args.putString("account", AccountSessionManager.getInstance().getLastActiveAccountID());
HomeFragment fragment=new HomeFragment();
fragment.setArguments(args);
showFragmentClearingBackStack(fragment);
}
}
}
}

View File

@ -0,0 +1,17 @@
package org.joinmastodon.android;
import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
public class MastodonApp extends Application{
@SuppressLint("StaticFieldLeak") // it's not a leak
public static Context context;
@Override
public void onCreate(){
super.onCreate();
context=getApplicationContext();
}
}

View File

@ -0,0 +1,103 @@
package org.joinmastodon.android;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import org.joinmastodon.android.api.requests.accounts.GetOwnAccount;
import org.joinmastodon.android.api.requests.oauth.GetOauthToken;
import org.joinmastodon.android.api.session.AccountSessionManager;
import org.joinmastodon.android.model.Account;
import org.joinmastodon.android.model.Application;
import org.joinmastodon.android.model.Instance;
import org.joinmastodon.android.model.Token;
import androidx.annotation.Nullable;
import me.grishka.appkit.api.Callback;
import me.grishka.appkit.api.ErrorResponse;
public class OAuthActivity extends Activity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Uri uri=getIntent().getData();
if(uri==null || isTaskRoot()){
finish();
return;
}
if(uri.getQueryParameter("error")!=null){
String error=uri.getQueryParameter("error_description");
if(TextUtils.isEmpty(error))
error=uri.getQueryParameter("error");
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
finish();
restartMainActivity();
return;
}
String code=uri.getQueryParameter("code");
if(TextUtils.isEmpty(code)){
finish();
return;
}
Instance instance=AccountSessionManager.getInstance().getAuthenticatingInstance();
Application app=AccountSessionManager.getInstance().getAuthenticatingApp();
if(instance==null || app==null){
finish();
return;
}
ProgressDialog progress=new ProgressDialog(this);
progress.setMessage(getString(R.string.finishing_auth));
progress.setCancelable(false);
progress.show();
new GetOauthToken(app.clientId, app.clientSecret, code)
.setCallback(new Callback<>(){
@Override
public void onSuccess(Token token){
new GetOwnAccount()
.setCallback(new Callback<>(){
@Override
public void onSuccess(Account account){
AccountSessionManager.getInstance().addAccount(instance, token, account, app);
progress.dismiss();
finish();
// not calling restartMainActivity() here on purpose to have it recreated (notice different flags)
Intent intent=new Intent(OAuthActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
@Override
public void onError(ErrorResponse error){
handleError(error);
progress.dismiss();
}
})
.exec(instance.uri, token);
}
@Override
public void onError(ErrorResponse error){
handleError(error);
progress.dismiss();
}
})
.execNoAuth(instance.uri);
}
private void handleError(ErrorResponse error){
error.showToast(OAuthActivity.this);
finish();
restartMainActivity();
}
private void restartMainActivity(){
Intent intent=new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
}

View File

@ -0,0 +1,11 @@
package org.joinmastodon.android.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AllFieldsAreRequired{
}

View File

@ -0,0 +1,35 @@
package org.joinmastodon.android.api;
import com.google.gson.JsonIOException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
public class JsonObjectRequestBody extends RequestBody{
private final Object obj;
public JsonObjectRequestBody(Object obj){
this.obj=obj;
}
@Override
public MediaType contentType(){
return MediaType.get("application/json;charset=utf-8");
}
@Override
public void writeTo(BufferedSink sink) throws IOException{
try{
OutputStreamWriter writer=new OutputStreamWriter(sink.outputStream(), StandardCharsets.UTF_8);
MastodonAPIController.gson.toJson(obj, writer);
writer.flush();
}catch(JsonIOException x){
throw new IOException(x);
}
}
}

View File

@ -0,0 +1,157 @@
package org.joinmastodon.android.api;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import org.joinmastodon.android.BuildConfig;
import org.joinmastodon.android.MastodonApp;
import org.joinmastodon.android.api.gson.IsoInstantTypeAdapter;
import org.joinmastodon.android.api.gson.IsoLocalDateTypeAdapter;
import org.joinmastodon.android.api.session.AccountSession;
import org.joinmastodon.android.model.BaseModel;
import java.io.IOException;
import java.io.Reader;
import java.time.Instant;
import java.time.LocalDate;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import me.grishka.appkit.utils.WorkerThread;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class MastodonAPIController{
private static final String TAG="MastodonAPIController";
public static final Gson gson=new GsonBuilder()
.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(Instant.class, new IsoInstantTypeAdapter())
.registerTypeAdapter(LocalDate.class, new IsoLocalDateTypeAdapter())
.create();
private static WorkerThread thread=new WorkerThread("MastodonAPIController");
private static OkHttpClient httpClient=new OkHttpClient.Builder().build();
private AccountSession session;
static{
thread.start();
}
public MastodonAPIController(@Nullable AccountSession session){
this.session=session;
}
public <T> void submitRequest(final MastodonAPIRequest<T> req){
thread.postRunnable(()->{
try{
Request.Builder builder=new Request.Builder()
.url(req.getURL().toString())
.method(req.getMethod(), req.getRequestBody())
.header("User-Agent", "MastodonAndroid/"+BuildConfig.VERSION_NAME);
String token=null;
if(session!=null)
token=session.token.accessToken;
else if(req.token!=null)
token=req.token.accessToken;
if(token!=null)
builder.header("Authorization", "Bearer "+token);
Request hreq=builder.build();
Call call=httpClient.newCall(hreq);
synchronized(req){
req.okhttpCall=call;
}
if(BuildConfig.DEBUG)
Log.d(TAG, "["+(session==null ? "no-auth" : session.getID())+"] Sending request: "+hreq);
call.enqueue(new Callback(){
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e){
if(call.isCanceled())
return;
if(BuildConfig.DEBUG)
Log.w(TAG, "["+(session==null ? "no-auth" : session.getID())+"] "+hreq+" failed: "+e);
synchronized(req){
req.okhttpCall=null;
}
req.onError(e.getLocalizedMessage());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException{
if(call.isCanceled())
return;
if(BuildConfig.DEBUG)
Log.d(TAG, "["+(session==null ? "no-auth" : session.getID())+"] "+hreq+" received response: "+response);
synchronized(req){
req.okhttpCall=null;
}
try(ResponseBody body=response.body()){
Reader reader=body.charStream();
if(response.isSuccessful()){
T respObj;
try{
if(req.respTypeToken!=null)
respObj=gson.fromJson(reader, req.respTypeToken.getType());
else
respObj=gson.fromJson(reader, req.respClass);
}catch(JsonIOException|JsonSyntaxException x){
if(BuildConfig.DEBUG)
Log.w(TAG, "["+(session==null ? "no-auth" : session.getID())+"] "+response+" error parsing or reading body", x);
req.onError(x.getLocalizedMessage());
return;
}
try{
req.validateAndPostprocessResponse(respObj);
}catch(IOException x){
if(BuildConfig.DEBUG)
Log.w(TAG, "["+(session==null ? "no-auth" : session.getID())+"] "+response+" error post-processing or validating response", x);
req.onError(x.getLocalizedMessage());
return;
}
if(BuildConfig.DEBUG)
Log.d(TAG, "["+(session==null ? "no-auth" : session.getID())+"] "+response+" parsed successfully: "+respObj);
req.onSuccess(respObj);
}else{
try{
JsonObject error=JsonParser.parseReader(reader).getAsJsonObject();
req.onError(error.get("error").getAsString());
}catch(JsonIOException|JsonSyntaxException x){
req.onError(response.code()+" "+response.message());
}catch(IllegalStateException x){
req.onError("Error parsing an API error");
}
}
}
}
});
}catch(Exception x){
if(BuildConfig.DEBUG)
Log.w(TAG, "["+(session==null ? "no-auth" : session.getID())+"] error creating and sending http request", x);
req.onError(x.getLocalizedMessage());
}
}, 0);
}
}

View File

@ -0,0 +1,147 @@
package org.joinmastodon.android.api;
import android.net.Uri;
import com.google.gson.reflect.TypeToken;
import org.joinmastodon.android.api.session.AccountSession;
import org.joinmastodon.android.api.session.AccountSessionManager;
import org.joinmastodon.android.model.BaseModel;
import org.joinmastodon.android.model.Token;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import androidx.annotation.CallSuper;
import me.grishka.appkit.api.APIRequest;
import me.grishka.appkit.api.Callback;
import okhttp3.Call;
import okhttp3.RequestBody;
public abstract class MastodonAPIRequest<T> extends APIRequest<T>{
private String domain;
private AccountSession account;
private String path;
private String method;
private Object requestBody;
private Map<String, String> queryParams;
Class<T> respClass;
TypeToken<T> respTypeToken;
Call okhttpCall;
Token token;
public MastodonAPIRequest(HttpMethod method, String path, Class<T> respClass){
this.path=path;
this.method=method.toString();
this.respClass=respClass;
}
public MastodonAPIRequest(HttpMethod method, String path, TypeToken<T> respTypeToken){
this.path=path;
this.method=method.toString();
this.respTypeToken=respTypeToken;
}
@Override
public synchronized void cancel(){
if(okhttpCall!=null){
okhttpCall.cancel();
}
}
@Override
public APIRequest<T> exec(){
throw new UnsupportedOperationException("Use exec(accountID) or execNoAuth(domain)");
}
public MastodonAPIRequest<T> exec(String accountID){
account=AccountSessionManager.getInstance().getAccount(accountID);
domain=account.domain;
account.getApiController().submitRequest(this);
return this;
}
public MastodonAPIRequest<T> execNoAuth(String domain){
this.domain=domain;
AccountSessionManager.getInstance().getUnauthenticatedApiController().submitRequest(this);
return this;
}
public MastodonAPIRequest<T> exec(String domain, Token token){
this.domain=domain;
this.token=token;
AccountSessionManager.getInstance().getUnauthenticatedApiController().submitRequest(this);
return this;
}
protected void setRequestBody(Object body){
requestBody=body;
}
protected void addQueryParameter(String key, String value){
if(queryParams==null)
queryParams=new HashMap<>();
queryParams.put(key, value);
}
protected String getPathPrefix(){
return "/api/v1";
}
public Uri getURL(){
Uri.Builder builder=new Uri.Builder()
.scheme("https")
.authority(domain)
.path(getPathPrefix()+path);
if(queryParams!=null){
for(Map.Entry<String, String> param:queryParams.entrySet()){
builder.appendQueryParameter(param.getKey(), param.getValue());
}
}
return builder.build();
}
public String getMethod(){
return method;
}
public RequestBody getRequestBody(){
return requestBody==null ? null : new JsonObjectRequestBody(requestBody);
}
@Override
public MastodonAPIRequest<T> setCallback(Callback<T> callback){
super.setCallback(callback);
return this;
}
@CallSuper
public void validateAndPostprocessResponse(T respObj) throws IOException{
if(respObj instanceof BaseModel){
((BaseModel) respObj).postprocess();
}else if(respObj instanceof List){
for(Object item : ((List) respObj)){
if(item instanceof BaseModel)
((BaseModel) item).postprocess();
}
}
}
void onError(String msg){
invokeErrorCallback(new MastodonErrorResponse(msg));
}
void onSuccess(T resp){
invokeSuccessCallback(resp);
}
public enum HttpMethod{
GET,
POST,
PUT,
DELETE
}
}

View File

@ -0,0 +1,29 @@
package org.joinmastodon.android.api;
import android.content.Context;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.joinmastodon.android.R;
import me.grishka.appkit.api.ErrorResponse;
public class MastodonErrorResponse extends ErrorResponse{
public final String error;
public MastodonErrorResponse(String error){
this.error=error;
}
@Override
public void bindErrorView(View view){
TextView text=view.findViewById(R.id.error_text);
text.setText(error);
}
@Override
public void showToast(Context context){
Toast.makeText(context, error, Toast.LENGTH_SHORT).show();
}
}

View File

@ -0,0 +1,20 @@
package org.joinmastodon.android.api;
import java.io.IOException;
public class ObjectValidationException extends IOException{
public ObjectValidationException(){
}
public ObjectValidationException(String message){
super(message);
}
public ObjectValidationException(String message, Throwable cause){
super(message, cause);
}
public ObjectValidationException(Throwable cause){
super(cause);
}
}

View File

@ -0,0 +1,11 @@
package org.joinmastodon.android.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface RequiredField{
}

View File

@ -0,0 +1,34 @@
package org.joinmastodon.android.api.gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class IsoInstantTypeAdapter extends TypeAdapter<Instant>{
@Override
public void write(JsonWriter out, Instant value) throws IOException{
if(value==null)
out.nullValue();
else
out.value(DateTimeFormatter.ISO_INSTANT.format(value));
}
@Override
public Instant read(JsonReader in) throws IOException{
if(in.peek()==JsonToken.NULL){
in.nextNull();
return null;
}
try{
return DateTimeFormatter.ISO_INSTANT.parse(in.nextString(), Instant::from);
}catch(DateTimeParseException x){
return null;
}
}
}

View File

@ -0,0 +1,33 @@
package org.joinmastodon.android.api.gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
public class IsoLocalDateTypeAdapter extends TypeAdapter<LocalDate>{
@Override
public void write(JsonWriter out, LocalDate value) throws IOException{
if(value==null)
out.nullValue();
else
out.value(value.toString());
}
@Override
public LocalDate read(JsonReader in) throws IOException{
if(in.peek()==JsonToken.NULL){
in.nextNull();
return null;
}
try{
return LocalDate.parse(in.nextString());
}catch(DateTimeParseException x){
return null;
}
}
}

View File

@ -0,0 +1,10 @@
package org.joinmastodon.android.api.requests;
import org.joinmastodon.android.api.MastodonAPIRequest;
import org.joinmastodon.android.model.Instance;
public class GetInstance extends MastodonAPIRequest<Instance>{
public GetInstance(){
super(HttpMethod.GET, "/instance", Instance.class);
}
}

View File

@ -0,0 +1,10 @@
package org.joinmastodon.android.api.requests.accounts;
import org.joinmastodon.android.api.MastodonAPIRequest;
import org.joinmastodon.android.model.Account;
public class GetOwnAccount extends MastodonAPIRequest<Account>{
public GetOwnAccount(){
super(HttpMethod.GET, "/accounts/verify_credentials", Account.class);
}
}

View File

@ -0,0 +1,32 @@
package org.joinmastodon.android.api.requests.catalog;
import android.net.Uri;
import android.text.TextUtils;
import com.google.gson.reflect.TypeToken;
import org.joinmastodon.android.api.MastodonAPIRequest;
import org.joinmastodon.android.model.catalog.CatalogCategory;
import org.joinmastodon.android.model.catalog.CatalogInstance;
import java.util.List;
public class GetCatalogCategories extends MastodonAPIRequest<List<CatalogCategory>>{
private String lang;
public GetCatalogCategories(String lang){
super(HttpMethod.GET, null, new TypeToken<>(){});
this.lang=lang;
}
@Override
public Uri getURL(){
Uri.Builder builder=new Uri.Builder()
.scheme("https")
.authority("api.joinmastodon.org")
.path("/categories");
if(!TextUtils.isEmpty(lang))
builder.appendQueryParameter("language", lang);
return builder.build();
}
}

View File

@ -0,0 +1,35 @@
package org.joinmastodon.android.api.requests.catalog;
import android.net.Uri;
import android.text.TextUtils;
import com.google.gson.reflect.TypeToken;
import org.joinmastodon.android.api.MastodonAPIRequest;
import org.joinmastodon.android.model.catalog.CatalogInstance;
import java.util.List;
public class GetCatalogInstances extends MastodonAPIRequest<List<CatalogInstance>>{
private String lang, category;
public GetCatalogInstances(String lang, String category){
super(HttpMethod.GET, null, new TypeToken<>(){});
this.lang=lang;
this.category=category;
}
@Override
public Uri getURL(){
Uri.Builder builder=new Uri.Builder()
.scheme("https")
.authority("api.joinmastodon.org")
.path("/servers");
if(!TextUtils.isEmpty(lang))
builder.appendQueryParameter("language", lang);
if(!TextUtils.isEmpty(category))
builder.appendQueryParameter("category", category);
return builder.build();
}
}

View File

@ -0,0 +1,21 @@
package org.joinmastodon.android.api.requests.oauth;
import android.net.Uri;
import org.joinmastodon.android.api.MastodonAPIRequest;
import org.joinmastodon.android.api.session.AccountSessionManager;
import org.joinmastodon.android.model.Application;
public class CreateOAuthApp extends MastodonAPIRequest<Application>{
public CreateOAuthApp(){
super(HttpMethod.POST, "/apps", Application.class);
setRequestBody(new Request());
}
private static class Request{
public String clientName="Mastodon for Android";
public String redirectUris=AccountSessionManager.REDIRECT_URI;
public String scopes=AccountSessionManager.SCOPE;
public String website="https://joinmastodon.org";
}
}

View File

@ -0,0 +1,32 @@
package org.joinmastodon.android.api.requests.oauth;
import org.joinmastodon.android.api.MastodonAPIRequest;
import org.joinmastodon.android.api.session.AccountSessionManager;
import org.joinmastodon.android.model.Token;
public class GetOauthToken extends MastodonAPIRequest<Token>{
public GetOauthToken(String clientID, String clientSecret, String code){
super(HttpMethod.POST, "/oauth/token", Token.class);
setRequestBody(new Request(clientID, clientSecret, code));
}
@Override
protected String getPathPrefix(){
return "";
}
private static class Request{
public String grantType="authorization_code";
public String clientId;
public String clientSecret;
public String redirectUri=AccountSessionManager.REDIRECT_URI;
public String scope=AccountSessionManager.SCOPE;
public String code;
public Request(String clientId, String clientSecret, String code){
this.clientId=clientId;
this.clientSecret=clientSecret;
this.code=code;
}
}
}

View File

@ -0,0 +1,35 @@
package org.joinmastodon.android.api.session;
import org.joinmastodon.android.api.MastodonAPIController;
import org.joinmastodon.android.model.Account;
import org.joinmastodon.android.model.Application;
import org.joinmastodon.android.model.Token;
public class AccountSession{
public Token token;
public Account self;
public String domain;
public int tootCharLimit;
public Application app;
private transient MastodonAPIController apiController;
AccountSession(Token token, Account self, Application app, String domain, int tootCharLimit){
this.token=token;
this.self=self;
this.domain=domain;
this.app=app;
this.tootCharLimit=tootCharLimit;
}
AccountSession(){}
public String getID(){
return domain+"_"+self.id;
}
public MastodonAPIController getApiController(){
if(apiController==null)
apiController=new MastodonAPIController(this);
return apiController;
}
}

View File

@ -0,0 +1,186 @@
package org.joinmastodon.android.api.session;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.joinmastodon.android.MastodonApp;
import org.joinmastodon.android.OAuthActivity;
import org.joinmastodon.android.R;
import org.joinmastodon.android.api.MastodonAPIController;
import org.joinmastodon.android.api.requests.oauth.CreateOAuthApp;
import org.joinmastodon.android.model.Account;
import org.joinmastodon.android.model.Application;
import org.joinmastodon.android.model.Instance;
import org.joinmastodon.android.model.Token;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.browser.customtabs.CustomTabsIntent;
import me.grishka.appkit.api.Callback;
import me.grishka.appkit.api.ErrorResponse;
public class AccountSessionManager{
private static final String TAG="AccountSessionManager";
public static final String SCOPE="read write follow push";
public static final String REDIRECT_URI="mastodon-android-auth://callback";
private static final AccountSessionManager instance=new AccountSessionManager();
private HashMap<String, AccountSession> sessions=new HashMap<>();
private MastodonAPIController unauthenticatedApiController=new MastodonAPIController(null);
private Instance authenticatingInstance;
private Application authenticatingApp;
private String lastActiveAccountID;
private SharedPreferences prefs;
public static AccountSessionManager getInstance(){
return instance;
}
private AccountSessionManager(){
prefs=MastodonApp.context.getSharedPreferences("account_manager", Context.MODE_PRIVATE);
File file=new File(MastodonApp.context.getFilesDir(), "accounts.json");
if(!file.exists())
return;
try(FileInputStream in=new FileInputStream(file)){
SessionsStorageWrapper w=MastodonAPIController.gson.fromJson(new InputStreamReader(in, StandardCharsets.UTF_8), SessionsStorageWrapper.class);
for(AccountSession session:w.accounts){
sessions.put(session.getID(), session);
}
}catch(IOException x){
Log.e(TAG, "Error loading accounts", x);
}
lastActiveAccountID=prefs.getString("lastActiveAccount", null);
}
public void addAccount(Instance instance, Token token, Account self, Application app){
AccountSession session=new AccountSession(token, self, app, instance.uri, instance.maxTootChars);
sessions.put(session.getID(), session);
lastActiveAccountID=session.getID();
writeAccountsFile();
}
private void writeAccountsFile(){
File file=new File(MastodonApp.context.getFilesDir(), "accounts.json");
try{
try(FileOutputStream out=new FileOutputStream(file)){
SessionsStorageWrapper w=new SessionsStorageWrapper();
w.accounts=new ArrayList<>(sessions.values());
OutputStreamWriter writer=new OutputStreamWriter(out, StandardCharsets.UTF_8);
MastodonAPIController.gson.toJson(w, writer);
writer.flush();
}
}catch(IOException x){
Log.e(TAG, "Error writing accounts file", x);
}
prefs.edit().putString("lastActiveAccount", lastActiveAccountID).apply();
}
@NonNull
public List<AccountSession> getLoggedInAccounts(){
return new ArrayList<>(sessions.values());
}
@NonNull
public AccountSession getAccount(String id){
AccountSession session=sessions.get(id);
if(session==null)
throw new IllegalStateException("Account session "+id+" not found");
return session;
}
@Nullable
public AccountSession getLastActiveAccount(){
if(sessions.isEmpty() || lastActiveAccountID==null)
return null;
return getAccount(lastActiveAccountID);
}
public String getLastActiveAccountID(){
return lastActiveAccountID;
}
public void removeAccount(String id){
AccountSession session=getAccount(id);
sessions.remove(id);
if(lastActiveAccountID.equals(id)){
if(sessions.isEmpty())
lastActiveAccountID=null;
else
lastActiveAccountID=getLoggedInAccounts().get(0).getID();
}
writeAccountsFile();
}
@NonNull
public MastodonAPIController getUnauthenticatedApiController(){
return unauthenticatedApiController;
}
public void authenticate(Context context, Instance instance){
authenticatingInstance=instance;
ProgressDialog progress=new ProgressDialog(context);
progress.setMessage(context.getString(R.string.preparing_auth));
progress.setCancelable(false);
progress.show();
new CreateOAuthApp()
.setCallback(new Callback<Application>(){
@Override
public void onSuccess(Application result){
authenticatingApp=result;
progress.dismiss();
Uri uri=new Uri.Builder()
.scheme("https")
.authority(instance.uri)
.path("/oauth/authorize")
.appendQueryParameter("response_type", "code")
.appendQueryParameter("client_id", result.clientId)
.appendQueryParameter("redirect_uri",