Fix authentication

This commit is contained in:
Thomas 2020-07-22 10:55:59 +02:00
parent 1f61e7f613
commit dc9dc14fd5
8 changed files with 106 additions and 68 deletions

View File

@ -37,7 +37,7 @@ import org.jetbrains.annotations.NotNull;
import app.fedilab.fedilabtube.asynctasks.RetrieveFeedsAsyncTask;
import app.fedilab.fedilabtube.asynctasks.RetrievePeertubeInformationAsyncTask;
import app.fedilab.fedilabtube.asynctasks.UpdateAccountInfoAsyncTask;
import app.fedilab.fedilabtube.client.PeertubeAPI;
import app.fedilab.fedilabtube.client.entities.Account;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.sqlite.AccountDAO;
@ -110,8 +110,10 @@ public class MainActivity extends AppCompatActivity {
String instance = Helper.getLiveInstance(MainActivity.this);
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Account account = new AccountDAO(MainActivity.this, db).getUniqAccount(userId, instance);
if( account != null) {
new UpdateAccountInfoAsyncTask(MainActivity.this, account.getToken(), account.getClient_id(), account.getClient_secret(), account.getRefresh_token(), account.getInstance()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
if (account != null) {
new Thread(() -> {
new PeertubeAPI(MainActivity.this).refreshToken(account.getToken(), account.getInstance());
}).start();
}
} else {
instanceItem.setVisible(true);

View File

@ -176,7 +176,7 @@ public class PeertubeActivity extends AppCompatActivity implements OnRetrievePee
peertube_playlist.setVisibility(View.VISIBLE);
peertube_bookmark.setVisibility(View.GONE);
if( Helper.isTablet(PeertubeActivity.this)) {
if (Helper.isTablet(PeertubeActivity.this)) {
RelativeLayout video_container = findViewById(R.id.video_container);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
@ -307,7 +307,7 @@ public class PeertubeActivity extends AppCompatActivity implements OnRetrievePee
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}else if (item.getItemId() == R.id.action_report) {
} else if (item.getItemId() == R.id.action_report) {
androidx.appcompat.app.AlertDialog.Builder dialogBuilder = new androidx.appcompat.app.AlertDialog.Builder(PeertubeActivity.this);
LayoutInflater inflater1 = getLayoutInflater();
View dialogView = inflater1.inflate(R.layout.popup_report_choice, new LinearLayout(PeertubeActivity.this), false);
@ -324,25 +324,29 @@ public class PeertubeActivity extends AppCompatActivity implements OnRetrievePee
return super.onOptionsItemSelected(item);
}
private void reportAlert(PeertubeAPI.reportType type, androidx.appcompat.app.AlertDialog alertDialog){
private void reportAlert(PeertubeAPI.reportType type, androidx.appcompat.app.AlertDialog alertDialog) {
androidx.appcompat.app.AlertDialog.Builder dialogBuilder = new androidx.appcompat.app.AlertDialog.Builder(PeertubeActivity.this);
LayoutInflater inflater1 = getLayoutInflater();
View dialogView = inflater1.inflate(R.layout.popup_report, new LinearLayout(PeertubeActivity.this), false);
dialogBuilder.setView(dialogView);
EditText report_content = dialogView.findViewById(R.id.report_content);
dialogBuilder.setNeutralButton(R.string.cancel, (dialog, id) -> dialog.dismiss());
androidx.appcompat.app.AlertDialog alertDialog2 = dialogBuilder.create();
dialogBuilder.setPositiveButton(R.string.report, (dialog, id) -> {
if( type == PeertubeAPI.reportType.VIDEO) {
new PostActionAsyncTask(PeertubeActivity.this, PeertubeAPI.StatusAction.REPORT_VIDEO, peertube.getId(), report_content.getText().toString(), PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
alertDialog.dismiss();
alertDialog2.dismiss();
}else if (type == PeertubeAPI.reportType.ACCOUNT) {
new PostActionAsyncTask(PeertubeActivity.this, PeertubeAPI.StatusAction.REPORT_ACCOUNT, peertube.getAccount().getId(), report_content.getText().toString(), PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
alertDialog.dismiss();
alertDialog2.dismiss();
if (report_content.getText().toString().trim().length() == 0) {
Toasty.info(PeertubeActivity.this, getString(R.string.report_comment_size), Toasty.LENGTH_LONG).show();
} else {
if (type == PeertubeAPI.reportType.VIDEO) {
new PostActionAsyncTask(PeertubeActivity.this, PeertubeAPI.StatusAction.REPORT_VIDEO, peertube.getId(), report_content.getText().toString(), PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
alertDialog.dismiss();
dialog.dismiss();
} else if (type == PeertubeAPI.reportType.ACCOUNT) {
new PostActionAsyncTask(PeertubeActivity.this, PeertubeAPI.StatusAction.REPORT_ACCOUNT, peertube.getAccount().getId(), report_content.getText().toString(), PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
alertDialog.dismiss();
dialog.dismiss();
}
}
});
androidx.appcompat.app.AlertDialog alertDialog2 = dialogBuilder.create();
alertDialog2.show();
}
@ -743,9 +747,9 @@ public class PeertubeActivity extends AppCompatActivity implements OnRetrievePee
if (peertube.isCommentsEnabled() && statusAction == PeertubeAPI.StatusAction.PEERTUBECOMMENT) {
new RetrievePeertubeSingleCommentsAsyncTask(PeertubeActivity.this, peertubeInstance, videoId, PeertubeActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else if( statusAction == PeertubeAPI.StatusAction.REPORT_ACCOUNT) {
} else if (statusAction == PeertubeAPI.StatusAction.REPORT_ACCOUNT) {
Toasty.success(PeertubeActivity.this, getString(R.string.successful_report), Toasty.LENGTH_LONG).show();
}else if( statusAction == PeertubeAPI.StatusAction.REPORT_VIDEO) {
} else if (statusAction == PeertubeAPI.StatusAction.REPORT_VIDEO) {
Toasty.success(PeertubeActivity.this, getString(R.string.successful_video_report), Toasty.LENGTH_LONG).show();
}
}

View File

@ -78,9 +78,9 @@ public class PostActionAsyncTask extends AsyncTask<Void, Void, Void> {
targetedId = comment;
} else if (apiAction == PeertubeAPI.StatusAction.PEERTUBEDELETEVIDEO) {
statusCode = peertubeAPI.deleteVideo(targetedId);
}else if (apiAction == PeertubeAPI.StatusAction.REPORT_ACCOUNT) {
} else if (apiAction == PeertubeAPI.StatusAction.REPORT_ACCOUNT) {
statusCode = peertubeAPI.report(PeertubeAPI.reportType.ACCOUNT, targetedId, comment);
}else if (apiAction == PeertubeAPI.StatusAction.REPORT_VIDEO) {
} else if (apiAction == PeertubeAPI.StatusAction.REPORT_VIDEO) {
statusCode = peertubeAPI.report(PeertubeAPI.reportType.VIDEO, targetedId, comment);
}
error = peertubeAPI.getError();

View File

@ -14,6 +14,7 @@ package app.fedilab.fedilabtube.client;
* You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
@ -77,12 +78,6 @@ public class PeertubeAPI {
private APIResponse apiResponse;
private Error APIError;
public enum reportType {
ACCOUNT,
COMMENT,
VIDEO
}
public PeertubeAPI(Context context) {
this.context = context;
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
@ -723,6 +718,68 @@ public class PeertubeAPI {
return peertubeInformation;
}
/**
* Refresh token and update user data
*
* @param token String
* @param instance String
*/
public void refreshToken(String token, String instance) {
SQLiteDatabase db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if (token == null) {
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instanceC = Helper.getLiveInstance(context);
Account accountToLogout = new AccountDAO(context, db).getUniqAccount(userId, instanceC);
Helper.logoutCurrentUser((Activity) context, accountToLogout);
return;
}
Account targetedAccount = new AccountDAO(context, db).getAccountByToken(token);
String newToken = null, newRefreshToken = null;
if (targetedAccount != null) {
HashMap<String, String> values = refreshToken(targetedAccount.getClient_id(), targetedAccount.getClient_secret(), targetedAccount.getRefresh_token());
if (values.containsKey("access_token") && values.get("access_token") != null) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
//This account is currently logged in, the token is updated
if (values.get("access_token") != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, values.get("access_token"));
editor.apply();
}
}
if (values.containsKey("refresh_token") && values.get("refresh_token") != null) {
newRefreshToken = values.get("refresh_token");
}
if (values.containsKey("access_token") && values.get("access_token") != null) {
newToken = values.get("access_token");
}
String response;
try {
response = new HttpsConnection(context).get("https://" + instance + "/api/v1/users/me", 60, null, newToken);
JSONObject accountObject = new JSONObject(response).getJSONObject("account");
account = parseAccountResponsePeertube(accountObject);
} catch (IOException | NoSuchAlgorithmException | KeyManagementException | JSONException e) {
e.printStackTrace();
} catch (HttpsConnection.HttpsConnectionException e) {
e.printStackTrace();
//setError(e.getStatusCode(), e);
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instanceC = Helper.getLiveInstance(context);
Account accountToLogout = new AccountDAO(context, db).getUniqAccount(userId, instanceC);
Helper.logoutCurrentUser((Activity) context, accountToLogout);
return;
}
if (newRefreshToken != null && newToken != null) {
account.setRefresh_token(newRefreshToken);
account.setToken(newToken);
}
new AccountDAO(context, db).updateAccount(account);
}
}
/***
* Verifiy credential of the authenticated user *synchronously*
* @return Account
@ -736,52 +793,16 @@ public class PeertubeAPI {
} catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) {
e.printStackTrace();
} catch (HttpsConnection.HttpsConnectionException e) {
if (e.getStatusCode() == 401 || e.getStatusCode() == 403) {
SQLiteDatabase db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Account targetedAccount = new AccountDAO(context, db).getAccountByToken(token);
if (targetedAccount != null) {
HashMap<String, String> values = refreshToken(targetedAccount.getClient_id(), targetedAccount.getClient_secret(), targetedAccount.getRefresh_token());
if (values.containsKey("access_token") && values.get("access_token") != null) {
targetedAccount.setToken(values.get("access_token"));
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String tokenShared = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
//This account is currently logged in, the token is updated
if (tokenShared != null && token.compareTo(tokenShared) == 0) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, targetedAccount.getToken());
editor.apply();
}
}
if (values.containsKey("refresh_token") && values.get("refresh_token") != null)
targetedAccount.setRefresh_token(values.get("refresh_token"));
new AccountDAO(context, db).updateAccount(targetedAccount);
String response;
try {
response = new HttpsConnection(context).get("https://" + instance + "/api/v1/users/me", 60, null, targetedAccount.getToken());
JSONObject accountObject = new JSONObject(response).getJSONObject("account");
account = parseAccountResponsePeertube(accountObject);
} catch (IOException | NoSuchAlgorithmException | KeyManagementException | JSONException e1) {
e1.printStackTrace();
} catch (HttpsConnection.HttpsConnectionException e1) {
e1.printStackTrace();
setError(e.getStatusCode(), e);
}
} else {
setError(e.getStatusCode(), e);
}
e.printStackTrace();
}
setError(e.getStatusCode(), e);
}
return account;
}
public int report(reportType type, String id, String reason) {
actionCode = -1;
try {
HashMap<String, String> params = new HashMap<>();
switch (type){
switch (type) {
case VIDEO:
params.put("video", id);
break;
@ -840,11 +861,13 @@ public class PeertubeAPI {
String response = new HttpsConnection(context).post(getAbsoluteUrl("/users/token"), 60, params, null);
JSONObject resobj = new JSONObject(response);
String token = resobj.getString("access_token");
if (resobj.has("refresh_token"))
refresh_token = resobj.getString("refresh_token");
String refresh = resobj.getString("refresh_token");
newValues.put("access_token", token);
newValues.put("refresh_token", refresh_token);
} catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException | HttpsConnection.HttpsConnectionException e) {
newValues.put("refresh_token", refresh);
} catch (NoSuchAlgorithmException | IOException | KeyManagementException | JSONException e) {
e.printStackTrace();
} catch (HttpsConnection.HttpsConnectionException e) {
setError(e.getStatusCode(), e);
e.printStackTrace();
}
return newValues;
@ -1740,7 +1763,6 @@ public class PeertubeAPI {
return peertubeNotifications;
}
/**
* Parse json response for several howto
*
@ -1866,6 +1888,12 @@ public class PeertubeAPI {
return Helper.instanceWithProtocol(context) + "/api/v1" + action;
}
public enum reportType {
ACCOUNT,
COMMENT,
VIDEO
}
public enum StatusAction {
FOLLOW,

View File

@ -2,6 +2,7 @@
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/popup_padding"
xmlns:app="http://schemas.android.com/apk/res-auto">
<EditText
android:hint="@string/report_helper"

View File

@ -2,6 +2,7 @@
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/popup_padding"
xmlns:app="http://schemas.android.com/apk/res-auto">
<Button
style="@style/Base.Widget.AppCompat.Button.Colored"

View File

@ -9,4 +9,5 @@
<dimen name="video_padding">0dp</dimen>
<bool name="is_tablet">false</bool>
<dimen name="video_comment_margin">0dp</dimen>
<dimen name="popup_padding">20dp</dimen>
</resources>

View File

@ -173,4 +173,5 @@
<string name="report_helper">Quelques explications concernant votre signalement…</string>
<string name="successful_report">Le compte a été signalé !</string>
<string name="successful_video_report">La vidéo a été signalée !</string>
<string name="report_comment_size">Veuillez préciser les raisons.</string>
</resources>