This commit is contained in:
Thomas 2023-01-23 12:12:22 +01:00
parent 74afdc0a7a
commit 4c5232039a
73 changed files with 485 additions and 3917 deletions

View File

@ -130,7 +130,7 @@ public class BasePeertubeActivity extends BaseBarActivity {
} else {
b.putInt("displayed", 1);
b.putParcelable("castedTube", peertube);
b.putSerializable("castedTube", peertube);
intentBC.putExtras(b);
LocalBroadcastManager.getInstance(BasePeertubeActivity.this).sendBroadcast(intentBC);
try {

View File

@ -286,19 +286,6 @@
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/settings"
android:theme="@style/AppThemeBar" />
<activity
android:name=".mastodon.activities.InstanceActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/action_about_instance"
android:theme="@style/AppThemeAlertDialog" />
<activity
android:name=".mastodon.activities.InstanceProfileActivity"
android:excludeFromRecents="true"
android:theme="@style/AppThemeAlertDialog" />
<activity
android:name=".mastodon.activities.ProxyActivity"
android:excludeFromRecents="true"
android:theme="@style/AppThemeAlertDialog" />
<activity
android:name=".mastodon.activities.HashTagActivity"
android:configChanges="keyboardHidden|orientation|screenSize" />
@ -310,11 +297,6 @@
android:configChanges="keyboardHidden|orientation|screenSize"
android:theme="@style/Transparent" />
<activity
android:name=".mastodon.activities.InstanceHealthActivity"
android:excludeFromRecents="true"
android:theme="@style/AppThemeAlertDialog" />
<activity
android:name=".mastodon.activities.ReportActivity"
android:theme="@style/AppThemeBar"
@ -427,10 +409,6 @@
android:name=".peertube.activities.PlaylistsActivity"
android:configChanges="orientation|screenSize"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity
android:name=".peertube.activities.LocalPlaylistsActivity"
android:configChanges="orientation|screenSize"
android:windowSoftInputMode="stateAlwaysHidden" />
<activity
android:name=".peertube.activities.VideosTimelineActivity"
android:configChanges="orientation|screenSize"
@ -448,12 +426,6 @@
<activity
android:name=".peertube.activities.WebviewActivity"
android:configChanges="keyboardHidden|orientation|screenSize" />
<activity
android:name=".peertube.activities.WebviewConnectActivity"
android:configChanges="keyboardHidden|orientation|screenSize" />
<activity
android:name=".peertube.activities.MastodonWebviewConnectActivity"
android:configChanges="keyboardHidden|orientation|screenSize" />
<activity
android:name=".peertube.activities.LoginActivity"
android:configChanges="orientation|screenSize"

View File

@ -16,9 +16,12 @@ package app.fedilab.android.mastodon.client.entities.app;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import androidx.preference.PreferenceManager;
import com.google.gson.Gson;
import java.io.Serializable;
@ -29,6 +32,9 @@ import java.util.List;
import app.fedilab.android.BaseMainActivity;
import app.fedilab.android.mastodon.exception.DBException;
import app.fedilab.android.mastodon.helper.Helper;
import app.fedilab.android.peertube.client.data.AccountData;
import app.fedilab.android.peertube.client.entities.Token;
import app.fedilab.android.peertube.helper.HelperInstance;
import app.fedilab.android.sqlite.Sqlite;
/**
@ -68,6 +74,21 @@ public class Account extends BaseAccount implements Serializable {
}
}
/**
* Serialized a Peertube BaseAccount class
*
* @param peertube_account {@link AccountData.PeertubeAccount} to serialize
* @return String serialized account
*/
public static String peertubeAccountToStringStorage(AccountData.PeertubeAccount peertube_account) {
Gson gson = new Gson();
try {
return gson.toJson(peertube_account);
} catch (Exception e) {
return null;
}
}
/**
* Unserialized a Mastodon BaseAccount
*
@ -83,6 +104,22 @@ public class Account extends BaseAccount implements Serializable {
}
}
/**
* Unserialized a Peertube account AccountData.PeertubeAccount
*
* @param serializedAccount String serialized account
* @return {@link AccountData.PeertubeAccount}
*/
public static AccountData.PeertubeAccount restorePeertubeAccountFromString(String serializedAccount) {
Gson gson = new Gson();
try {
return gson.fromJson(serializedAccount, AccountData.PeertubeAccount.class);
} catch (Exception e) {
return null;
}
}
/**
* Returns all BaseAccount in db
*
@ -98,6 +135,21 @@ public class Account extends BaseAccount implements Serializable {
}
}
/**
* Returns all BaseAccount in db
*
* @return BaseAccount List<BaseAccount>
*/
public List<BaseAccount> getPeertubeAccounts() {
try {
Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_API + " = 'PEERTUBE' AND " + Sqlite.COL_TOKEN + " IS NOT NULL", null, null, null, Sqlite.COL_INSTANCE + " ASC", null);
return cursorToListUserWithOwner(c);
} catch (Exception e) {
return null;
}
}
/**
* Insert or update a user
*
@ -144,6 +196,9 @@ public class Account extends BaseAccount implements Serializable {
if (account.mastodon_account != null) {
values.put(Sqlite.COL_ACCOUNT, mastodonAccountToStringStorage(account.mastodon_account));
}
if (account.peertube_account != null) {
values.put(Sqlite.COL_ACCOUNT, peertubeAccountToStringStorage(account.peertube_account));
}
values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(new Date()));
values.put(Sqlite.COL_UPDATED_AT, Helper.dateToString(new Date()));
//Inserts token
@ -181,6 +236,9 @@ public class Account extends BaseAccount implements Serializable {
if (account.mastodon_account != null) {
values.put(Sqlite.COL_ACCOUNT, mastodonAccountToStringStorage(account.mastodon_account));
}
if (account.peertube_account != null) {
values.put(Sqlite.COL_ACCOUNT, peertubeAccountToStringStorage(account.peertube_account));
}
values.put(Sqlite.COL_UPDATED_AT, Helper.dateToString(new Date()));
//Inserts token
try {
@ -193,6 +251,33 @@ public class Account extends BaseAccount implements Serializable {
}
}
/**
* Update an account in db
*
* @param token {@link Token}
* @return long - db id
* @throws DBException exception with database
*/
public long updatePeertubeToken(Token token) throws DBException {
ContentValues values = new ContentValues();
if (token.getRefresh_token() != null) {
values.put(Sqlite.COL_REFRESH_TOKEN, token.getRefresh_token());
}
if (token.getAccess_token() != null)
values.put(Sqlite.COL_TOKEN, token.getAccess_token());
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(context);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = HelperInstance.getLiveInstance(context);
try {
return db.update(Sqlite.TABLE_USER_ACCOUNT,
values, Sqlite.COL_USER_ID + " = ? AND " + Sqlite.COL_INSTANCE + " =?",
new String[]{userId, instance});
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
/**
* Check if a user exists in db
*
@ -454,6 +539,7 @@ public class Account extends BaseAccount implements Serializable {
FRIENDICA,
PLEROMA,
PIXELFED,
PEERTUBE,
UNKNOWN
}
}

View File

@ -19,6 +19,8 @@ import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Date;
import app.fedilab.android.peertube.client.data.AccountData;
/**
* Class that manages Accounts from database
* Accounts details are serialized and can be for different softwares
@ -51,6 +53,8 @@ public class BaseAccount implements Serializable {
public Date updated_at;
@SerializedName("mastodon_account")
public app.fedilab.android.mastodon.client.entities.api.Account mastodon_account;
@SerializedName("peertube_account")
public AccountData.PeertubeAccount peertube_account;
@SerializedName("admin")
public boolean admin;

View File

@ -18,7 +18,6 @@ import static app.fedilab.android.peertube.activities.PeertubeMainActivity.badge
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
@ -46,15 +45,16 @@ import org.jetbrains.annotations.NotNull;
import app.fedilab.android.R;
import app.fedilab.android.databinding.ActivityAccountPeertubeBinding;
import app.fedilab.android.mastodon.activities.BaseBarActivity;
import app.fedilab.android.mastodon.client.entities.app.Account;
import app.fedilab.android.mastodon.client.entities.app.BaseAccount;
import app.fedilab.android.mastodon.exception.DBException;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.peertube.client.data.AccountData;
import app.fedilab.android.peertube.fragment.DisplayAccountsFragment;
import app.fedilab.android.peertube.fragment.DisplayChannelsFragment;
import app.fedilab.android.peertube.fragment.DisplayNotificationsFragment;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.helper.SwitchAccountHelper;
import app.fedilab.android.peertube.sqlite.AccountDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
public class AccountActivity extends BaseBarActivity {
@ -78,16 +78,21 @@ public class AccountActivity extends BaseBarActivity {
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
Account account = new AccountDAO(AccountActivity.this, db).getAccountByToken(token);
if (account == null) {
Helper.logoutCurrentUser(AccountActivity.this, null);
BaseAccount baseAccount = null;
try {
baseAccount = new Account(AccountActivity.this).getAccountByToken(token);
} catch (DBException e) {
e.printStackTrace();
}
if (baseAccount == null) {
finish();
return;
}
AccountData.PeertubeAccount account = baseAccount.peertube_account;
setTitle(String.format("@%s", account.getUsername()));
@ -97,11 +102,12 @@ public class AccountActivity extends BaseBarActivity {
binding.instance.setText(account.getHost());
BaseAccount finalBaseAccount = baseAccount;
binding.logoutButton.setOnClickListener(v -> {
AlertDialog.Builder dialogBuilderLogoutAccount = new AlertDialog.Builder(AccountActivity.this);
dialogBuilderLogoutAccount.setMessage(getString(R.string.logout_account_confirmation, account.getUsername(), account.getHost()));
dialogBuilderLogoutAccount.setPositiveButton(R.string.action_logout, (dialog, id) -> {
Helper.logoutCurrentUser(AccountActivity.this, account);
Helper.logoutCurrentUser(AccountActivity.this, finalBaseAccount);
dialog.dismiss();
});
dialogBuilderLogoutAccount.setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss());
@ -215,9 +221,9 @@ public class AccountActivity extends BaseBarActivity {
binding.remoteAccount.setVisibility(View.VISIBLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
binding.remoteAccount.setText(Html.fromHtml(getString(R.string.remote_account_from, account.getSoftware()), Html.FROM_HTML_MODE_LEGACY));
binding.remoteAccount.setText(Html.fromHtml(getString(R.string.remote_account_from, baseAccount.software), Html.FROM_HTML_MODE_LEGACY));
else
binding.remoteAccount.setText(Html.fromHtml(getString(R.string.remote_account_from, account.getSoftware())));
binding.remoteAccount.setText(Html.fromHtml(getString(R.string.remote_account_from, baseAccount.software)));
}
}

View File

@ -21,7 +21,6 @@ import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
@ -35,7 +34,6 @@ import app.fedilab.android.mastodon.activities.BaseBarActivity;
import app.fedilab.android.peertube.client.data.PlaylistData.Playlist;
import app.fedilab.android.peertube.client.data.VideoPlaylistData;
import app.fedilab.android.peertube.drawer.PlaylistAdapter;
import app.fedilab.android.peertube.viewmodel.PlaylistsVM;
public class AllLocalPlaylistsActivity extends BaseBarActivity implements PlaylistAdapter.AllPlaylistRemoved {
@ -63,8 +61,6 @@ public class AllLocalPlaylistsActivity extends BaseBarActivity implements Playli
mainLoader.setVisibility(View.VISIBLE);
nextElementLoader.setVisibility(View.GONE);
PlaylistsVM viewModel = new ViewModelProvider(AllLocalPlaylistsActivity.this).get(PlaylistsVM.class);
viewModel.localePlaylist().observe(AllLocalPlaylistsActivity.this, this::manageVIewPlaylists);
FloatingActionButton add_new = findViewById(R.id.add_new);
add_new.setVisibility(View.GONE);

View File

@ -38,11 +38,10 @@ import app.fedilab.android.R;
import app.fedilab.android.databinding.ActivityLoginPeertubeBinding;
import app.fedilab.android.mastodon.activities.BaseBarActivity;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.entities.Error;
import app.fedilab.android.peertube.client.entities.Oauth;
import app.fedilab.android.peertube.client.entities.OauthParams;
import app.fedilab.android.peertube.client.entities.Token;
import app.fedilab.android.peertube.client.entities.WellKnownNodeinfo;
import app.fedilab.android.peertube.client.mastodon.RetrofitMastodonAPI;
import app.fedilab.android.peertube.helper.Helper;
import es.dmoral.toasty.Toasty;
@ -53,7 +52,7 @@ public class LoginActivity extends BaseBarActivity {
private static String client_id;
private static String client_secret;
private ActivityLoginPeertubeBinding binding;
private String instance;
@SuppressLint("SetTextI18n")
@Override
@ -62,6 +61,13 @@ public class LoginActivity extends BaseBarActivity {
binding = ActivityLoginPeertubeBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
Bundle b = getIntent().getExtras();
if (b != null) {
instance = b.getString(app.fedilab.android.mastodon.helper.Helper.ARG_INSTANCE, null);
}
if (instance == null) {
finish();
}
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
@ -77,15 +83,13 @@ public class LoginActivity extends BaseBarActivity {
binding.createAnAccountPeertube.setOnClickListener(v -> {
Intent mainActivity = new Intent(LoginActivity.this, PeertubeRegisterActivity.class);
Bundle b = new Bundle();
mainActivity.putExtras(b);
startActivity(mainActivity);
});
binding.loginInstanceContainer.setVisibility(View.VISIBLE);
binding.loginInstance.setText(instance);
if (Helper.isTablet(LoginActivity.this)) {
ViewGroup.LayoutParams layoutParamsI = binding.loginInstanceContainer.getLayoutParams();
@ -137,10 +141,7 @@ public class LoginActivity extends BaseBarActivity {
return;
}
String finalInstance = instance;
new Thread(() -> {
WellKnownNodeinfo.NodeInfo instanceNodeInfo = null;
connectToFediverse(finalInstance, instanceNodeInfo);
}).start();
new Thread(() -> connectToFediverse(finalInstance)).start();
});
}
@ -149,28 +150,8 @@ public class LoginActivity extends BaseBarActivity {
*
* @param finalInstance String
*/
private void connectToFediverse(String finalInstance, WellKnownNodeinfo.NodeInfo instanceNodeInfo) {
Oauth oauth = null;
String software;
if (instanceNodeInfo != null) {
software = instanceNodeInfo.getSoftware().getName().toUpperCase().trim();
switch (software) {
case "MASTODON":
case "PLEROMA":
oauth = new RetrofitMastodonAPI(LoginActivity.this, finalInstance, null).oauthClient(Helper.CLIENT_NAME_VALUE, Helper.REDIRECT_CONTENT_WEB, Helper.OAUTH_SCOPES_MASTODON, Helper.WEBSITE_VALUE);
break;
case "FRIENDICA":
break;
default:
oauth = new RetrofitPeertubeAPI(LoginActivity.this, finalInstance, null).oauthClient(Helper.CLIENT_NAME_VALUE, Helper.WEBSITE_VALUE, Helper.OAUTH_SCOPES_PEERTUBE, Helper.WEBSITE_VALUE);
}
} else {
oauth = new RetrofitPeertubeAPI(LoginActivity.this, finalInstance, null).oauthClient(Helper.CLIENT_NAME_VALUE, Helper.WEBSITE_VALUE, Helper.OAUTH_SCOPES_PEERTUBE, Helper.WEBSITE_VALUE);
software = "PEERTUBE";
}
private void connectToFediverse(String finalInstance) {
Oauth oauth = new RetrofitPeertubeAPI(LoginActivity.this, finalInstance, null).oauthClient(Helper.CLIENT_NAME_VALUE, Helper.WEBSITE_VALUE, Helper.OAUTH_SCOPES_PEERTUBE, Helper.WEBSITE_VALUE);
if (oauth == null) {
runOnUiThread(() -> {
binding.loginButton.setEnabled(true);
@ -190,12 +171,7 @@ public class LoginActivity extends BaseBarActivity {
oauthParams.setClient_id(client_id);
oauthParams.setClient_secret(client_secret);
oauthParams.setGrant_type("password");
final boolean isMastodonAPI = software.compareTo("MASTODON") == 0 || software.compareTo("PLEROMA") == 0;
if (software.compareTo("PEERTUBE") == 0) {
oauthParams.setScope("user");
} else if (isMastodonAPI) {
oauthParams.setScope("read write follow");
}
oauthParams.setScope("user");
if (binding.loginUid.getText() != null) {
oauthParams.setUsername(binding.loginUid.getText().toString().trim());
}
@ -203,45 +179,29 @@ public class LoginActivity extends BaseBarActivity {
oauthParams.setPassword(binding.loginPasswd.getText().toString());
}
try {
Token token = null;
if (software.compareTo("PEERTUBE") == 0) {
token = new RetrofitPeertubeAPI(LoginActivity.this, finalInstance, null).manageToken(oauthParams);
} else if (isMastodonAPI) {
Intent i = new Intent(LoginActivity.this, MastodonWebviewConnectActivity.class);
i.putExtra("software", software);
i.putExtra("instance", finalInstance);
i.putExtra("client_id", client_id);
i.putExtra("client_secret", client_secret);
startActivity(i);
return;
}
proceedLogin(token, finalInstance, software.compareTo("PEERTUBE") == 0 ? null : software);
Token token = new RetrofitPeertubeAPI(LoginActivity.this, finalInstance, null).manageToken(oauthParams);
proceedLogin(token, finalInstance);
} catch (final Exception e) {
oauthParams.setUsername(binding.loginUid.getText().toString().toLowerCase().trim());
if (software.compareTo("PEERTUBE") == 0) {
Token token = new RetrofitPeertubeAPI(LoginActivity.this, finalInstance, null).manageToken(oauthParams);
proceedLogin(token, finalInstance, software.compareTo("PEERTUBE") == 0 ? null : software);
Token token = null;
try {
token = new RetrofitPeertubeAPI(LoginActivity.this, finalInstance, null).manageToken(oauthParams);
} catch (Error ex) {
ex.printStackTrace();
}
proceedLogin(token, finalInstance);
} catch (Error e) {
e.printStackTrace();
}
}
@SuppressLint("ApplySharedPref")
private void proceedLogin(Token token, String host, String software) {
private void proceedLogin(Token token, String host) {
runOnUiThread(() -> {
if (token != null) {
boolean remote_account = software != null && software.toUpperCase().trim().compareTo("PEERTUBE") != 0;
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token.getAccess_token());
editor.putString(Helper.PREF_SOFTWARE, remote_account ? software : null);
editor.putString(Helper.PREF_REMOTE_INSTANCE, remote_account ? host : null);
if (!remote_account) {
editor.putString(Helper.PREF_INSTANCE, host);
}
editor.commit();
//Update the account with the token;
updateCredential(LoginActivity.this, token.getAccess_token(), client_id, client_secret, token.getRefresh_token(), host, software);
updateCredential(LoginActivity.this, token.getAccess_token(), client_id, client_secret, token.getRefresh_token(), host, null);
} else {
binding.loginButton.setEnabled(true);
}

View File

@ -39,9 +39,9 @@ import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.InstanceData;
import app.fedilab.android.peertube.drawer.AboutInstanceAdapter;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.sqlite.Sqlite;
import app.fedilab.android.peertube.sqlite.StoredInstanceDAO;
import app.fedilab.android.peertube.viewmodel.InfoInstanceVM;
import app.fedilab.android.sqlite.Sqlite;
public class ManageInstancesActivity extends BaseBarActivity implements AboutInstanceAdapter.AllInstancesRemoved {

View File

@ -1,192 +0,0 @@
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */
package app.fedilab.android.peertube.activities;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import app.fedilab.android.R;
import app.fedilab.android.mastodon.activities.BaseBarActivity;
import app.fedilab.android.peertube.client.entities.OauthParams;
import app.fedilab.android.peertube.client.entities.Token;
import app.fedilab.android.peertube.client.mastodon.RetrofitMastodonAPI;
import app.fedilab.android.peertube.helper.Helper;
import es.dmoral.toasty.Toasty;
public class MastodonWebviewConnectActivity extends BaseBarActivity {
private WebView webView;
private AlertDialog alert;
private String clientId, clientSecret;
private String instance, software;
@SuppressWarnings("deprecation")
public static void clearCookies(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
} else {
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
cookieSyncMngr.startSync();
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.removeSessionCookie();
cookieSyncMngr.stopSync();
cookieSyncMngr.sync();
}
}
private static String redirectUserToAuthorizeAndLogin(String clientId, String instance) {
String queryString = Helper.CLIENT_ID + "=" + clientId;
queryString += "&" + Helper.REDIRECT_URI + "=" + Uri.encode(Helper.REDIRECT_CONTENT_WEB);
queryString += "&response_type=code";
queryString += "&scope=read write follow";
return "https://" + instance + "/oauth/authorize?" + queryString;
}
@SuppressLint("SetJavaScriptEnabled")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview_connect);
Bundle b = getIntent().getExtras();
if (b != null) {
instance = b.getString("instance");
clientId = b.getString("client_id");
clientSecret = b.getString("client_secret");
software = b.getString("software");
}
if (instance == null)
finish();
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.login);
webView = findViewById(R.id.webviewConnect);
clearCookies(MastodonWebviewConnectActivity.this);
webView.getSettings().setJavaScriptEnabled(true);
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
final ProgressBar pbar = findViewById(R.id.progress_bar);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int progress) {
if (progress < 100 && pbar.getVisibility() == ProgressBar.GONE) {
pbar.setVisibility(ProgressBar.VISIBLE);
}
pbar.setProgress(progress);
if (progress == 100) {
pbar.setVisibility(ProgressBar.GONE);
}
}
});
if (instance == null) {
finish();
}
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
super.shouldOverrideUrlLoading(view, url);
if (url.contains(Helper.REDIRECT_CONTENT_WEB)) {
String[] val = url.split("code=");
if (val.length < 2) {
Toasty.error(MastodonWebviewConnectActivity.this, getString(R.string.toast_code_error), Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(MastodonWebviewConnectActivity.this, LoginActivity.class);
startActivity(myIntent);
finish();
return false;
}
String code = val[1];
if (code.contains("&")) {
code = code.split("&")[0];
}
OauthParams oauthParams = new OauthParams();
oauthParams.setClient_id(clientId);
oauthParams.setClient_secret(clientSecret);
oauthParams.setGrant_type("authorization_code");
oauthParams.setCode(code);
oauthParams.setRedirect_uri(Helper.REDIRECT_CONTENT_WEB);
new Thread(() -> {
try {
Token token = new RetrofitMastodonAPI(MastodonWebviewConnectActivity.this, instance, null).manageToken(oauthParams);
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token.getAccess_token());
editor.apply();
new RetrofitMastodonAPI(MastodonWebviewConnectActivity.this, instance, token.getAccess_token()).updateCredential(MastodonWebviewConnectActivity.this, clientId, clientSecret, token.getRefresh_token(), software);
} catch (Exception | Error ignored) {
}
}).start();
return true;
}
return false;
}
});
webView.loadUrl(redirectUserToAuthorizeAndLogin(clientId, instance));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (webView != null && webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (alert != null) {
alert.dismiss();
alert = null;
}
if (webView != null) {
webView.destroy();
}
}
}

View File

@ -51,6 +51,7 @@ import app.fedilab.android.R;
import app.fedilab.android.databinding.ActivityMyAccountSettingsPeertubeBinding;
import app.fedilab.android.mastodon.activities.BaseBarActivity;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.entities.Error;
import app.fedilab.android.peertube.client.entities.NotificationSettings;
import app.fedilab.android.peertube.client.entities.UserMe;
import app.fedilab.android.peertube.client.entities.UserSettings;

View File

@ -124,10 +124,10 @@ import java.util.regex.Pattern;
import app.fedilab.android.R;
import app.fedilab.android.activities.BasePeertubeActivity;
import app.fedilab.android.databinding.ActivityPeertubeBinding;
import app.fedilab.android.mastodon.exception.DBException;
import app.fedilab.android.peertube.client.APIResponse;
import app.fedilab.android.peertube.client.MenuItemVideo;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.peertube.client.data.CaptionData.Caption;
import app.fedilab.android.peertube.client.data.CommentData;
import app.fedilab.android.peertube.client.data.CommentData.Comment;
@ -147,8 +147,6 @@ import app.fedilab.android.peertube.drawer.MenuItemAdapter;
import app.fedilab.android.peertube.helper.CacheDataSourceFactory;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.helper.HelperInstance;
import app.fedilab.android.peertube.sqlite.AccountDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
import app.fedilab.android.peertube.viewmodel.CaptionsVM;
import app.fedilab.android.peertube.viewmodel.CommentVM;
import app.fedilab.android.peertube.viewmodel.PlaylistsVM;
@ -159,6 +157,7 @@ import app.fedilab.android.peertube.viewmodel.mastodon.MastodonPostActionsVM;
import app.fedilab.android.peertube.webview.CustomWebview;
import app.fedilab.android.peertube.webview.MastalabWebChromeClient;
import app.fedilab.android.peertube.webview.MastalabWebViewClient;
import app.fedilab.android.sqlite.Sqlite;
import es.dmoral.toasty.Toasty;
@ -224,7 +223,12 @@ public class PeertubeActivity extends BasePeertubeActivity implements CommentLis
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
if (Helper.canMakeAction(PeertubeActivity.this) && !sepiaSearch) {
Account account = new AccountDAO(PeertubeActivity.this, db).getAccountByToken(token);
Account account = null;
try {
account = new app.fedilab.android.mastodon.client.entities.app.Account(PeertubeActivity.this).getAccountByToken(token);
} catch (DBException e) {
e.printStackTrace();
}
loadAvatar(PeertubeActivity.this, account, binding.myPp);
}
isRemote = false;
@ -973,7 +977,7 @@ public class PeertubeActivity extends BasePeertubeActivity implements CommentLis
binding.ppChannel.setOnClickListener(v -> {
Intent intent = new Intent(PeertubeActivity.this, ShowChannelActivity.class);
Bundle b = new Bundle();
b.putParcelable("channel", peertube.getChannel());
b.putSerializable("channel", peertube.getChannel());
b.putBoolean("sepia_search", sepiaSearch);
if (sepiaSearch) {
b.putString("peertube_instance", peertube.getAccount().getHost());
@ -2201,7 +2205,7 @@ public class PeertubeActivity extends BasePeertubeActivity implements CommentLis
if (nextVideo != null) {
Intent intent = new Intent(PeertubeActivity.this, PeertubeActivity.class);
Bundle b = new Bundle();
b.putParcelable("video", nextVideo);
b.putSerializable("video", nextVideo);
b.putString("video_id", nextVideo.getId());
b.putString("video_uuid", nextVideo.getUuid());
playedVideos.add(nextVideo.getId());

View File

@ -61,8 +61,10 @@ import app.fedilab.android.R;
import app.fedilab.android.activities.AboutActivity;
import app.fedilab.android.activities.PeertubeBaseMainActivity;
import app.fedilab.android.databinding.ActivityMainPeertubeBinding;
import app.fedilab.android.mastodon.client.entities.app.Account;
import app.fedilab.android.mastodon.client.entities.app.BaseAccount;
import app.fedilab.android.mastodon.exception.DBException;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.peertube.client.data.InstanceData;
import app.fedilab.android.peertube.client.entities.AcadInstances;
import app.fedilab.android.peertube.client.entities.Error;
@ -79,10 +81,9 @@ import app.fedilab.android.peertube.helper.HelperAcadInstance;
import app.fedilab.android.peertube.helper.HelperInstance;
import app.fedilab.android.peertube.helper.SwitchAccountHelper;
import app.fedilab.android.peertube.services.RetrieveInfoService;
import app.fedilab.android.peertube.sqlite.AccountDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
import app.fedilab.android.peertube.sqlite.StoredInstanceDAO;
import app.fedilab.android.peertube.viewmodel.TimelineVM;
import app.fedilab.android.sqlite.Sqlite;
import es.dmoral.toasty.Toasty;
@ -219,7 +220,6 @@ public abstract class PeertubeMainActivity extends PeertubeBaseMainActivity {
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
checkIfConnectedUsers();
recentFragment = new DisplayVideosFragment();
Bundle bundle = new Bundle();
@ -354,18 +354,27 @@ public abstract class PeertubeMainActivity extends PeertubeBaseMainActivity {
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String instanceShar = sharedpreferences.getString(Helper.PREF_INSTANCE, null);
String userIdShar = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
Account account = new AccountDAO(PeertubeMainActivity.this, db).getAccountByToken(tokenStr);
BaseAccount account = null;
try {
account = new Account(PeertubeMainActivity.this).getAccountByToken(tokenStr);
} catch (DBException e) {
e.printStackTrace();
}
if (account == null) {
account = new AccountDAO(PeertubeMainActivity.this, db).getAccountByIdInstance(userIdShar, instanceShar);
try {
account = new Account(PeertubeMainActivity.this).getUniqAccount(userIdShar, instanceShar);
} catch (DBException e) {
e.printStackTrace();
}
}
if (account != null) {
Account finalAccount = account;
BaseAccount finalAccount = account;
OauthParams oauthParams = new OauthParams();
oauthParams.setGrant_type("refresh_token");
oauthParams.setClient_id(account.getClient_id());
oauthParams.setClient_secret(account.getClient_secret());
oauthParams.setRefresh_token(account.getRefresh_token());
oauthParams.setAccess_token(account.getToken());
oauthParams.setClient_id(account.client_id);
oauthParams.setClient_secret(account.client_secret);
oauthParams.setRefresh_token(account.refresh_token);
oauthParams.setAccess_token(account.token);
try {
Token token = new RetrofitPeertubeAPI(PeertubeMainActivity.this).manageToken(oauthParams);
if (token == null) {
@ -383,10 +392,15 @@ public abstract class PeertubeMainActivity extends PeertubeBaseMainActivity {
userMe = new RetrofitPeertubeAPI(PeertubeMainActivity.this, instance, token.getAccess_token()).verifyCredentials();
if (userMe != null && userMe.getAccount() != null) {
new AccountDAO(PeertubeMainActivity.this, db).updateAccount(userMe.getAccount());
account.peertube_account = userMe.getAccount();
try {
new Account(PeertubeMainActivity.this).insertOrUpdate(account);
} catch (DBException e) {
e.printStackTrace();
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_ID, account.getId());
editor.putString(Helper.PREF_KEY_NAME, account.getUsername());
editor.putString(Helper.PREF_KEY_ID, account.user_id);
editor.putString(Helper.PREF_KEY_NAME, account.peertube_account.getUsername());
editor.putBoolean(getString(R.string.set_autoplay_choice), userMe.isAutoPlayVideo());
editor.putBoolean(getString(R.string.set_store_in_history), userMe.isVideosHistoryEnabled());
editor.putBoolean(getString(R.string.set_autoplay_next_video_choice), userMe.isAutoPlayNextVideo());
@ -540,25 +554,6 @@ public abstract class PeertubeMainActivity extends PeertubeBaseMainActivity {
}
private void checkIfConnectedUsers() {
new Thread(() -> {
try {
typeOfConnection = TypeOfConnection.NORMAL;
if (!Helper.canMakeAction(PeertubeMainActivity.this)) {
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<Account> accounts = new AccountDAO(PeertubeMainActivity.this, db).getAllAccount();
if (accounts != null && accounts.size() > 0) {
//The user is not authenticated and there accounts in db. That means the user is surfing some other instances
typeOfConnection = TypeOfConnection.SURFING;
}
}
runOnUiThread(this::invalidateOptionsMenu);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
@Override
@ -623,11 +618,7 @@ public abstract class PeertubeMainActivity extends PeertubeBaseMainActivity {
type = HelperAcadInstance.MOSTLIKED;
} else if (item.getItemId() == R.id.action_playlist) {
Intent intent;
if (Helper.isLoggedIn(PeertubeMainActivity.this)) {
intent = new Intent(PeertubeMainActivity.this, AllPlaylistsActivity.class);
} else {
intent = new Intent(PeertubeMainActivity.this, AllLocalPlaylistsActivity.class);
}
intent = new Intent(PeertubeMainActivity.this, AllPlaylistsActivity.class);
startActivity(intent);
} else if (item.getItemId() == R.id.action_sepia_search) {
Intent intent = new Intent(PeertubeMainActivity.this, SepiaSearchActivity.class);

View File

@ -14,7 +14,6 @@ package app.fedilab.android.peertube.activities;
* 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.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
@ -26,14 +25,12 @@ import app.fedilab.android.mastodon.activities.BaseBarActivity;
import app.fedilab.android.peertube.client.data.PlaylistData;
import app.fedilab.android.peertube.fragment.DisplayVideosFragment;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.helper.PlaylistExportHelper;
import app.fedilab.android.peertube.viewmodel.TimelineVM;
import es.dmoral.toasty.Toasty;
public class PlaylistsActivity extends BaseBarActivity {
private final int PICK_IMPORT = 5556;
@Override
@ -70,22 +67,6 @@ public class PlaylistsActivity extends BaseBarActivity {
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMPORT && resultCode == RESULT_OK) {
if (data == null || data.getData() == null) {
Toasty.error(PlaylistsActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
return;
}
PlaylistExportHelper.manageIntentUrl(PlaylistsActivity.this, data);
} else if (requestCode == PICK_IMPORT) {
Toasty.error(PlaylistsActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

View File

@ -311,7 +311,7 @@ public class SepiaSearchActivity extends BaseBarActivity {
sepiaSearchVideo.setSearch(binding.searchBar.getText());
DisplaySepiaSearchFragment displaySepiaSearchFragment = new DisplaySepiaSearchFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("sepiaSearchVideo", sepiaSearchVideo);
bundle.putSerializable("sepiaSearchVideo", sepiaSearchVideo);
displaySepiaSearchFragment.setArguments(bundle);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, displaySepiaSearchFragment, "SEPIA_SEARCH").commit();

View File

@ -68,7 +68,7 @@ public class ShowAccountActivity extends BaseBarActivity {
private TextView account_note, subscriber_count;
private ImageView account_pp;
private TextView account_dn;
private AccountData.Account account;
private AccountData.PeertubeAccount account;
private String accountAcct;
@ -246,7 +246,7 @@ public class ShowAccountActivity extends BaseBarActivity {
public void manageViewAccounts(APIResponse apiResponse) {
if (apiResponse.getAccounts() != null && apiResponse.getAccounts().size() == 1) {
AccountData.Account account = apiResponse.getAccounts().get(0);
AccountData.PeertubeAccount account = apiResponse.getAccounts().get(0);
if (this.account == null) {
this.account = account;
manageAccount();
@ -257,7 +257,7 @@ public class ShowAccountActivity extends BaseBarActivity {
}
}
private void manageNotes(AccountData.Account account) {
private void manageNotes(AccountData.PeertubeAccount account) {
if (account.getDescription() != null && account.getDescription().compareTo("null") != 0 && account.getDescription().trim().length() > 0) {
SpannableString spannableString;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
@ -295,7 +295,7 @@ public class ShowAccountActivity extends BaseBarActivity {
}
DisplayVideosFragment displayVideosFragment = new DisplayVideosFragment();
bundle.putSerializable(Helper.TIMELINE_TYPE, TimelineVM.TimelineType.ACCOUNT_VIDEOS);
bundle.putParcelable("account", account);
bundle.putSerializable("account", account);
bundle.putString("peertube_instance", account.getHost());
displayVideosFragment.setArguments(bundle);
return displayVideosFragment;

View File

@ -26,7 +26,6 @@ import static app.fedilab.android.peertube.helper.Helper.isLoggedIn;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
@ -63,14 +62,10 @@ import app.fedilab.android.databinding.ActivityShowChannelBinding;
import app.fedilab.android.mastodon.activities.BaseBarActivity;
import app.fedilab.android.peertube.client.APIResponse;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.AccountData;
import app.fedilab.android.peertube.client.data.ChannelData.Channel;
import app.fedilab.android.peertube.drawer.OwnAccountsAdapter;
import app.fedilab.android.peertube.fragment.DisplayAccountsFragment;
import app.fedilab.android.peertube.fragment.DisplayVideosFragment;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.sqlite.AccountDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
import app.fedilab.android.peertube.viewmodel.ChannelsVM;
import app.fedilab.android.peertube.viewmodel.PostActionsVM;
import app.fedilab.android.peertube.viewmodel.RelationshipVM;
@ -116,43 +111,7 @@ public class ShowChannelActivity extends BaseBarActivity {
viewModel.get(sepiaSearch ? peertubeInstance : null, CHANNEL, channelAcct == null ? channel.getAcct() : channelAcct).observe(ShowChannelActivity.this, this::manageViewAccounts);
manageChannel();
if (PeertubeMainActivity.typeOfConnection == SURFING) {
binding.accountFollow.setText(getString(R.string.action_follow));
binding.accountFollow.setEnabled(true);
new Thread(() -> {
try {
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<AccountData.Account> accounts = new AccountDAO(ShowChannelActivity.this, db).getAllAccount();
runOnUiThread(() -> {
binding.accountFollow.setVisibility(View.VISIBLE);
binding.accountFollow.setOnClickListener(v -> {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(ShowChannelActivity.this);
builderSingle.setTitle(getString(R.string.list_of_accounts));
if (accounts != null && accounts.size() > 0) {
if (accounts.size() > 1) {
final OwnAccountsAdapter accountsListAdapter = new OwnAccountsAdapter(ShowChannelActivity.this, accounts);
builderSingle.setAdapter(accountsListAdapter, (dialog, which) -> new Thread(() -> {
try {
RetrofitPeertubeAPI peertubeAPI = new RetrofitPeertubeAPI(ShowChannelActivity.this, accounts.get(which).getHost(), accounts.get(which).getToken());
peertubeAPI.post(FOLLOW, channel.getAcct(), null);
} catch (Exception e) {
e.printStackTrace();
}
}).start());
} else {
RetrofitPeertubeAPI peertubeAPI = new RetrofitPeertubeAPI(ShowChannelActivity.this, accounts.get(0).getHost(), accounts.get(0).getToken());
peertubeAPI.post(FOLLOW, channel.getAcct(), null);
}
}
builderSingle.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
builderSingle.show();
});
});
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
@Override
@ -204,7 +163,7 @@ public class ShowChannelActivity extends BaseBarActivity {
} else if (item.getItemId() == R.id.action_display_account) {
Bundle b = new Bundle();
Intent intent = new Intent(ShowChannelActivity.this, ShowAccountActivity.class);
b.putParcelable("account", channel.getOwnerAccount());
b.putSerializable("account", channel.getOwnerAccount());
b.putString("accountAcct", channel.getOwnerAccount().getAcct());
intent.putExtras(b);
startActivity(intent);
@ -449,7 +408,7 @@ public class ShowChannelActivity extends BaseBarActivity {
DisplayVideosFragment displayVideosFragment = new DisplayVideosFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(Helper.TIMELINE_TYPE, TimelineVM.TimelineType.CHANNEL_VIDEOS);
bundle.putParcelable("channel", channel);
bundle.putSerializable("channel", channel);
bundle.putString("peertube_instance", channel.getHost());
bundle.putBoolean("sepia_search", sepiaSearch);
displayVideosFragment.setArguments(bundle);

View File

@ -1,254 +0,0 @@
package app.fedilab.android.peertube.activities;
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */
import static app.fedilab.android.peertube.client.RetrofitPeertubeAPI.updateCredential;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import androidx.appcompat.app.AlertDialog;
import java.net.URL;
import java.util.regex.Matcher;
import app.fedilab.android.R;
import app.fedilab.android.mastodon.activities.BaseBarActivity;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.entities.OauthParams;
import app.fedilab.android.peertube.client.entities.Token;
import app.fedilab.android.peertube.helper.Helper;
public class WebviewConnectActivity extends BaseBarActivity {
private WebView webView;
private AlertDialog alert;
private String clientId, clientSecret;
private String url;
@SuppressWarnings("deprecation")
public static void clearCookies(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
} else {
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
cookieSyncMngr.startSync();
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.removeSessionCookie();
cookieSyncMngr.stopSync();
cookieSyncMngr.sync();
}
}
@SuppressLint("SetJavaScriptEnabled")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
WebView.setWebContentsDebuggingEnabled(true);
setContentView(R.layout.activity_webview_connect);
Bundle b = getIntent().getExtras();
if (b != null) {
url = b.getString("url");
}
if (url == null)
finish();
clientId = sharedpreferences.getString(Helper.CLIENT_ID, null);
clientSecret = sharedpreferences.getString(Helper.CLIENT_SECRET, null);
webView = findViewById(R.id.webviewConnect);
clearCookies(WebviewConnectActivity.this);
webView.getSettings().setJavaScriptEnabled(true);
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setSupportMultipleWindows(false);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webView.getSettings().setMediaPlaybackRequiresUserGesture(true);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.login);
final ProgressBar pbar = findViewById(R.id.progress_bar);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int progress) {
if (progress < 100 && pbar.getVisibility() == ProgressBar.GONE) {
pbar.setVisibility(ProgressBar.VISIBLE);
}
pbar.setProgress(progress);
if (progress == 100) {
pbar.setVisibility(ProgressBar.GONE);
}
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
//Avoid to load first page for academic instances & openid
if (url.contains("/client")) {
view.stopLoading();
}
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl() != null) {
String url = request.getUrl().toString();
Matcher matcher = Helper.redirectPattern.matcher(url);
if (matcher.find()) {
String externalAuthToken = matcher.group(1);
String username = matcher.group(2);
new Thread(() -> {
try {
OauthParams oauthParams = new OauthParams();
oauthParams.setClient_id(sharedpreferences.getString(Helper.CLIENT_ID, null));
oauthParams.setClient_secret(sharedpreferences.getString(Helper.CLIENT_SECRET, null));
oauthParams.setGrant_type("password");
oauthParams.setScope("upload");
oauthParams.setResponse_type("code");
oauthParams.setUsername(username);
oauthParams.setExternalAuthToken(externalAuthToken);
oauthParams.setPassword(externalAuthToken);
String instance = new URL(url).getHost();
Token token = null;
token = new RetrofitPeertubeAPI(WebviewConnectActivity.this, instance, null).manageToken(oauthParams);
if (token != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token.getAccess_token());
editor.putString(Helper.PREF_SOFTWARE, null);
editor.putString(Helper.PREF_REMOTE_INSTANCE, null);
editor.putString(Helper.PREF_INSTANCE, instance);
editor.apply();
updateCredential(WebviewConnectActivity.this, token.getAccess_token(), clientId, clientSecret, token.getRefresh_token(), new URL(url).getHost(), null);
finish();
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
return true;
}
}
return super.shouldOverrideUrlLoading(view, request);
}
/* @Override
public void onPageFinished(WebView view, String url) {
Matcher matcher = Helper.redirectPattern.matcher(url);
if (matcher.find()) {
String externalAuthToken = matcher.group(1);
String username = matcher.group(2);
new Thread(() -> {
try {
OauthParams oauthParams = new OauthParams();
oauthParams.setClient_id(sharedpreferences.getString(Helper.CLIENT_ID, null));
oauthParams.setClient_secret(sharedpreferences.getString(Helper.CLIENT_SECRET, null));
oauthParams.setGrant_type("password");
oauthParams.setScope("upload");
oauthParams.setResponse_type("code");
oauthParams.setUsername(username);
oauthParams.setExternalAuthToken(externalAuthToken);
oauthParams.setPassword(externalAuthToken);
String instance = new URL(url).getHost();
Token token = null;
try {
token = new RetrofitPeertubeAPI(WebviewConnectActivity.this, instance, null).manageToken(oauthParams);
} catch (Error error) {
error.printStackTrace();
Error.displayError(WebviewConnectActivity.this, error);
}
if (token != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token.getAccess_token());
editor.putString(Helper.PREF_SOFTWARE, null);
editor.putString(Helper.PREF_REMOTE_INSTANCE, null);
editor.putString(Helper.PREF_INSTANCE, instance);
editor.apply();
updateCredential(WebviewConnectActivity.this, token.getAccess_token(), clientId, clientSecret, token.getRefresh_token(), new URL(url).getHost(), null);
finish();
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
super.onPageFinished(view, url);
}*/
});
webView.loadUrl(url);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (webView != null && webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (alert != null) {
alert.dismiss();
alert = null;
}
if (webView != null) {
webView.destroy();
}
}
}

View File

@ -35,7 +35,7 @@ import app.fedilab.android.peertube.client.entities.Rating;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class APIResponse {
private List<AccountData.Account> accounts = null;
private List<AccountData.PeertubeAccount> accounts = null;
private List<ChannelData.Channel> channels = null;
private String targetedId = null;
private String actionReturn = null;
@ -59,11 +59,11 @@ public class APIResponse {
private int statusCode;
private String captionText;
public List<AccountData.Account> getAccounts() {
public List<AccountData.PeertubeAccount> getAccounts() {
return accounts;
}
public void setAccounts(List<AccountData.Account> accounts) {
public void setAccounts(List<AccountData.PeertubeAccount> accounts) {
this.accounts = accounts;
}

View File

@ -394,7 +394,7 @@ public interface PeertubeService {
//Get a single account
@GET("accounts/{accountHandle}")
Call<AccountData.Account> getAccount(@Path("accountHandle") String accountHandle);
Call<AccountData.PeertubeAccount> getAccount(@Path("accountHandle") String accountHandle);
//Get/Post/Update/Delete playlist
@GET("accounts/{accountHandle}/video-playlists")

View File

@ -47,6 +47,8 @@ import java.util.Set;
import java.util.concurrent.TimeUnit;
import app.fedilab.android.R;
import app.fedilab.android.mastodon.client.entities.app.Account;
import app.fedilab.android.mastodon.exception.DBException;
import app.fedilab.android.peertube.activities.PeertubeMainActivity;
import app.fedilab.android.peertube.client.data.AccountData;
import app.fedilab.android.peertube.client.data.BlockData;
@ -78,12 +80,11 @@ import app.fedilab.android.peertube.client.entities.VideoParams;
import app.fedilab.android.peertube.client.entities.WellKnownNodeinfo;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.helper.HelperInstance;
import app.fedilab.android.peertube.sqlite.AccountDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
import app.fedilab.android.peertube.viewmodel.ChannelsVM;
import app.fedilab.android.peertube.viewmodel.CommentVM;
import app.fedilab.android.peertube.viewmodel.PlaylistsVM;
import app.fedilab.android.peertube.viewmodel.TimelineVM;
import app.fedilab.android.sqlite.Sqlite;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
@ -146,11 +147,12 @@ public class RetrofitPeertubeAPI {
public static void updateCredential(Activity activity, String token, String client_id, String client_secret, String refresh_token, String host, String software) {
new Thread(() -> {
AccountData.Account account;
AccountData.PeertubeAccount peertubeAccount;
Account account = new Account();
String instance = host;
try {
UserMe userMe = new RetrofitPeertubeAPI(activity, instance, token).verifyCredentials();
account = userMe.getAccount();
peertubeAccount = userMe.getAccount();
} catch (Error error) {
Error.displayError(activity, error);
error.printStackTrace();
@ -162,27 +164,25 @@ public class RetrofitPeertubeAPI {
} catch (UnsupportedEncodingException ignored) {
}
SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
account.setToken(token);
account.setClient_id(client_id);
account.setClient_secret(client_secret);
account.setRefresh_token(refresh_token);
account.setHost(instance);
account.token = token;
account.client_id = client_id;
account.client_secret = client_secret;
account.refresh_token = refresh_token;
account.instance = instance;
account.peertube_account = peertubeAccount;
SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
boolean userExists = new AccountDAO(activity, db).userExist(account);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_ID, account.getId());
editor.putString(Helper.PREF_KEY_NAME, account.getUsername());
boolean remote_account = software != null && software.toUpperCase().trim().compareTo("PEERTUBE") != 0;
if (!remote_account) {
boolean userExists = false;
try {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_ID, account.user_id);
editor.putString(Helper.PREF_KEY_NAME, peertubeAccount.getUsername());
editor.putString(Helper.PREF_INSTANCE, host);
editor.apply();
new Account(activity).insertOrUpdate(account);
} catch (DBException e) {
e.printStackTrace();
}
editor.apply();
if (userExists)
new AccountDAO(activity, db).updateAccountCredential(account);
else {
if (account.getUsername() != null && account.getCreatedAt() != null)
new AccountDAO(activity, db).insertAccount(account, software);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
Intent mainActivity = new Intent(activity, PeertubeMainActivity.class);
@ -255,7 +255,7 @@ public class RetrofitPeertubeAPI {
editor.putString(Helper.PREF_REMOTE_INSTANCE, null);
editor.apply();
SQLiteDatabase db = Sqlite.getInstance(_context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
new AccountDAO(_context, db).updateAccountToken(tokenReply);
new Account(_context).updatePeertubeToken(tokenReply);
}
return tokenReply;
} else {
@ -268,7 +268,7 @@ public class RetrofitPeertubeAPI {
}
throw error;
}
} catch (IOException e) {
} catch (IOException | DBException e) {
e.printStackTrace();
}
}
@ -1356,13 +1356,13 @@ public class RetrofitPeertubeAPI {
*/
public APIResponse getAccount(String accountHandle) {
PeertubeService peertubeService = init();
Call<AccountData.Account> accountDataCall = peertubeService.getAccount(accountHandle);
Call<AccountData.PeertubeAccount> accountDataCall = peertubeService.getAccount(accountHandle);
APIResponse apiResponse = new APIResponse();
if (accountDataCall != null) {
try {
Response<AccountData.Account> response = accountDataCall.execute();
Response<AccountData.PeertubeAccount> response = accountDataCall.execute();
if (response.isSuccessful() && response.body() != null) {
List<AccountData.Account> accountList = new ArrayList<>();
List<AccountData.PeertubeAccount> accountList = new ArrayList<>();
accountList.add(response.body());
apiResponse.setAccounts(accountList);
} else {

View File

@ -14,11 +14,10 @@ package app.fedilab.android.peertube.client.data;
* 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.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@ -26,25 +25,14 @@ import app.fedilab.android.peertube.client.entities.Avatar;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class AccountData {
public class AccountData implements Serializable {
@SerializedName("total")
public int total;
@SerializedName("data")
public List<Account> data;
public List<PeertubeAccount> data;
public static class Account implements Parcelable {
public static final Creator<Account> CREATOR = new Creator<Account>() {
@Override
public Account createFromParcel(Parcel source) {
return new Account(source);
}
@Override
public Account[] newArray(int size) {
return new Account[size];
}
};
public static class PeertubeAccount implements Serializable {
@SerializedName("avatar")
private Avatar avatar;
@SerializedName("createdAt")
@ -73,33 +61,11 @@ public class AccountData {
private String url;
@SerializedName("userId")
private String userId;
private String token;
private String client_id;
private String client_secret;
private String refresh_token;
private String software;
public Account() {
public PeertubeAccount() {
}
protected Account(Parcel in) {
this.avatar = in.readParcelable(Avatar.class.getClassLoader());
long tmpCreatedAt = in.readLong();
this.createdAt = tmpCreatedAt == -1 ? null : new Date(tmpCreatedAt);
this.description = in.readString();
this.displayName = in.readString();
this.followersCount = in.readInt();
this.followingCount = in.readInt();
this.host = in.readString();
this.hostRedundancyAllowed = in.readByte() != 0;
this.id = in.readString();
this.name = in.readString();
this.username = in.readString();
long tmpUpdatedAt = in.readLong();
this.updatedAt = tmpUpdatedAt == -1 ? null : new Date(tmpUpdatedAt);
this.url = in.readString();
this.userId = in.readString();
}
public Avatar getAvatar() {
return avatar;
@ -201,37 +167,6 @@ public class AccountData {
return name + "@" + host;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getClient_id() {
return client_id;
}
public void setClient_id(String client_id) {
this.client_id = client_id;
}
public String getClient_secret() {
return client_secret;
}
public void setClient_secret(String client_secret) {
this.client_secret = client_secret;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getUserId() {
return userId;
@ -241,35 +176,5 @@ public class AccountData {
this.userId = userId;
}
public String getSoftware() {
return software;
}
public void setSoftware(String software) {
this.software = software;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(this.avatar, flags);
dest.writeLong(this.createdAt != null ? this.createdAt.getTime() : -1);
dest.writeString(this.description);
dest.writeString(this.displayName);
dest.writeInt(this.followersCount);
dest.writeInt(this.followingCount);
dest.writeString(this.host);
dest.writeByte(this.hostRedundancyAllowed ? (byte) 1 : (byte) 0);
dest.writeString(this.id);
dest.writeString(this.name);
dest.writeString(this.username);
dest.writeLong(this.updatedAt != null ? this.updatedAt.getTime() : -1);
dest.writeString(this.url);
dest.writeString(this.userId);
}
}
}

View File

@ -46,25 +46,25 @@ public class BlockData {
@SuppressWarnings("unused")
public static class Block {
@SerializedName("blockedAccount")
private AccountData.Account blockedAccount;
private AccountData.PeertubeAccount blockedAccount;
@SerializedName("byAccount")
private AccountData.Account byAccount;
private AccountData.PeertubeAccount byAccount;
@SerializedName("createdAt")
private Date createdAt;
public AccountData.Account getBlockedAccount() {
public AccountData.PeertubeAccount getBlockedAccount() {
return blockedAccount;
}
public void setBlockedAccount(AccountData.Account blockedAccount) {
public void setBlockedAccount(AccountData.PeertubeAccount blockedAccount) {
this.blockedAccount = blockedAccount;
}
public AccountData.Account getByAccount() {
public AccountData.PeertubeAccount getByAccount() {
return byAccount;
}
public void setByAccount(AccountData.Account byAccount) {
public void setByAccount(AccountData.PeertubeAccount byAccount) {
this.byAccount = byAccount;
}

View File

@ -14,12 +14,10 @@ package app.fedilab.android.peertube.client.data;
* 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.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@ -35,18 +33,8 @@ public class ChannelData {
@SerializedName("data")
public List<Channel> data;
public static class Channel implements Parcelable {
public static final Creator<Channel> CREATOR = new Creator<Channel>() {
@Override
public Channel createFromParcel(Parcel source) {
return new Channel(source);
}
public static class Channel implements Serializable {
@Override
public Channel[] newArray(int size) {
return new Channel[size];
}
};
@SerializedName("avatar")
private Avatar avatar;
@SerializedName("createdAt")
@ -70,7 +58,7 @@ public class ChannelData {
@SerializedName("name")
private String name;
@SerializedName("ownerAccount")
private AccountData.Account ownerAccount;
private AccountData.PeertubeAccount ownerAccount;
@SerializedName("support")
private String support;
@SerializedName("updatedAt")
@ -85,28 +73,6 @@ public class ChannelData {
public Channel() {
}
protected Channel(Parcel in) {
this.avatar = in.readParcelable(Avatar.class.getClassLoader());
long tmpCreatedAt = in.readLong();
this.createdAt = tmpCreatedAt == -1 ? null : new Date(tmpCreatedAt);
this.description = in.readString();
this.displayName = in.readString();
this.followersCount = in.readInt();
this.followingCount = in.readInt();
this.host = in.readString();
this.hostRedundancyAllowed = in.readByte() != 0;
this.id = in.readString();
this.isLocal = in.readByte() != 0;
this.name = in.readString();
this.ownerAccount = in.readParcelable(AccountData.Account.class.getClassLoader());
this.support = in.readString();
long tmpUpdatedAt = in.readLong();
this.updatedAt = tmpUpdatedAt == -1 ? null : new Date(tmpUpdatedAt);
this.url = in.readString();
this.viewsPerDays = new ArrayList<>();
in.readList(this.viewsPerDays, ViewsPerDay.class.getClassLoader());
this.acct = in.readString();
}
public Avatar getAvatar() {
return avatar;
@ -204,11 +170,11 @@ public class ChannelData {
this.name = name;
}
public AccountData.Account getOwnerAccount() {
public AccountData.PeertubeAccount getOwnerAccount() {
return ownerAccount;
}
public void setOwnerAccount(AccountData.Account ownerAccount) {
public void setOwnerAccount(AccountData.PeertubeAccount ownerAccount) {
this.ownerAccount = ownerAccount;
}
@ -251,32 +217,6 @@ public class ChannelData {
public void setSelected(boolean selected) {
this.selected = selected;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(this.avatar, flags);
dest.writeLong(this.createdAt != null ? this.createdAt.getTime() : -1);
dest.writeString(this.description);
dest.writeString(this.displayName);
dest.writeInt(this.followersCount);
dest.writeInt(this.followingCount);
dest.writeString(this.host);
dest.writeByte(this.hostRedundancyAllowed ? (byte) 1 : (byte) 0);
dest.writeString(this.id);
dest.writeByte(this.isLocal ? (byte) 1 : (byte) 0);
dest.writeString(this.name);
dest.writeParcelable(this.ownerAccount, flags);
dest.writeString(this.support);
dest.writeLong(this.updatedAt != null ? this.updatedAt.getTime() : -1);
dest.writeString(this.url);
dest.writeList(this.viewsPerDays);
dest.writeString(this.acct);
}
}
public static class ChannelCreation {

View File

@ -16,6 +16,7 @@ package app.fedilab.android.peertube.client.data;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@ -28,10 +29,10 @@ public class CommentData {
public List<Comment> data;
public static class Comment {
public static class Comment implements Serializable {
@SerializedName("account")
private AccountData.Account account;
private AccountData.PeertubeAccount account;
@SerializedName("createdAt")
private Date createdAt;
@SerializedName("deletedAt")
@ -60,11 +61,11 @@ public class CommentData {
private boolean isReplyViewOpen = false;
public AccountData.Account getAccount() {
public AccountData.PeertubeAccount getAccount() {
return account;
}
public void setAccount(AccountData.Account account) {
public void setAccount(AccountData.PeertubeAccount account) {
this.account = account;
}
@ -228,7 +229,7 @@ public class CommentData {
@SerializedName("video")
private VideoData.Video video;
@SerializedName("account")
private AccountData.Account account;
private AccountData.PeertubeAccount account;
public String getId() {
return id;
@ -254,11 +255,11 @@ public class CommentData {
this.video = video;
}
public AccountData.Account getAccount() {
public AccountData.PeertubeAccount getAccount() {
return account;
}
public void setAccount(AccountData.Account account) {
public void setAccount(AccountData.PeertubeAccount account) {
this.account = account;
}
}

View File

@ -14,8 +14,7 @@ package app.fedilab.android.peertube.client.data;
* 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.os.Parcel;
import android.os.Parcelable;
import android.text.SpannableStringBuilder;
import com.google.gson.annotations.SerializedName;
@ -25,7 +24,7 @@ import java.util.Date;
import java.util.List;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class InstanceData {
public class InstanceData implements Serializable {
@SerializedName("total")
public int total;
@ -33,7 +32,7 @@ public class InstanceData {
public List<Instance> data;
public static class Instance {
public static class Instance implements Serializable {
@SerializedName("autoBlacklistUserVideosEnabled")
private boolean autoBlacklistUserVideosEnabled;
@ -278,19 +277,8 @@ public class InstanceData {
}
}
public static class AboutInstance implements Parcelable, Serializable {
public static class AboutInstance implements Serializable {
public static final Creator<AboutInstance> CREATOR = new Creator<AboutInstance>() {
@Override
public AboutInstance createFromParcel(Parcel in) {
return new AboutInstance(in);
}
@Override
public AboutInstance[] newArray(int size) {
return new AboutInstance[size];
}
};
@SerializedName("name")
private String name;
@SerializedName("shortDescription")
@ -305,13 +293,6 @@ public class InstanceData {
public AboutInstance() {
}
protected AboutInstance(Parcel in) {
name = in.readString();
shortDescription = in.readString();
description = in.readString();
terms = in.readString();
host = in.readString();
}
public String getName() {
return name;
@ -361,23 +342,11 @@ public class InstanceData {
this.truncatedDescription = truncatedDescription;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(shortDescription);
parcel.writeString(description);
parcel.writeString(terms);
parcel.writeString(host);
}
}
public static class InstanceConfig {
public static class InstanceConfig implements Serializable {
@SerializedName("user")
private User user;
@SerializedName("plugin")
@ -401,7 +370,7 @@ public class InstanceData {
}
public static class User {
public static class User implements Serializable {
@SerializedName("videoQuota")
private long videoQuota;
@SerializedName("videoQuotaDaily")

View File

@ -51,7 +51,7 @@ public class NotificationData {
@SerializedName("videoBlacklist")
private VideoBlacklist videoBlacklist;
@SerializedName("account")
private AccountData.Account account;
private AccountData.PeertubeAccount account;
@SerializedName("actorFollow")
private ActorFollow actorFollow;
@SerializedName("createdAt")
@ -124,11 +124,11 @@ public class NotificationData {
this.videoBlacklist = videoBlacklist;
}
public AccountData.Account getAccount() {
public AccountData.PeertubeAccount getAccount() {
return account;
}
public void setAccount(AccountData.Account account) {
public void setAccount(AccountData.PeertubeAccount account) {
this.account = account;
}

View File

@ -14,11 +14,10 @@ package app.fedilab.android.peertube.client.data;
* 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.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@ -32,18 +31,8 @@ public class PlaylistData {
@SerializedName("data")
public List<Playlist> data;
public static class Playlist implements Parcelable {
public static final Creator<Playlist> CREATOR = new Creator<Playlist>() {
@Override
public Playlist createFromParcel(Parcel source) {
return new Playlist(source);
}
public static class Playlist implements Serializable {
@Override
public Playlist[] newArray(int size) {
return new Playlist[size];
}
};
@SerializedName("id")
private String id;
@SerializedName("createdAt")
@ -67,31 +56,13 @@ public class PlaylistData {
@SerializedName("type")
private Item type;
@SerializedName("ownerAccount")
private AccountData.Account ownerAccount;
private AccountData.PeertubeAccount ownerAccount;
@SerializedName("videoChannel")
private ChannelData.Channel videoChannel;
public Playlist() {
}
protected Playlist(Parcel in) {
this.id = in.readString();
long tmpCreatedAt = in.readLong();
this.createdAt = tmpCreatedAt == -1 ? null : new Date(tmpCreatedAt);
long tmpUpdatedAt = in.readLong();
this.updatedAt = tmpUpdatedAt == -1 ? null : new Date(tmpUpdatedAt);
this.description = in.readString();
this.uuid = in.readString();
this.displayName = in.readString();
this.isLocal = in.readByte() != 0;
this.videoLength = in.readLong();
this.thumbnailPath = in.readString();
this.privacy = in.readParcelable(Item.class.getClassLoader());
this.type = in.readParcelable(Item.class.getClassLoader());
this.ownerAccount = in.readParcelable(AccountData.Account.class.getClassLoader());
this.videoChannel = in.readParcelable(ChannelData.Channel.class.getClassLoader());
}
public String getId() {
return id;
}
@ -180,11 +151,11 @@ public class PlaylistData {
this.type = type;
}
public AccountData.Account getOwnerAccount() {
public AccountData.PeertubeAccount getOwnerAccount() {
return ownerAccount;
}
public void setOwnerAccount(AccountData.Account ownerAccount) {
public void setOwnerAccount(AccountData.PeertubeAccount ownerAccount) {
this.ownerAccount = ownerAccount;
}
@ -196,27 +167,6 @@ public class PlaylistData {
this.videoChannel = videoChannel;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeLong(this.createdAt != null ? this.createdAt.getTime() : -1);
dest.writeLong(this.updatedAt != null ? this.updatedAt.getTime() : -1);
dest.writeString(this.description);
dest.writeString(this.uuid);
dest.writeString(this.displayName);
dest.writeByte(this.isLocal ? (byte) 1 : (byte) 0);
dest.writeLong(this.videoLength);
dest.writeString(this.thumbnailPath);
dest.writeParcelable(this.privacy, flags);
dest.writeParcelable(this.type, flags);
dest.writeParcelable(this.ownerAccount, flags);
dest.writeParcelable(this.videoChannel, flags);
}
}
}

View File

@ -17,16 +17,14 @@ package app.fedilab.android.peertube.client.data;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.peertube.client.entities.File;
import app.fedilab.android.peertube.client.entities.Item;
import app.fedilab.android.peertube.client.entities.ItemStr;
@ -36,7 +34,7 @@ import app.fedilab.android.peertube.helper.Helper;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class VideoData {
public class VideoData implements Serializable {
@SerializedName("total")
public int total;
@ -44,20 +42,9 @@ public class VideoData {
public List<Video> data;
public static class Video implements Parcelable {
public static final Creator<Video> CREATOR = new Creator<Video>() {
@Override
public Video createFromParcel(Parcel source) {
return new Video(source);
}
@Override
public Video[] newArray(int size) {
return new Video[size];
}
};
public static class Video implements Serializable {
@SerializedName("account")
private Account account;
private AccountData.PeertubeAccount account;
@SerializedName("blacklisted")
private boolean blacklisted;
@SerializedName("blacklistedReason")
@ -145,55 +132,6 @@ public class VideoData {
public Video() {
}
protected Video(Parcel in) {
this.account = in.readParcelable(Account.class.getClassLoader());
this.blacklisted = in.readByte() != 0;
this.blacklistedReason = in.readString();
this.category = in.readParcelable(Item.class.getClassLoader());
this.channel = in.readParcelable(ChannelData.Channel.class.getClassLoader());
this.commentsEnabled = in.readByte() != 0;
long tmpCreatedAt = in.readLong();
this.createdAt = tmpCreatedAt == -1 ? null : new Date(tmpCreatedAt);
this.description = in.readString();
this.descriptionPath = in.readString();
this.dislikes = in.readInt();
this.downloadEnabled = in.readByte() != 0;
this.duration = in.readInt();
this.embedPath = in.readString();
this.embedUrl = in.readString();
this.files = new ArrayList<>();
in.readList(this.files, File.class.getClassLoader());
this.id = in.readString();
this.isLive = in.readByte() != 0;
this.isLocal = in.readByte() != 0;
this.language = in.readParcelable(ItemStr.class.getClassLoader());
this.licence = in.readParcelable(Item.class.getClassLoader());
this.likes = in.readInt();
this.name = in.readString();
this.nsfw = in.readByte() != 0;
long tmpOriginallyPublishedAt = in.readLong();
this.originallyPublishedAt = tmpOriginallyPublishedAt == -1 ? null : new Date(tmpOriginallyPublishedAt);
this.previewPath = in.readString();
this.privacy = in.readParcelable(Item.class.getClassLoader());
long tmpPublishedAt = in.readLong();
this.publishedAt = tmpPublishedAt == -1 ? null : new Date(tmpPublishedAt);
this.state = in.readParcelable(Item.class.getClassLoader());
this.streamingPlaylists = new ArrayList<>();
in.readList(this.streamingPlaylists, StreamingPlaylists.class.getClassLoader());
this.support = in.readString();
this.tags = in.createStringArrayList();
this.thumbnailPath = in.readString();
this.trackerUrls = in.createStringArrayList();
long tmpUpdatedAt = in.readLong();
this.updatedAt = tmpUpdatedAt == -1 ? null : new Date(tmpUpdatedAt);
this.userHistory = in.readParcelable(UserHistory.class.getClassLoader());
this.uuid = in.readString();
this.views = in.readInt();
this.waitTranscoding = in.readByte() != 0;
this.myRating = in.readString();
}
public String getFileUrl(String resolution, Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int mode = sharedpreferences.getInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_NORMAL);
@ -273,11 +211,11 @@ public class VideoData {
return files != null && files.size() > 0 ? files.get(0).getFileDownloadUrl() : null;
}
public Account getAccount() {
public AccountData.PeertubeAccount getAccount() {
return account;
}
public void setAccount(Account account) {
public void setAccount(AccountData.PeertubeAccount account) {
this.account = account;
}
@ -641,54 +579,6 @@ public class VideoData {
this.userHistory = userHistory;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(this.account, flags);
dest.writeByte(this.blacklisted ? (byte) 1 : (byte) 0);
dest.writeString(this.blacklistedReason);
dest.writeParcelable(this.category, flags);
dest.writeParcelable(this.channel, flags);
dest.writeByte(this.commentsEnabled ? (byte) 1 : (byte) 0);
dest.writeLong(this.createdAt != null ? this.createdAt.getTime() : -1);
dest.writeString(this.description);
dest.writeString(this.descriptionPath);
dest.writeInt(this.dislikes);
dest.writeByte(this.downloadEnabled ? (byte) 1 : (byte) 0);
dest.writeInt(this.duration);
dest.writeString(this.embedPath);
dest.writeString(this.embedUrl);
dest.writeList(this.files);
dest.writeString(this.id);
dest.writeByte(this.isLive ? (byte) 1 : (byte) 0);
dest.writeByte(this.isLocal ? (byte) 1 : (byte) 0);
dest.writeParcelable(this.language, flags);
dest.writeParcelable(this.licence, flags);
dest.writeInt(this.likes);
dest.writeString(this.name);
dest.writeByte(this.nsfw ? (byte) 1 : (byte) 0);
dest.writeLong(this.originallyPublishedAt != null ? this.originallyPublishedAt.getTime() : -1);
dest.writeString(this.previewPath);
dest.writeParcelable(this.privacy, flags);
dest.writeLong(this.publishedAt != null ? this.publishedAt.getTime() : -1);
dest.writeParcelable(this.state, flags);
dest.writeList(this.streamingPlaylists);
dest.writeString(this.support);
dest.writeStringList(this.tags);
dest.writeString(this.thumbnailPath);
dest.writeStringList(this.trackerUrls);
dest.writeLong(this.updatedAt != null ? this.updatedAt.getTime() : -1);
dest.writeParcelable(this.userHistory, flags);
dest.writeString(this.uuid);
dest.writeInt(this.views);
dest.writeByte(this.waitTranscoding ? (byte) 1 : (byte) 0);
dest.writeString(this.myRating);
}
public enum titleType {
TAG,
CATEGORY,
@ -696,7 +586,7 @@ public class VideoData {
}
}
public static class VideoImport {
public static class VideoImport implements Serializable {
@SerializedName("id")
private String id;
@SerializedName("video")
@ -751,19 +641,8 @@ public class VideoData {
}
public static class UserHistory implements Parcelable {
public static class UserHistory implements Serializable {
public static final Creator<UserHistory> CREATOR = new Creator<UserHistory>() {
@Override
public UserHistory createFromParcel(Parcel in) {
return new UserHistory(in);
}
@Override
public UserHistory[] newArray(int size) {
return new UserHistory[size];
}
};
@SerializedName("currentTime")
long currentTime;
@ -771,11 +650,6 @@ public class VideoData {
public UserHistory() {
}
protected UserHistory(Parcel in) {
this.currentTime = in.readLong();
}
public long getCurrentTime() {
return currentTime;
}
@ -784,19 +658,10 @@ public class VideoData {
this.currentTime = currentTime;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeLong(currentTime);
}
}
public static class Description {
public static class Description implements Serializable {
@SerializedName("description")
private String description;
@ -810,18 +675,8 @@ public class VideoData {
}
public static class VideoExport implements Parcelable {
public static final Creator<VideoExport> CREATOR = new Creator<VideoExport>() {
@Override
public VideoExport createFromParcel(Parcel in) {
return new VideoExport(in);
}
public static class VideoExport implements Serializable {
@Override
public VideoExport[] newArray(int size) {
return new VideoExport[size];
}
};
private int id;
private String uuid;
private Video videoData;
@ -830,12 +685,6 @@ public class VideoData {
public VideoExport() {
}
protected VideoExport(Parcel in) {
id = in.readInt();
uuid = in.readString();
videoData = in.readParcelable(Video.class.getClassLoader());
playlistDBid = in.readInt();
}
public int getId() {
return id;
@ -869,17 +718,5 @@ public class VideoData {
this.playlistDBid = playlistDBid;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(id);
parcel.writeString(uuid);
parcel.writeParcelable(videoData, i);
parcel.writeInt(playlistDBid);
}
}
}

View File

@ -15,16 +15,15 @@ package app.fedilab.android.peertube.client.data;
* see <http://www.gnu.org/licenses>. */
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class VideoPlaylistData {
public class VideoPlaylistData implements Serializable {
@SerializedName("total")
public int total;
@ -47,7 +46,7 @@ public class VideoPlaylistData {
this.data = data;
}
public static class VideoPlaylist {
public static class VideoPlaylist implements Serializable {
@SerializedName("id")
private String id;
@SerializedName("position")
@ -110,7 +109,7 @@ public class VideoPlaylistData {
}
}
public static class VideoPlaylistCreation {
public static class VideoPlaylistCreation implements Serializable {
@SerializedName("videoPlaylist")
private VideoPlaylistCreationItem videoPlaylist;
@ -123,7 +122,7 @@ public class VideoPlaylistData {
}
}
public static class PlaylistElement {
public static class PlaylistElement implements Serializable {
@SerializedName("videoPlaylistElement")
private VideoPlaylistCreationItem videoPlaylistElement;
@ -136,7 +135,7 @@ public class VideoPlaylistData {
}
}
public static class VideoPlaylistCreationItem {
public static class VideoPlaylistCreationItem implements Serializable {
@SerializedName("id")
String id;
@SerializedName("uuid")
@ -159,19 +158,8 @@ public class VideoPlaylistData {
}
}
public static class VideoPlaylistExport implements Parcelable {
public static class VideoPlaylistExport implements Serializable {
public static final Creator<VideoPlaylistExport> CREATOR = new Creator<VideoPlaylistExport>() {
@Override
public VideoPlaylistExport createFromParcel(Parcel in) {
return new VideoPlaylistExport(in);
}
@Override
public VideoPlaylistExport[] newArray(int size) {
return new VideoPlaylistExport[size];
}
};
private long playlistDBkey;
private String acct;
private String uuid;
@ -182,13 +170,6 @@ public class VideoPlaylistData {
public VideoPlaylistExport() {
}
protected VideoPlaylistExport(Parcel in) {
playlistDBkey = in.readLong();
acct = in.readString();
uuid = in.readString();
playlist = in.readParcelable(PlaylistData.Playlist.class.getClassLoader());
in.readList(this.videos, VideoPlaylist.class.getClassLoader());
}
public String getAcct() {
return acct;
@ -230,18 +211,5 @@ public class VideoPlaylistData {
this.videos = videos;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeLong(playlistDBkey);
parcel.writeString(acct);
parcel.writeString(uuid);
parcel.writeParcelable(playlist, i);
parcel.writeList(videos);
}
}
}

View File

@ -1,10 +1,8 @@
package app.fedilab.android.peertube.client.entities;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Date;
/* Copyright 2020 Thomas Schneider
@ -22,20 +20,9 @@ import java.util.Date;
* You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */
@SuppressWarnings({"unused", "RedundantSuppression"})
public class Avatar implements Parcelable {
public class Avatar implements Serializable {
public static final Creator<Avatar> CREATOR = new Creator<Avatar>() {
@Override
public Avatar createFromParcel(Parcel source) {
return new Avatar(source);
}
@Override
public Avatar[] newArray(int size) {
return new Avatar[size];
}
};
@SerializedName("createdAt")
private Date createdAt;
@SerializedName("path")
@ -46,13 +33,6 @@ public class Avatar implements Parcelable {
public Avatar() {
}
protected Avatar(Parcel in) {
long tmpCreatedAt = in.readLong();
this.createdAt = tmpCreatedAt == -1 ? null : new Date(tmpCreatedAt);
this.path = in.readString();
long tmpUpdatedAt = in.readLong();
this.updatedAt = tmpUpdatedAt == -1 ? null : new Date(tmpUpdatedAt);
}
public Date getCreatedAt() {
return createdAt;
@ -78,15 +58,4 @@ public class Avatar implements Parcelable {
this.updatedAt = updatedAt;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.createdAt != null ? this.createdAt.getTime() : -1);
dest.writeString(this.path);
dest.writeLong(this.updatedAt != null ? this.updatedAt.getTime() : -1);
}
}

View File

@ -1,25 +1,14 @@
package app.fedilab.android.peertube.client.entities;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class File implements Parcelable {
public class File implements Serializable {
public static final Creator<File> CREATOR = new Creator<File>() {
@Override
public File createFromParcel(Parcel source) {
return new File(source);
}
@Override
public File[] newArray(int size) {
return new File[size];
}
};
@SerializedName("fileDownloadUrl")
private String fileDownloadUrl;
@SerializedName("fileUrl")
@ -42,18 +31,6 @@ public class File implements Parcelable {
public File() {
}
protected File(Parcel in) {
this.fileDownloadUrl = in.readString();
this.fileUrl = in.readString();
this.fps = in.readInt();
this.magnetUri = in.readString();
this.metadataUrl = in.readString();
this.resolutions = in.readParcelable(Item.class.getClassLoader());
this.size = in.readLong();
this.torrentDownloadUrl = in.readString();
this.torrentUrl = in.readString();
}
public String getFileDownloadUrl() {
return fileDownloadUrl;
}
@ -126,21 +103,4 @@ public class File implements Parcelable {
this.torrentUrl = torrentUrl;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.fileDownloadUrl);
dest.writeString(this.fileUrl);
dest.writeInt(this.fps);
dest.writeString(this.magnetUri);
dest.writeString(this.metadataUrl);
dest.writeParcelable(this.resolutions, flags);
dest.writeLong(this.size);
dest.writeString(this.torrentDownloadUrl);
dest.writeString(this.torrentUrl);
}
}

View File

@ -14,25 +14,14 @@ package app.fedilab.android.peertube.client.entities;
* 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.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class Item implements Parcelable {
public class Item implements Serializable {
public static final Creator<Item> CREATOR = new Creator<Item>() {
@Override
public Item createFromParcel(Parcel source) {
return new Item(source);
}
@Override
public Item[] newArray(int size) {
return new Item[size];
}
};
@SerializedName("id")
private int id;
@SerializedName("label")
@ -41,10 +30,6 @@ public class Item implements Parcelable {
public Item() {
}
protected Item(Parcel in) {
this.id = in.readInt();
this.label = in.readString();
}
public int getId() {
return id;
@ -61,15 +46,4 @@ public class Item implements Parcelable {
public void setLabel(String label) {
this.label = label;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.label);
}
}

View File

@ -14,25 +14,15 @@ package app.fedilab.android.peertube.client.entities;
* 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.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class ItemStr implements Parcelable {
public class ItemStr implements Serializable {
public static final Creator<ItemStr> CREATOR = new Creator<ItemStr>() {
@Override
public ItemStr createFromParcel(Parcel source) {
return new ItemStr(source);
}
@Override
public ItemStr[] newArray(int size) {
return new ItemStr[size];
}
};
@SerializedName("id")
private String id;
@SerializedName("label")
@ -41,12 +31,6 @@ public class ItemStr implements Parcelable {
public ItemStr() {
}
protected ItemStr(Parcel in) {
this.id = in.readString();
this.label = in.readString();
}
public String getId() {
return id;
}
@ -62,15 +46,4 @@ public class ItemStr implements Parcelable {
public void setLabel(String label) {
this.label = label;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.label);
}
}

View File

@ -14,29 +14,16 @@ package app.fedilab.android.peertube.client.entities;
* 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.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@SuppressWarnings("unused")
public class SepiaSearch implements Parcelable {
public class SepiaSearch implements Serializable {
public static final Creator<SepiaSearch> CREATOR = new Creator<SepiaSearch>() {
@Override
public SepiaSearch createFromParcel(Parcel source) {
return new SepiaSearch(source);
}
@Override
public SepiaSearch[] newArray(int size) {
return new SepiaSearch[size];
}
};
@SerializedName("start")
private String start;
@SerializedName("count")
@ -67,25 +54,6 @@ public class SepiaSearch implements Parcelable {
public SepiaSearch() {
}
protected SepiaSearch(Parcel in) {
this.start = in.readString();
this.count = in.readString();
this.search = in.readString();
this.durationMax = in.readInt();
this.durationMin = in.readInt();
long tmpStartDate = in.readLong();
this.startDate = tmpStartDate == -1 ? null : new Date(tmpStartDate);
this.boostLanguages = in.createStringArrayList();
this.categoryOneOf = new ArrayList<>();
in.readList(this.categoryOneOf, Integer.class.getClassLoader());
this.licenceOneOf = new ArrayList<>();
in.readList(this.licenceOneOf, Integer.class.getClassLoader());
this.tagsOneOf = in.createStringArrayList();
this.tagsAllOf = in.createStringArrayList();
this.nsfw = in.readByte() != 0;
this.sort = in.readString();
}
public String getStart() {
return start;
}
@ -190,25 +158,4 @@ public class SepiaSearch implements Parcelable {
this.sort = sort;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.start);
dest.writeString(this.count);
dest.writeString(this.search);
dest.writeInt(this.durationMax);
dest.writeInt(this.durationMin);
dest.writeLong(this.startDate != null ? this.startDate.getTime() : -1);
dest.writeStringList(this.boostLanguages);
dest.writeList(this.categoryOneOf);
dest.writeList(this.licenceOneOf);
dest.writeStringList(this.tagsOneOf);
dest.writeStringList(this.tagsAllOf);
dest.writeByte(this.nsfw ? (byte) 1 : (byte) 0);
dest.writeString(this.sort);
}
}

View File

@ -14,27 +14,15 @@ package app.fedilab.android.peertube.client.entities;
* 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.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class StreamingPlaylists implements Parcelable {
public class StreamingPlaylists implements Serializable {
public static final Creator<StreamingPlaylists> CREATOR = new Creator<StreamingPlaylists>() {
@Override
public StreamingPlaylists createFromParcel(Parcel in) {
return new StreamingPlaylists(in);
}
@Override
public StreamingPlaylists[] newArray(int size) {
return new StreamingPlaylists[size];
}
};
@SerializedName("id")
private String id;
@SerializedName("type")
@ -48,15 +36,6 @@ public class StreamingPlaylists implements Parcelable {
@SerializedName("redundancies")
private List<Redundancies> redundancies;
protected StreamingPlaylists(Parcel in) {
id = in.readString();
type = in.readInt();
playlistUrl = in.readString();
segmentsSha256Url = in.readString();
files = in.createTypedArrayList(File.CREATOR);
redundancies = in.createTypedArrayList(Redundancies.CREATOR);
}
public String getId() {
return id;
}
@ -105,41 +84,11 @@ public class StreamingPlaylists implements Parcelable {
this.redundancies = redundancies;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(id);
parcel.writeInt(type);
parcel.writeString(playlistUrl);
parcel.writeString(segmentsSha256Url);
parcel.writeTypedList(files);
parcel.writeTypedList(redundancies);
}
public static class Redundancies implements Parcelable {
public static final Creator<Redundancies> CREATOR = new Creator<Redundancies>() {
@Override
public Redundancies createFromParcel(Parcel in) {
return new Redundancies(in);
}
@Override
public Redundancies[] newArray(int size) {
return new Redundancies[size];
}
};
public static class Redundancies implements Serializable {
@SerializedName("baseUrl")
private String baseUrl;
protected Redundancies(Parcel in) {
baseUrl = in.readString();
}
public String getBaseUrl() {
return baseUrl;
}
@ -147,15 +96,5 @@ public class StreamingPlaylists implements Parcelable {
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(baseUrl);
}
}
}

View File

@ -19,14 +19,14 @@ import com.google.gson.annotations.SerializedName;
import java.util.Date;
import java.util.List;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.peertube.client.data.AccountData.PeertubeAccount;
import app.fedilab.android.peertube.client.data.ChannelData;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class UserMe {
@SerializedName("account")
private Account account;
private PeertubeAccount account;
@SerializedName("autoPlayNextVideo")
private boolean autoPlayNextVideo;
@SerializedName("autoPlayNextVideoPlaylist")
@ -74,11 +74,11 @@ public class UserMe {
@SerializedName("webTorrentEnabled")
private boolean webTorrentEnabled;
public Account getAccount() {
public PeertubeAccount getAccount() {
return account;
}
public void setAccount(Account account) {
public void setAccount(PeertubeAccount account) {
this.account = account;
}

View File

@ -14,38 +14,20 @@ package app.fedilab.android.peertube.client.entities;
* 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.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Date;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class ViewsPerDay implements Parcelable {
public class ViewsPerDay implements Serializable {
public static final Creator<ViewsPerDay> CREATOR = new Creator<ViewsPerDay>() {
@Override
public ViewsPerDay createFromParcel(Parcel in) {
return new ViewsPerDay(in);
}
@Override
public ViewsPerDay[] newArray(int size) {
return new ViewsPerDay[size];
}
};
@SerializedName("date")
private Date date;
@SerializedName("views")
private int views;
protected ViewsPerDay(Parcel in) {
long tmpDate = in.readLong();
this.date = tmpDate == -1 ? null : new Date(tmpDate);
views = in.readInt();
}
public Date getDate() {
return date;
}
@ -61,15 +43,4 @@ public class ViewsPerDay implements Parcelable {
public void setViews(int views) {
this.views = views;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeLong(this.date != null ? this.date.getTime() : -1);
parcel.writeInt(views);
}
}

View File

@ -1,255 +0,0 @@
package app.fedilab.android.peertube.client.mastodon;
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* 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.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
import app.fedilab.android.peertube.client.data.AccountData;
import app.fedilab.android.peertube.client.entities.Avatar;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class MastodonAccount {
public static AccountData.Account convertToPeertubeAccount(Account initialAccount) {
AccountData.Account account = new AccountData.Account();
Avatar avatar = new Avatar();
avatar.setPath(initialAccount.getAvatar());
account.setAvatar(avatar);
account.setDescription(initialAccount.getDescription());
account.setDisplayName(initialAccount.getDisplayName());
account.setUsername(initialAccount.getUsername());
account.setHost(initialAccount.getHost());
return account;
}
public static class Account implements Parcelable {
public static final Creator<Account> CREATOR = new Creator<Account>() {
@Override
public Account createFromParcel(Parcel source) {
return new Account(source);
}
@Override
public Account[] newArray(int size) {
return new Account[size];
}
};
@SerializedName("avatar")
private String avatar;
@SerializedName("created_at")
private Date createdAt;
@SerializedName("note")
private String description;
@SerializedName("display_name")
private String displayName;
@SerializedName("followers_count")
private int followersCount;
@SerializedName("following_count")
private int followingCount;
@SerializedName("id")
private String id;
@SerializedName("username")
private String username;
@SerializedName("updated_at")
private Date updatedAt;
@SerializedName("url")
private String url;
private String token;
private String client_id;
private String client_secret;
private String refresh_token;
private String software;
private String host;
public Account() {
}
protected Account(Parcel in) {
this.avatar = in.readString();
long tmpCreatedAt = in.readLong();
this.createdAt = tmpCreatedAt == -1 ? null : new Date(tmpCreatedAt);
this.description = in.readString();
this.displayName = in.readString();
this.followersCount = in.readInt();
this.followingCount = in.readInt();
this.id = in.readString();
this.username = in.readString();
long tmpUpdatedAt = in.readLong();
this.updatedAt = tmpUpdatedAt == -1 ? null : new Date(tmpUpdatedAt);
this.url = in.readString();
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public int getFollowersCount() {
return followersCount;
}
public void setFollowersCount(int followersCount) {
this.followersCount = followersCount;
}
public int getFollowingCount() {
return followingCount;
}
public void setFollowingCount(int followingCount) {
this.followingCount = followingCount;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAcct() {
return username + "@" + host;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getClient_id() {
return client_id;
}
public void setClient_id(String client_id) {
this.client_id = client_id;
}
public String getClient_secret() {
return client_secret;
}
public void setClient_secret(String client_secret) {
this.client_secret = client_secret;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getSoftware() {
return software;
}
public void setSoftware(String software) {
this.software = software;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.avatar);
dest.writeLong(this.createdAt != null ? this.createdAt.getTime() : -1);
dest.writeString(this.description);
dest.writeString(this.displayName);
dest.writeInt(this.followersCount);
dest.writeInt(this.followingCount);
dest.writeString(this.id);
dest.writeString(this.username);
dest.writeLong(this.updatedAt != null ? this.updatedAt.getTime() : -1);
dest.writeString(this.url);
}
}
}

View File

@ -1,104 +0,0 @@
package app.fedilab.android.peertube.client.mastodon;
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */
import app.fedilab.android.peertube.client.entities.Oauth;
import app.fedilab.android.peertube.client.entities.Token;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
interface MastodonService {
@FormUrlEncoded
@POST("apps")
Call<Oauth> getOauth(
@Field("client_name") String client_name,
@Field("redirect_uris") String redirect_uris,
@Field("scopes") String scopes,
@Field("website") String website);
@FormUrlEncoded
@POST("oauth/token")
Call<Token> createToken(
@Field("grant_type") String grant_type,
@Field("client_id") String client_id,
@Field("client_secret") String client_secret,
@Field("redirect_uri") String redirect_uri,
@Field("code") String code);
@GET("accounts/verify_credentials")
Call<MastodonAccount.Account> verifyCredentials(@Header("Authorization") String credentials);
@GET("search?type=statuses&resolve=true")
Call<Results> searchMessage(
@Header("Authorization") String credentials,
@Query("q") String messageURL
);
@FormUrlEncoded
@POST("statuses")
Call<Status> postReply(
@Header("Authorization") String credentials,
@Field("in_reply_to_id") String inReplyToId,
@Field("status") String content,
@Field("visibility") String visibility
);
@POST("statuses/{id}/reblog")
Call<Status> boost(
@Header("Authorization") String credentials,
@Path("id") String id
);
@POST("statuses/{id}/unreblog")
Call<Status> unBoost(
@Header("Authorization") String credentials,
@Path("id") String id
);
@POST("statuses/{id}/favourite")
Call<Status> favourite(
@Header("Authorization") String credentials,
@Path("id") String id
);
@POST("statuses/{id}/unfavourite")
Call<Status> unfavourite(
@Header("Authorization") String credentials,
@Path("id") String id
);
@POST("statuses/{id}/bookmark")
Call<Status> bookmark(
@Header("Authorization") String credentials,
@Path("id") String id
);
@POST("statuses/{id}/unbookmark")
Call<Status> unbookmark(
@Header("Authorization") String credentials,
@Path("id") String id
);
}

View File

@ -1,44 +0,0 @@
package app.fedilab.android.peertube.client.mastodon;
/* Copyright 2021 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Results {
@SerializedName("accounts")
private List<MastodonAccount.Account> accounts;
@SerializedName("statuses")
private List<Status> statuses;
public List<MastodonAccount.Account> getAccounts() {
return accounts;
}
public void setAccounts(List<MastodonAccount.Account> accounts) {
this.accounts = accounts;
}
public List<Status> getStatuses() {
return statuses;
}
public void setStatuses(List<Status> statuses) {
this.statuses = statuses;
}
}

View File

@ -1,357 +0,0 @@
package app.fedilab.android.peertube.client.mastodon;
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* 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.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Looper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;
import app.fedilab.android.R;
import app.fedilab.android.peertube.activities.PeertubeMainActivity;
import app.fedilab.android.peertube.client.APIResponse;
import app.fedilab.android.peertube.client.entities.Error;
import app.fedilab.android.peertube.client.entities.Oauth;
import app.fedilab.android.peertube.client.entities.OauthParams;
import app.fedilab.android.peertube.client.entities.Token;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.sqlite.MastodonAccountDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitMastodonAPI {
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
private final String finalUrl;
private final String finalUrl2;
private final Context _context;
private String instance;
private String token;
public RetrofitMastodonAPI(Context context) {
_context = context;
SharedPreferences sharedpreferences = _context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
this.instance = sharedpreferences.getString(Helper.PREF_REMOTE_INSTANCE, null);
this.token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
finalUrl = "https://" + this.instance + "/api/v1/";
finalUrl2 = "https://" + this.instance + "/api/v2/";
}
public RetrofitMastodonAPI(Context context, String instance, String token) {
_context = context;
this.instance = instance;
this.token = token;
finalUrl = "https://" + instance + "/api/v1/";
finalUrl2 = "https://" + this.instance + "/api/v2/";
}
public Status search(String url) throws Error {
MastodonService mastodonService2 = init2();
Call<Results> statusCall = mastodonService2.searchMessage(getToken(), url);
Response<Results> response;
try {
response = statusCall.execute();
if (response.isSuccessful() && response.body() != null && response.body().getStatuses() != null && response.body().getStatuses().size() > 0) {
return response.body().getStatuses().get(0);
} else {
Error error = new Error();
error.setStatusCode(response.code());
if (response.errorBody() != null) {
error.setError(response.errorBody().string());
} else {
error.setError(_context.getString(R.string.toast_error));
}
throw error;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void updateCredential(Activity activity, String client_id, String client_secret, String refresh_token, String software) {
new Thread(() -> {
MastodonAccount.Account account;
try {
account = new RetrofitMastodonAPI(activity, instance, token).verifyCredentials();
} catch (Error error) {
Error.displayError(activity, error);
error.printStackTrace();
return;
}
try {
//At the state the instance can be encoded
instance = URLDecoder.decode(instance, "utf-8");
} catch (UnsupportedEncodingException ignored) {
}
SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
account.setToken(token);
account.setClient_id(client_id);
account.setClient_secret(client_secret);
account.setRefresh_token(refresh_token);
account.setHost(instance);
account.setSoftware(software);
SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
boolean userExists = new MastodonAccountDAO(activity, db).userExist(account);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_ID, account.getId());
editor.putString(Helper.PREF_KEY_NAME, account.getUsername());
if (token != null) {
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token);
}
editor.putString(Helper.PREF_REMOTE_INSTANCE, account.getHost());
editor.putString(Helper.PREF_SOFTWARE, software);
editor.apply();
if (userExists) {
new MastodonAccountDAO(activity, db).updateAccountCredential(account);
} else {
if (account.getUsername() != null && account.getCreatedAt() != null) {
new MastodonAccountDAO(activity, db).insertAccount(account);
}
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
Intent mainActivity = new Intent(activity, PeertubeMainActivity.class);
mainActivity.putExtra(Helper.INTENT_ACTION, Helper.ADD_USER_INTENT);
activity.startActivity(mainActivity);
activity.finish();
};
mainHandler.post(myRunnable);
}).start();
}
private MastodonService init_no_api() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://" + instance)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
SharedPreferences sharedpreferences = _context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
if (token == null) {
token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
}
return retrofit.create(MastodonService.class);
}
private MastodonService init() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(finalUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
SharedPreferences sharedpreferences = _context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
if (token == null) {
token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
}
return retrofit.create(MastodonService.class);
}
private MastodonService init2() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(finalUrl2)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
SharedPreferences sharedpreferences = _context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
if (token == null) {
token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
}
return retrofit.create(MastodonService.class);
}
/**
* Get Oauth
*
* @return APIResponse
*/
public Oauth oauthClient(String client_name, String redirect_uris, String scopes, String website) {
MastodonService mastodonService = init();
try {
Call<Oauth> oauth;
oauth = mastodonService.getOauth(client_name, redirect_uris, scopes, website);
Response<Oauth> response = oauth.execute();
if (response.isSuccessful() && response.body() != null) {
return response.body();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/***
* Verifiy credential of the authenticated user *synchronously*
* @return Account
*/
public MastodonAccount.Account verifyCredentials() throws Error {
MastodonService mastodonService = init();
Call<MastodonAccount.Account> accountCall = mastodonService.verifyCredentials("Bearer " + token);
APIResponse apiResponse = new APIResponse();
try {
Response<MastodonAccount.Account> response = accountCall.execute();
if (response.isSuccessful() && response.body() != null) {
return response.body();
} else {
Error error = new Error();
error.setStatusCode(response.code());
if (response.errorBody() != null) {
error.setError(response.errorBody().string());
} else {
error.setError(_context.getString(R.string.toast_error));
}
throw error;
}
} catch (IOException e) {
Error error = new Error();
error.setError(_context.getString(R.string.toast_error));
apiResponse.setError(error);
e.printStackTrace();
}
return null;
}
/***
* Verifiy credential of the authenticated user *synchronously*
* @return Account
*/
public Token manageToken(OauthParams oauthParams) throws Error {
MastodonService mastodonService = init_no_api();
Call<Token> createToken = mastodonService.createToken(
oauthParams.getGrant_type(),
oauthParams.getClient_id(),
oauthParams.getClient_secret(),
oauthParams.getRedirect_uri(),
oauthParams.getCode()
);
if (createToken != null) {
try {
Response<Token> response = createToken.execute();
if (response.isSuccessful()) {
return response.body();
} else {
Error error = new Error();
error.setStatusCode(response.code());
if (response.errorBody() != null) {
error.setError(response.errorBody().string());
} else {
error.setError(_context.getString(R.string.toast_error));
}
throw error;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public Status commentAction(String url, String content) throws Error {
MastodonService mastodonService = init();
Status status = search(url);
if (status != null) {
Call<Status> postReplyCall = mastodonService.postReply(getToken(), status.getId(), content, null);
try {
Response<Status> responsePost = postReplyCall.execute();
if (responsePost.isSuccessful()) {
Status statusReturned = responsePost.body();
if (statusReturned != null && statusReturned.getAccount() != null) {
statusReturned.getAccount().setHost(instance);
}
return statusReturned;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public Status postAction(actionType type, Status status) {
MastodonService mastodonService = init();
Call<Status> postAction = null;
if (status != null) {
switch (type) {
case BOOST:
postAction = mastodonService.boost(getToken(), status.getId());
break;
case UNBOOST:
postAction = mastodonService.unBoost(getToken(), status.getId());
break;
case FAVOURITE:
postAction = mastodonService.favourite(getToken(), status.getId());
break;
case UNFAVOURITE:
postAction = mastodonService.unfavourite(getToken(), status.getId());
break;
case BOOKMARK:
postAction = mastodonService.bookmark(getToken(), status.getId());
break;
case UNBOOKMARK:
postAction = mastodonService.unbookmark(getToken(), status.getId());
break;
}
try {
if (postAction != null) {
Response<Status> responsePost = postAction.execute();
if (responsePost.isSuccessful()) {
Status statusReturned = responsePost.body();
if (statusReturned != null && statusReturned.getAccount() != null) {
statusReturned.getAccount().setHost(instance);
}
return statusReturned;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
private String getToken() {
if (token != null) {
return "Bearer " + token;
} else {
return null;
}
}
public enum actionType {
BOOST,
UNBOOST,
FAVOURITE,
UNFAVOURITE,
BOOKMARK,
UNBOOKMARK
}
}

View File

@ -1,149 +0,0 @@
package app.fedilab.android.peertube.client.mastodon;
/* Copyright 2021 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with TubeLab; if not,
* see <http://www.gnu.org/licenses>. */
import com.google.gson.annotations.SerializedName;
import java.util.Date;
import app.fedilab.android.peertube.client.data.CommentData;
@SuppressWarnings("unused")
public class Status {
@SerializedName("id")
private String id;
@SerializedName("in_reply_to_id")
private String inReplyToCommentId;
@SerializedName("account")
private MastodonAccount.Account account;
@SerializedName("url")
private String url;
@SerializedName("content")
private String text;
@SerializedName("created_at")
private Date createdAt;
@SerializedName("reblogs_count")
private int reblogsCount;
@SerializedName("favourites_count")
private int favouritesCount;
@SerializedName("favourited")
private boolean favourited;
@SerializedName("reblogged")
private boolean reblogged;
@SerializedName("bookmarked")
private boolean bookmarked;
public static CommentData.Comment convertStatusToComment(Status status) {
CommentData.Comment comment = new CommentData.Comment();
comment.setAccount(MastodonAccount.convertToPeertubeAccount(status.getAccount()));
comment.setCreatedAt(status.getCreatedAt());
comment.setText(status.getText());
return comment;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getInReplyToCommentId() {
return inReplyToCommentId;
}
public void setInReplyToCommentId(String inReplyToCommentId) {
this.inReplyToCommentId = inReplyToCommentId;
}
public MastodonAccount.Account getAccount() {
return account;
}
public void setAccount(MastodonAccount.Account account) {
this.account = account;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public int getReblogsCount() {
return reblogsCount;
}
public void setReblogsCount(int reblogsCount) {
this.reblogsCount = reblogsCount;
}
public int getFavouriteCount() {
return favouritesCount;
}
public boolean isFavourited() {
return favourited;
}
public void setFavourited(boolean favourited) {
this.favourited = favourited;
}
public boolean isReblogged() {
return reblogged;
}
public void setReblogged(boolean reblogged) {
this.reblogged = reblogged;
}
public int getFavouritesCount() {
return favouritesCount;
}
public void setFavouritesCount(int favouritesCount) {
this.favouritesCount = favouritesCount;
}
public boolean isBookmarked() {
return bookmarked;
}
public void setBookmarked(boolean bookmarked) {
this.bookmarked = bookmarked;
}
}

View File

@ -44,7 +44,6 @@ import app.fedilab.android.R;
import app.fedilab.android.databinding.DrawerAboutInstancePeertubeBinding;
import app.fedilab.android.peertube.client.data.InstanceData;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.sqlite.Sqlite;
import app.fedilab.android.peertube.sqlite.StoredInstanceDAO;

View File

@ -39,7 +39,7 @@ import app.fedilab.android.R;
import app.fedilab.android.peertube.activities.ShowAccountActivity;
import app.fedilab.android.peertube.client.APIResponse;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.peertube.client.data.AccountData;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.viewmodel.PostActionsVM;
import es.dmoral.toasty.Toasty;
@ -47,13 +47,13 @@ import es.dmoral.toasty.Toasty;
public class AccountsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final List<Account> accounts;
private final List<AccountData.PeertubeAccount> accounts;
private final AccountsListAdapter accountsListAdapter;
private final RetrofitPeertubeAPI.DataType type;
public AllAccountsRemoved allAccountsRemoved;
private Context context;
public AccountsListAdapter(RetrofitPeertubeAPI.DataType type, List<Account> accounts) {
public AccountsListAdapter(RetrofitPeertubeAPI.DataType type, List<AccountData.PeertubeAccount> accounts) {
this.accounts = accounts;
this.accountsListAdapter = this;
this.type = type;
@ -70,7 +70,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
final ViewHolder holder = (ViewHolder) viewHolder;
final Account account = accounts.get(position);
final AccountData.PeertubeAccount account = accounts.get(position);
if (type == RetrofitPeertubeAPI.DataType.MUTED) {
holder.account_action.setOnClickListener(v -> {
PostActionsVM viewModel = new ViewModelProvider((ViewModelStoreOwner) context).get(PostActionsVM.class);
@ -96,7 +96,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
holder.account_pp.setOnClickListener(v -> {
Intent intent = new Intent(context, ShowAccountActivity.class);
Bundle b = new Bundle();
b.putParcelable("account", account);
b.putSerializable("account", account);
b.putString("accountAcct", account.getAcct());
intent.putExtras(b);
context.startActivity(intent);
@ -122,7 +122,7 @@ public class AccountsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
}
if (statusAction == RetrofitPeertubeAPI.ActionType.UNMUTE) {
int position = 0;
for (Account account : accounts) {
for (AccountData.PeertubeAccount account : accounts) {
if (account.getAcct().equals(elementTargeted)) {
accounts.remove(position);
accountsListAdapter.notifyItemRemoved(position);

View File

@ -123,7 +123,7 @@ public class ChannelListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
holder.account_pp.setOnClickListener(v -> {
Intent intent = new Intent(context, ShowChannelActivity.class);
Bundle b = new Bundle();
b.putParcelable("channel", channel);
b.putSerializable("channel", channel);
intent.putExtras(b);
context.startActivity(intent);
});

View File

@ -279,7 +279,7 @@ public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
holder.binding.commentAccountProfile.setOnClickListener(v -> {
Bundle b = new Bundle();
Intent intent = new Intent(context, ShowAccountActivity.class);
b.putParcelable("account", comment.getAccount());
b.putSerializable("account", comment.getAccount());
b.putString("accountAcct", comment.getAccount().getAcct());
intent.putExtras(b);
context.startActivity(intent);

View File

@ -28,16 +28,16 @@ import androidx.annotation.NonNull;
import java.util.List;
import app.fedilab.android.R;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.mastodon.client.entities.app.BaseAccount;
import app.fedilab.android.peertube.helper.Helper;
public class OwnAccountsAdapter extends ArrayAdapter<Account> {
public class OwnAccountsAdapter extends ArrayAdapter<BaseAccount> {
private final List<Account> accounts;
private final List<BaseAccount> accounts;
private final LayoutInflater layoutInflater;
public OwnAccountsAdapter(Context context, List<Account> accounts) {
public OwnAccountsAdapter(Context context, List<BaseAccount> accounts) {
super(context, android.R.layout.simple_list_item_1, accounts);
this.accounts = accounts;
layoutInflater = LayoutInflater.from(context);
@ -50,7 +50,7 @@ public class OwnAccountsAdapter extends ArrayAdapter<Account> {
}
@Override
public Account getItem(int position) {
public BaseAccount getItem(int position) {
return accounts.get(position);
}
@ -63,7 +63,7 @@ public class OwnAccountsAdapter extends ArrayAdapter<Account> {
@Override
public View getView(final int position, View convertView, @NonNull ViewGroup parent) {
final Account account = accounts.get(position);
final BaseAccount account = accounts.get(position);
final ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.drawer_account_owner, parent, false);
@ -76,7 +76,7 @@ public class OwnAccountsAdapter extends ArrayAdapter<Account> {
} else {
holder = (ViewHolder) convertView.getTag();
}
ac
holder.account_un.setText(String.format("@%s", account.getAcct()));
//Profile picture
Helper.loadAvatar(holder.account_pp.getContext(), account, holder.account_pp);

View File

@ -85,9 +85,9 @@ public class PeertubeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
private TimelineVM.TimelineType timelineType;
private boolean sepiaSearch;
private ChannelData.Channel forChannel;
private AccountData.Account forAccount;
private AccountData.PeertubeAccount forAccount;
public PeertubeAdapter(List<VideoData.Video> videos, TimelineVM.TimelineType timelineType, boolean sepiaSearch, ChannelData.Channel forChannel, AccountData.Account forAccount) {
public PeertubeAdapter(List<VideoData.Video> videos, TimelineVM.TimelineType timelineType, boolean sepiaSearch, ChannelData.Channel forChannel, AccountData.PeertubeAccount forAccount) {
this.videos = videos;
this.timelineType = timelineType;
this.sepiaSearch = sepiaSearch || timelineType == SEPIA_SEARCH;
@ -189,7 +189,7 @@ public class PeertubeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
holder.binding.peertubeProfile.setOnClickListener(v -> {
Intent intent = new Intent(context, ShowChannelActivity.class);
Bundle b = new Bundle();
b.putParcelable("channel", video.getChannel());
b.putSerializable("channel", video.getChannel());
b.putBoolean("sepia_search", sepiaSearch || forChannel != null);
if (sepiaSearch || forChannel != null) {
b.putString("peertube_instance", video.getAccount().getHost());
@ -293,7 +293,7 @@ public class PeertubeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
b.putString("video_uuid", video.getUuid());
b.putBoolean("isMyVideo", ownVideos);
b.putBoolean("sepia_search", sepiaSearch);
b.putParcelable("video", video);
b.putSerializable("video", video);
if (sepiaSearch) {
b.putString("peertube_instance", video.getAccount().getHost());
}
@ -304,7 +304,7 @@ public class PeertubeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
Intent intent = new Intent(context, PeertubeActivity.class);
Bundle b = new Bundle();
b.putString("video_id", video.getId());
b.putParcelable("video", video);
b.putSerializable("video", video);
b.putString("video_uuid", video.getUuid());
b.putBoolean("isMyVideo", ownVideos);
b.putBoolean("sepia_search", sepiaSearch);

View File

@ -74,7 +74,7 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter<Recyc
//Follow Notification
boolean clickableNotification = true;
holder.peertube_notif_pp.setVisibility(View.VISIBLE);
AccountData.Account accountAction = null;
AccountData.PeertubeAccount accountAction = null;
ChannelData.Channel channelAction = null;
if (notification.isRead()) {
holder.unread.setVisibility(View.INVISIBLE);
@ -97,7 +97,7 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter<Recyc
else
holder.peertube_notif_message.setText(Html.fromHtml(message));
Actor actor = notification.getActorFollow().getFollower();
accountAction = new AccountData.Account();
accountAction = new AccountData.PeertubeAccount();
accountAction.setAvatar(actor.getAvatar());
accountAction.setDisplayName(actor.getDisplayName());
accountAction.setHost(actor.getHost());
@ -112,11 +112,11 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter<Recyc
holder.peertube_notif_message.setText(Html.fromHtml(message, Html.FROM_HTML_MODE_LEGACY));
else
holder.peertube_notif_message.setText(Html.fromHtml(message));
AccountData.Account finalAccountAction1 = accountAction;
AccountData.PeertubeAccount finalAccountAction1 = accountAction;
holder.peertube_notif_message.setOnClickListener(v -> {
Intent intent = new Intent(context, PeertubeActivity.class);
Bundle b = new Bundle();
b.putParcelable("video", notification.getVideo());
b.putSerializable("video", notification.getVideo());
b.putString("peertube_instance", finalAccountAction1.getHost());
b.putString("video_id", notification.getComment().getVideo().getId());
b.putString("video_uuid", notification.getComment().getVideo().getUuid());
@ -158,7 +158,7 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter<Recyc
holder.peertube_notif_message.setOnClickListener(v -> {
Intent intent = new Intent(context, PeertubeActivity.class);
Bundle b = new Bundle();
b.putParcelable("video", notification.getVideo());
b.putSerializable("video", notification.getVideo());
b.putString("peertube_instance", HelperInstance.getLiveInstance(context));
b.putBoolean("isMyVideo", finalMyVideo);
b.putString("video_id", notification.getVideo().getId());
@ -188,7 +188,7 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter<Recyc
}
}
holder.peertube_notif_date.setText(Helper.dateDiff(context, notification.getCreatedAt()));
AccountData.Account finalAccountAction = accountAction;
AccountData.PeertubeAccount finalAccountAction = accountAction;
ChannelData.Channel finalChannelAction = channelAction;
if (clickableNotification) {
holder.peertube_notif_pp.setOnClickListener(v -> {
@ -196,11 +196,11 @@ public class PeertubeNotificationsListAdapter extends RecyclerView.Adapter<Recyc
Intent intent = null;
if (finalAccountAction != null) {
intent = new Intent(context, ShowAccountActivity.class);
b.putParcelable("account", finalAccountAction);
b.putSerializable("account", finalAccountAction);
b.putString("accountAcct", finalAccountAction.getUsername() + "@" + finalAccountAction.getHost());
} else if (finalChannelAction != null) {
intent = new Intent(context, ShowChannelActivity.class);
b.putParcelable("channel", finalChannelAction);
b.putSerializable("channel", finalChannelAction);
}
if (intent != null) {
intent.putExtras(b);

View File

@ -38,8 +38,6 @@ import app.fedilab.android.peertube.activities.AllPlaylistsActivity;
import app.fedilab.android.peertube.client.APIResponse;
import app.fedilab.android.peertube.client.data.PlaylistData.Playlist;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.sqlite.ManagePlaylistsDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
import app.fedilab.android.peertube.viewmodel.PlaylistsVM;

View File

@ -37,7 +37,6 @@ import java.util.List;
import app.fedilab.android.R;
import app.fedilab.android.peertube.client.APIResponse;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.peertube.client.data.BlockData;
import app.fedilab.android.peertube.drawer.AccountsListAdapter;
import app.fedilab.android.peertube.viewmodel.AccountsVM;

View File

@ -58,7 +58,7 @@ import app.fedilab.android.R;
import app.fedilab.android.peertube.activities.PlaylistsActivity;
import app.fedilab.android.peertube.client.APIResponse;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.peertube.client.data.AccountData;
import app.fedilab.android.peertube.client.data.PlaylistData.Playlist;
import app.fedilab.android.peertube.client.entities.Item;
import app.fedilab.android.peertube.client.entities.PlaylistParams;
@ -242,7 +242,7 @@ public class DisplayPlaylistsFragment extends Fragment {
if (apiResponse.getPlaylists() != null && apiResponse.getPlaylists().size() > 0) {
Intent intent = new Intent(context, PlaylistsActivity.class);
Bundle b = new Bundle();
b.putParcelable("playlist", apiResponse.getPlaylists().get(0));
b.putSerializable("playlist", apiResponse.getPlaylists().get(0));
intent.putExtras(b);
context.startActivity(intent);
this.playlists.add(0, apiResponse.getPlaylists().get(0));
@ -268,14 +268,14 @@ public class DisplayPlaylistsFragment extends Fragment {
}
//Populate channels
List<Account> accounts = apiResponse.getAccounts();
List<AccountData.PeertubeAccount> accounts = apiResponse.getAccounts();
String[] channelName = new String[accounts.size() + 1];
String[] channelId = new String[accounts.size() + 1];
int i = 1;
channelName[0] = "";
channelId[0] = "";
channels = new HashMap<>();
for (Account account : accounts) {
for (AccountData.PeertubeAccount account : accounts) {
channels.put(account.getUsername(), account.getId());
channelName[i] = account.getUsername();
channelId[i] = account.getId();

View File

@ -86,7 +86,7 @@ public class DisplayVideosFragment extends Fragment implements AccountsHorizonta
private SearchVM viewModelSearch;
private AccountsVM viewModelAccounts;
private ChannelData.Channel channel;
private AccountData.Account account;
private AccountData.PeertubeAccount account;
private Map<String, Boolean> relationship;
private Map<String, List<PlaylistExist>> playlists;
private String playlistId;
@ -118,8 +118,8 @@ public class DisplayVideosFragment extends Fragment implements AccountsHorizonta
Bundle bundle = this.getArguments();
if (bundle != null) {
search_peertube = bundle.getString("search_peertube", null);
channel = bundle.getParcelable("channel");
account = bundle.getParcelable("account");
channel = (ChannelData.Channel) bundle.getSerializable("channel");
account = (AccountData.PeertubeAccount) bundle.getSerializable("account");
remoteInstance = bundle.getString("peertube_instance", null);
sepiaSearch = bundle.getBoolean("sepia_search", false);
type = (TimelineVM.TimelineType) bundle.get(Helper.TIMELINE_TYPE);
@ -498,8 +498,6 @@ public class DisplayVideosFragment extends Fragment implements AccountsHorizonta
viewModelFeeds.getVideosInChannel(sepiaSearch ? remoteInstance : null, channelId, max_id).observe(this.requireActivity(), this::manageVIewVideos);
} else if (type == TimelineVM.TimelineType.VIDEOS_IN_PLAYLIST) {
viewModelFeeds.loadVideosInPlaylist(playlistId, max_id).observe(this.requireActivity(), this::manageVIewVideos);
} else if (type == VIDEOS_IN_LOCAL_PLAYLIST) {
viewModelFeeds.loadVideosInLocalPlaylist(playlistId).observe(this.requireActivity(), this::manageVIewVideos);
} else if (type == TimelineVM.TimelineType.HISTORY) {
viewModelFeeds.getVideoHistory(max_id, startDate, endDate).observe(this.requireActivity(), this::manageVIewVideos);
} else {

View File

@ -39,7 +39,6 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import app.fedilab.android.BuildConfig;
import app.fedilab.android.R;
import app.fedilab.android.peertube.activities.MyAccountActivity;
import app.fedilab.android.peertube.activities.PeertubeMainActivity;
@ -329,19 +328,18 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
//****** App theme *******
ListPreference set_theme_choice = findPreference(getString(R.string.set_theme_choice));
List<String> arrayTheme = Arrays.asList(getResources().getStringArray(R.array.settings_theme));
CharSequence[] entriesTheme = arrayTheme.toArray(new CharSequence[0]);
CharSequence[] entryValuesTheme = new CharSequence[3];
final SharedPreferences sharedpref = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int currentTheme = sharedpref.getInt(Helper.SET_THEME, BuildConfig.default_theme);
entryValuesTheme[0] = String.valueOf(Helper.LIGHT_MODE);
entryValuesTheme[1] = String.valueOf(Helper.DARK_MODE);
entryValuesTheme[2] = String.valueOf(Helper.DEFAULT_MODE);
if (set_theme_choice != null) {
set_theme_choice.setEntries(entriesTheme);
set_theme_choice.setEntryValues(entryValuesTheme);
set_theme_choice.setValueIndex(currentTheme);
ListPreference SET_THEME_BASE = findPreference(getString(R.string.SET_THEME_BASE));
if (SET_THEME_BASE != null) {
SET_THEME_BASE.getContext().setTheme(app.fedilab.android.mastodon.helper.Helper.dialogStyle());
}
ListPreference SET_THEME_DEFAULT_LIGHT = findPreference(getString(R.string.SET_THEME_DEFAULT_LIGHT));
if (SET_THEME_DEFAULT_LIGHT != null) {
SET_THEME_DEFAULT_LIGHT.getContext().setTheme(app.fedilab.android.mastodon.helper.Helper.dialogStyle());
}
ListPreference SET_THEME_DEFAULT_DARK = findPreference(getString(R.string.SET_THEME_DEFAULT_DARK));
if (SET_THEME_DEFAULT_DARK != null) {
SET_THEME_DEFAULT_DARK.getContext().setTheme(app.fedilab.android.mastodon.helper.Helper.dialogStyle());
}
@ -427,7 +425,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
set_video_in_list_choice.setChecked(videosInList);
//****** Allow Chromecast *******
int cast = sharedpref.getInt(getString(R.string.set_cast_choice), BuildConfig.cast_enabled);
int cast = sharedpref.getInt(getString(R.string.set_cast_choice), 0);
SwitchPreference set_cast_choice = findPreference(getString(R.string.set_cast_choice));
assert set_cast_choice != null;
set_cast_choice.setChecked(cast == 1);

View File

@ -27,7 +27,6 @@ import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
@ -56,6 +55,7 @@ import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import java.io.IOException;
import java.io.InputStream;
@ -71,15 +71,15 @@ import java.util.Locale;
import java.util.regex.Pattern;
import app.fedilab.android.R;
import app.fedilab.android.mastodon.client.entities.app.BaseAccount;
import app.fedilab.android.mastodon.exception.DBException;
import app.fedilab.android.peertube.activities.PeertubeMainActivity;
import app.fedilab.android.peertube.activities.WebviewActivity;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.peertube.client.data.AccountData;
import app.fedilab.android.peertube.client.data.ChannelData;
import app.fedilab.android.peertube.client.data.VideoData;
import app.fedilab.android.peertube.client.entities.File;
import app.fedilab.android.peertube.client.entities.PeertubeInformation;
import app.fedilab.android.peertube.sqlite.AccountDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
import app.fedilab.android.peertube.webview.CustomWebview;
import app.fedilab.android.peertube.webview.ProxyHelper;
import es.dmoral.toasty.Toasty;
@ -123,8 +123,6 @@ public class Helper {
public static final String OAUTH_SCOPES_MASTODON = "read write follow";
public static final String REDIRECT_CONTENT = "urn:ietf:wg:oauth:2.0:oob";
public static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
public static final String PREF_SOFTWARE = "pref_software";
public static final String PREF_REMOTE_INSTANCE = "pref_remote_instance";
public static final Pattern redirectPattern = Pattern.compile("externalAuthToken=(\\w+)&username=([\\w.-]+)");
public static final String SET_VIDEO_CACHE = "set_video_cache";
public static final String RECEIVE_CAST_SETTINGS = "receive_cast_settings";
@ -293,7 +291,7 @@ public class Helper {
}
public static void loadAvatar(final Context context, Account account, final ImageView imageView) {
public static void loadAvatar(final Context context, AccountData.PeertubeAccount account, final ImageView imageView) {
String url = null;
if (account.getAvatar() != null) {
url = account.getAvatar().getPath();
@ -532,39 +530,30 @@ public class Helper {
/**
* Log out the authenticated user by removing its token
*
* @param activity Activity
* @param account Account
* @param activity Activity
* @param currentAccount BaseAccount
*/
public static void logoutCurrentUser(Activity activity, Account account) {
SharedPreferences sharedpreferences = activity.getSharedPreferences(APP_PREFS, MODE_PRIVATE);
//Current user
SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if (account != null) {
new AccountDAO(activity, db).removeUser(account);
}
Account newAccount = new AccountDAO(activity, db).getLastUsedAccount();
SharedPreferences.Editor editor = sharedpreferences.edit();
if (newAccount == null) {
editor.putString(PREF_KEY_OAUTH_TOKEN, null);
editor.putString(CLIENT_ID, null);
editor.putString(CLIENT_SECRET, null);
editor.putString(PREF_KEY_ID, null);
editor.putString(PREF_INSTANCE, null);
editor.putString(ID, null);
editor.apply();
Intent loginActivity = new Intent(activity, PeertubeMainActivity.class);
activity.startActivity(loginActivity);
activity.finish();
public static void logoutCurrentUser(Activity activity, BaseAccount currentAccount) {
AlertDialog.Builder alt_bld = new MaterialAlertDialogBuilder(activity, app.fedilab.android.mastodon.helper.Helper.dialogStyle());
alt_bld.setTitle(R.string.action_logout);
if (currentAccount.mastodon_account != null && currentAccount.mastodon_account.username != null && currentAccount.instance != null) {
alt_bld.setMessage(activity.getString(R.string.logout_account_confirmation, currentAccount.mastodon_account.username, currentAccount.instance));
} else if (currentAccount.mastodon_account != null && currentAccount.mastodon_account.acct != null) {
alt_bld.setMessage(activity.getString(R.string.logout_account_confirmation, currentAccount.mastodon_account.acct, ""));
} else {
editor.putString(PREF_KEY_OAUTH_TOKEN, newAccount.getToken());
editor.putString(PREF_KEY_ID, newAccount.getId());
editor.putString(PREF_INSTANCE, newAccount.getHost().trim());
editor.commit();
Intent changeAccount = new Intent(activity, PeertubeMainActivity.class);
changeAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(changeAccount);
alt_bld.setMessage(activity.getString(R.string.logout_account_confirmation, "", ""));
}
alt_bld.setPositiveButton(R.string.action_logout, (dialog, id) -> {
dialog.dismiss();
try {
app.fedilab.android.mastodon.helper.Helper.removeAccount(activity);
} catch (DBException e) {
e.printStackTrace();
}
});
alt_bld.setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss());
AlertDialog alert = alt_bld.create();
alert.show();
}
@ -669,7 +658,7 @@ public class Helper {
}
public static boolean isOwner(Context context, Account account) {
public static boolean isOwner(Context context, AccountData.PeertubeAccount account) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
String userName = sharedpreferences.getString(Helper.PREF_KEY_NAME, "");
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, "");
@ -687,7 +676,7 @@ public class Helper {
if (video == null) {
return false;
}
Account account = video.getAccount();
AccountData.PeertubeAccount account = video.getAccount();
ChannelData.Channel channel = video.getChannel();
if (account != null && instance != null && userName != null) {
return account.getUsername().compareTo(userName) == 0 && account.getHost().compareTo(instance) == 0;

View File

@ -47,7 +47,7 @@ public class NotificationHelper {
* @param message String message for the notification
*/
@SuppressLint("UnspecifiedImmutableFlag")
public static void notify_user(Context context, AccountData.Account account, Intent intent, Bitmap icon, String title, String message) {
public static void notify_user(Context context, AccountData.PeertubeAccount account, Intent intent, Bitmap icon, String title, String message) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
int notificationId = (int) System.currentTimeMillis();
PendingIntent pIntent;
@ -85,7 +85,7 @@ public class NotificationHelper {
.setContentIntent(pIntent)
.setLargeIcon(icon)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_notification_tubelab)
.setSmallIcon(R.drawable.ic_notification)
.setGroup(account.getAcct())
.setGroupSummary(true)
.build();

View File

@ -1,117 +0,0 @@
package app.fedilab.android.peertube.helper;
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* 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.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.OpenableColumns;
import com.google.gson.Gson;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
import app.fedilab.android.peertube.activities.AllLocalPlaylistsActivity;
import app.fedilab.android.peertube.client.data.VideoPlaylistData;
import app.fedilab.android.peertube.sqlite.ManagePlaylistsDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
public class PlaylistExportHelper {
/**
* Unserialized VideoPlaylistExport
*
* @param serializedVideoPlaylistExport String serialized VideoPlaylistExport
* @return VideoPlaylistExport
*/
public static VideoPlaylistData.VideoPlaylistExport restorePlaylistFromString(String serializedVideoPlaylistExport) {
Gson gson = new Gson();
try {
return gson.fromJson(serializedVideoPlaylistExport, VideoPlaylistData.VideoPlaylistExport.class);
} catch (Exception e) {
return null;
}
}
/**
* Serialized VideoPlaylistExport class
*
* @param videoPlaylistExport Playlist to serialize
* @return String serialized VideoPlaylistData.VideoPlaylistExport
*/
public static String playlistToStringStorage(VideoPlaylistData.VideoPlaylistExport videoPlaylistExport) {
Gson gson = new Gson();
try {
return gson.toJson(videoPlaylistExport);
} catch (Exception e) {
return null;
}
}
/**
* Manage intent for opening a tubelab file allowing to import a whole playlist and store it in db
*
* @param activity Activity
* @param intent Intent
*/
public static void manageIntentUrl(Activity activity, Intent intent) {
if (intent.getData() != null) {
String url = intent.getData().toString();
String filename = url;
if (url.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = activity.getContentResolver().query(intent.getData(), null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
filename = cursor.getString(cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
}
} finally {
assert cursor != null;
cursor.close();
}
}
String text = null;
if (filename.endsWith(".tubelab")) {
try {
InputStream inputStream = activity.getContentResolver().openInputStream(intent.getData());
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
text = s.hasNext() ? s.next() : "";
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (text != null && text.length() > 20) {
String finalText = text;
new Thread(() -> {
VideoPlaylistData.VideoPlaylistExport videoPlaylistExport = PlaylistExportHelper.restorePlaylistFromString(finalText);
if (videoPlaylistExport != null) {
SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
new ManagePlaylistsDAO(activity, db).insertPlaylist(videoPlaylistExport);
}
activity.runOnUiThread(() -> {
Intent intentPlaylist = new Intent(activity, AllLocalPlaylistsActivity.class);
activity.startActivity(intentPlaylist);
});
}).start();
}
}
}
}
}

View File

@ -19,53 +19,51 @@ import static android.content.Context.MODE_PRIVATE;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import androidx.appcompat.app.AlertDialog;
import java.util.List;
import app.fedilab.android.BaseMainActivity;
import app.fedilab.android.R;
import app.fedilab.android.mastodon.client.entities.app.Account;
import app.fedilab.android.mastodon.client.entities.app.BaseAccount;
import app.fedilab.android.mastodon.exception.DBException;
import app.fedilab.android.peertube.activities.LoginActivity;
import app.fedilab.android.peertube.activities.PeertubeMainActivity;
import app.fedilab.android.peertube.client.data.AccountData;
import app.fedilab.android.peertube.drawer.OwnAccountsAdapter;
import app.fedilab.android.peertube.sqlite.AccountDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
public class SwitchAccountHelper {
public static void switchDialog(Activity activity, boolean withAddAccount) {
SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<AccountData.Account> accounts = new AccountDAO(activity, db).getAllAccount();
List<BaseAccount> accounts = null;
try {
accounts = new Account(activity).getAll();
} catch (DBException e) {
e.printStackTrace();
}
AlertDialog.Builder builderSingle = new AlertDialog.Builder(activity);
builderSingle.setTitle(activity.getString(R.string.list_of_accounts));
if (accounts != null) {
final OwnAccountsAdapter accountsListAdapter = new OwnAccountsAdapter(activity, accounts);
final AccountData.Account[] accountArray = new AccountData.Account[accounts.size()];
final BaseAccount[] accountArray = new BaseAccount[accounts.size()];
int i = 0;
for (AccountData.Account account : accounts) {
for (BaseAccount account : accounts) {
accountArray[i] = account;
i++;
}
builderSingle.setAdapter(accountsListAdapter, (dialog, which) -> {
final AccountData.Account account = accountArray[which];
final BaseAccount account = accountArray[which];
SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
boolean remote_account = account.getSoftware() != null && account.getSoftware().toUpperCase().trim().compareTo("PEERTUBE") != 0;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, account.getToken());
editor.putString(Helper.PREF_SOFTWARE, remote_account ? account.getSoftware() : null);
editor.putString(Helper.PREF_REMOTE_INSTANCE, remote_account ? account.getHost() : null);
if (!remote_account) {
editor.putString(Helper.PREF_INSTANCE, account.getHost());
}
editor.putString(Helper.PREF_KEY_ID, account.getId());
editor.putString(Helper.PREF_KEY_NAME, account.getUsername());
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, account.token);
editor.putString(Helper.PREF_INSTANCE, account.instance);
editor.putString(Helper.PREF_KEY_ID, account.user_id);
editor.putString(Helper.PREF_KEY_NAME, account.peertube_account != null ? account.peertube_account.getUsername() : null);
editor.apply();
dialog.dismiss();
Intent intent = new Intent(activity, PeertubeMainActivity.class);
Intent intent = new Intent(activity, BaseMainActivity.class);
activity.startActivity(intent);
activity.finish();
});

View File

@ -1,391 +0,0 @@
package app.fedilab.android.peertube.sqlite;
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* 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.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.peertube.client.entities.Avatar;
import app.fedilab.android.peertube.client.entities.Token;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.helper.HelperInstance;
@SuppressWarnings("UnusedReturnValue")
public class AccountDAO {
private final SQLiteDatabase db;
public Context context;
public AccountDAO(Context context, SQLiteDatabase db) {
//Creation of the DB with tables
this.context = context;
this.db = db;
}
/**
* Insert an Account in database
*
* @param account Account
* @return boolean
*/
public boolean insertAccount(Account account, String software) {
ContentValues values = new ContentValues();
if (account.getCreatedAt() == null)
account.setCreatedAt(new Date());
if (account.getDescription() == null)
account.setDescription("");
values.put(Sqlite.COL_USER_ID, account.getId());
values.put(Sqlite.COL_USERNAME, account.getUsername());
values.put(Sqlite.COL_ACCT, account.getUsername() + "@" + account.getHost());
values.put(Sqlite.COL_DISPLAYED_NAME, account.getDisplayName() != null ? account.getDisplayName() : account.getUsername());
values.put(Sqlite.COL_FOLLOWERS_COUNT, account.getFollowersCount());
values.put(Sqlite.COL_FOLLOWING_COUNT, account.getFollowingCount());
values.put(Sqlite.COL_NOTE, account.getDescription());
values.put(Sqlite.COL_URL, account.getUrl());
values.put(Sqlite.COL_AVATAR, account.getAvatar() != null ? account.getAvatar().getPath() : "null");
values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(account.getCreatedAt()));
values.put(Sqlite.COL_INSTANCE, account.getHost());
values.put(Sqlite.COL_LOCKED, false);
values.put(Sqlite.COL_STATUSES_COUNT, 0);
values.put(Sqlite.COL_URL, "");
values.put(Sqlite.COL_AVATAR_STATIC, "");
values.put(Sqlite.COL_HEADER, "");
values.put(Sqlite.COL_HEADER_STATIC, "");
if (software != null && software.toUpperCase().trim().compareTo("PEERTUBE") != 0) {
values.put(Sqlite.COL_SOFTWARE, software.toUpperCase().trim());
}
if (account.getClient_id() != null && account.getClient_secret() != null) {
values.put(Sqlite.COL_CLIENT_ID, account.getClient_id());
values.put(Sqlite.COL_CLIENT_SECRET, account.getClient_secret());
}
if (account.getRefresh_token() != null) {
values.put(Sqlite.COL_REFRESH_TOKEN, account.getRefresh_token());
}
if (account.getToken() != null)
values.put(Sqlite.COL_OAUTHTOKEN, account.getToken());
//Inserts account
try {
db.insertOrThrow(Sqlite.TABLE_USER_ACCOUNT, null, values);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Update an Account in database
*
* @param account Account
* @return boolean
*/
public int updateAccount(Account account) {
ContentValues values = new ContentValues();
if (account.getCreatedAt() == null)
account.setCreatedAt(new Date());
if (account.getDescription() == null)
account.setDescription("");
values.put(Sqlite.COL_USER_ID, account.getId());
values.put(Sqlite.COL_USERNAME, account.getUsername());
values.put(Sqlite.COL_ACCT, account.getUsername() + "@" + account.getHost());
values.put(Sqlite.COL_DISPLAYED_NAME, account.getDisplayName());
values.put(Sqlite.COL_FOLLOWERS_COUNT, account.getFollowersCount());
values.put(Sqlite.COL_FOLLOWING_COUNT, account.getFollowingCount());
values.put(Sqlite.COL_NOTE, account.getDescription());
values.put(Sqlite.COL_URL, account.getUrl());
values.put(Sqlite.COL_AVATAR, account.getAvatar() != null ? account.getAvatar().getPath() : "null");
values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(account.getCreatedAt()));
try {
return db.update(Sqlite.TABLE_USER_ACCOUNT,
values, Sqlite.COL_USERNAME + " = ? AND " + Sqlite.COL_INSTANCE + " =?",
new String[]{account.getUsername(), account.getHost()});
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* Update an Account token in database
*
* @param token Token
* @return boolean
*/
public int updateAccountToken(Token token) {
ContentValues values = new ContentValues();
if (token.getRefresh_token() != null) {
values.put(Sqlite.COL_REFRESH_TOKEN, token.getRefresh_token());
}
if (token.getAccess_token() != null)
values.put(Sqlite.COL_OAUTHTOKEN, token.getAccess_token());
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = HelperInstance.getLiveInstance(context);
try {
return db.update(Sqlite.TABLE_USER_ACCOUNT,
values, Sqlite.COL_USER_ID + " = ? AND " + Sqlite.COL_INSTANCE + " =?",
new String[]{userId, instance});
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
/**
* Update an Account in database
*
* @param account Account
* @return boolean
*/
public int updateAccountCredential(Account account) {
ContentValues values = new ContentValues();
if (account.getCreatedAt() == null)
account.setCreatedAt(new Date());
if (account.getDescription() == null)
account.setDescription("");
values.put(Sqlite.COL_USERNAME, account.getUsername());
values.put(Sqlite.COL_ACCT, account.getUsername() + "@" + account.getHost());
values.put(Sqlite.COL_DISPLAYED_NAME, account.getDisplayName());
values.put(Sqlite.COL_FOLLOWERS_COUNT, account.getFollowersCount());
values.put(Sqlite.COL_FOLLOWING_COUNT, account.getFollowingCount());
values.put(Sqlite.COL_NOTE, account.getDescription());
values.put(Sqlite.COL_URL, account.getUrl());
values.put(Sqlite.COL_AVATAR, account.getAvatar().getPath());
values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(account.getCreatedAt()));
if (account.getClient_id() != null && account.getClient_secret() != null) {
values.put(Sqlite.COL_CLIENT_ID, account.getClient_id());
values.put(Sqlite.COL_CLIENT_SECRET, account.getClient_secret());
}
if (account.getRefresh_token() != null) {
values.put(Sqlite.COL_REFRESH_TOKEN, account.getRefresh_token());
}
if (account.getToken() != null)
values.put(Sqlite.COL_OAUTHTOKEN, account.getToken());
return db.update(Sqlite.TABLE_USER_ACCOUNT,
values, Sqlite.COL_USER_ID + " = ? AND " + Sqlite.COL_INSTANCE + " =?",
new String[]{account.getId(), account.getHost()});
}
public int removeUser(Account account) {
return db.delete(Sqlite.TABLE_USER_ACCOUNT, Sqlite.COL_USER_ID + " = '" + account.getId() +
"' AND " + Sqlite.COL_INSTANCE + " = '" + account.getHost() + "'", null);
}
/**
* Returns last used account
*
* @return Account
*/
public Account getLastUsedAccount() {
try {
Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_OAUTHTOKEN + " != 'null'", null, null, null, Sqlite.COL_UPDATED_AT + " DESC", "1");
return cursorToUser(c);
} catch (Exception e) {
return null;
}
}
/**
* Returns all Account in db
*
* @return Account List<Account>
*/
public List<Account> getAllAccount() {
try {
Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, null, null, null, null, Sqlite.COL_INSTANCE + " ASC", null);
return cursorToListUser(c);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Returns all Peertube Account only in db
*
* @return Account List<Account>
*/
public List<Account> getAllPeertubeAccount() {
try {
Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_SOFTWARE + "=? OR " + Sqlite.COL_SOFTWARE + " is null", new String[]{"PEERTUBE"}, null, null, Sqlite.COL_INSTANCE + " ASC", null);
return cursorToListUser(c);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Returns an Account by token
*
* @param token String
* @return Account
*/
public Account getAccountByToken(String token) {
try {
Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_OAUTHTOKEN + " = \"" + token + "\"", null, null, null, null, "1");
return cursorToUser(c);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Returns an Account by id and instance
*
* @param id String
* @param instance String
* @return Account
*/
public Account getAccountByIdInstance(String id, String instance) {
try {
Cursor c = db.query(Sqlite.TABLE_USER_ACCOUNT, null, Sqlite.COL_USER_ID + " = \"" + id + "\" AND " + Sqlite.COL_INSTANCE + " = \"" + instance + "\"", null, null, null, null, "1");
return cursorToUser(c);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Test if the current user is already stored in data base
*
* @param account Account
* @return boolean
*/
public boolean userExist(Account account) {
Cursor mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_USER_ACCOUNT
+ " where " + Sqlite.COL_USERNAME + " = '" + account.getUsername() + "' AND " + Sqlite.COL_INSTANCE + " = '" + account.getHost() + "'", null);
mCount.moveToFirst();
int count = mCount.getInt(0);
mCount.close();
return (count > 0);
}
/***
* Method to hydrate an Account from database
* @param c Cursor
* @return Account
*/
private Account cursorToUser(Cursor c) {
//No element found
if (c.getCount() == 0) {
c.close();
return null;
}
//Take the first element
c.moveToFirst();
//New user
Account account = new Account();
account.setId(c.getString(c.getColumnIndex(Sqlite.COL_USER_ID)));
account.setUsername(c.getString(c.getColumnIndex(Sqlite.COL_USERNAME)));
account.setDisplayName(c.getString(c.getColumnIndex(Sqlite.COL_DISPLAYED_NAME)));
account.setFollowersCount(c.getInt(c.getColumnIndex(Sqlite.COL_FOLLOWERS_COUNT)));
account.setFollowingCount(c.getInt(c.getColumnIndex(Sqlite.COL_FOLLOWING_COUNT)));
account.setDescription(c.getString(c.getColumnIndex(Sqlite.COL_NOTE)));
account.setUrl(c.getString(c.getColumnIndex(Sqlite.COL_URL)));
Avatar avatar = new Avatar();
avatar.setPath(c.getString(c.getColumnIndex(Sqlite.COL_AVATAR)));
account.setAvatar(avatar);
account.setUpdatedAt(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_UPDATED_AT))));
account.setCreatedAt(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_CREATED_AT))));
account.setHost(c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE)));
account.setToken(c.getString(c.getColumnIndex(Sqlite.COL_OAUTHTOKEN)));
account.setSoftware(c.getString(c.getColumnIndex(Sqlite.COL_SOFTWARE)));
account.setClient_id(c.getString(c.getColumnIndex(Sqlite.COL_CLIENT_ID)));
account.setClient_secret(c.getString(c.getColumnIndex(Sqlite.COL_CLIENT_SECRET)));
account.setRefresh_token(c.getString(c.getColumnIndex(Sqlite.COL_REFRESH_TOKEN)));
//Close the cursor
c.close();
//User is returned
return account;
}
/***
* Method to hydrate an Accounts from database
* @param c Cursor
* @return List<Account>
*/
private List<Account> cursorToListUser(Cursor c) {
//No element found
if (c.getCount() == 0) {
c.close();
return null;
}
List<Account> accounts = new ArrayList<>();
while (c.moveToNext()) {
//New user
Account account = new Account();
account.setId(c.getString(c.getColumnIndex(Sqlite.COL_USER_ID)));
account.setUsername(c.getString(c.getColumnIndex(Sqlite.COL_USERNAME)));
account.setDisplayName(c.getString(c.getColumnIndex(Sqlite.COL_DISPLAYED_NAME)));
account.setFollowersCount(c.getInt(c.getColumnIndex(Sqlite.COL_FOLLOWERS_COUNT)));
account.setFollowingCount(c.getInt(c.getColumnIndex(Sqlite.COL_FOLLOWING_COUNT)));
account.setDescription(c.getString(c.getColumnIndex(Sqlite.COL_NOTE)));
account.setUrl(c.getString(c.getColumnIndex(Sqlite.COL_URL)));
Avatar avatar = new Avatar();
avatar.setPath(c.getString(c.getColumnIndex(Sqlite.COL_AVATAR)));
account.setAvatar(avatar);
account.setUpdatedAt(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_UPDATED_AT))));
account.setCreatedAt(Helper.stringToDate(context, c.getString(c.getColumnIndex(Sqlite.COL_CREATED_AT))));
account.setHost(c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE)));
account.setToken(c.getString(c.getColumnIndex(Sqlite.COL_OAUTHTOKEN)));
account.setSoftware(c.getString(c.getColumnIndex(Sqlite.COL_SOFTWARE)));
account.setClient_id(c.getString(c.getColumnIndex(Sqlite.COL_CLIENT_ID)));
account.setClient_secret(c.getString(c.getColumnIndex(Sqlite.COL_CLIENT_SECRET)));
account.setRefresh_token(c.getString(c.getColumnIndex(Sqlite.COL_REFRESH_TOKEN)));
accounts.add(account);
}
//Close the cursor
c.close();
//Users list is returned
return accounts;
}
}

View File

@ -1,377 +0,0 @@
package app.fedilab.android.peertube.sqlite;
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* 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.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import app.fedilab.android.peertube.client.data.PlaylistData;
import app.fedilab.android.peertube.client.data.VideoData;
import app.fedilab.android.peertube.client.data.VideoPlaylistData;
@SuppressWarnings("UnusedReturnValue")
public class ManagePlaylistsDAO {
private final SQLiteDatabase db;
public Context context;
public ManagePlaylistsDAO(Context context, SQLiteDatabase db) {
//Creation of the DB with tables
this.context = context;
this.db = db;
}
/**
* Unserialized Video
*
* @param serializedVideo String serialized Video
* @return Video
*/
public static VideoData.Video restoreVideoFromString(String serializedVideo) {
Gson gson = new Gson();
try {
return gson.fromJson(serializedVideo, VideoData.Video.class);
} catch (Exception e) {
return null;
}
}
/**
* Serialized Video class
*
* @param video Video to serialize
* @return String serialized video
*/
public static String videoToStringStorage(VideoData.Video video) {
Gson gson = new Gson();
try {
return gson.toJson(video);
} catch (Exception e) {
return null;
}
}
/**
* Unserialized Playlist
*
* @param serializedPlaylist String serialized Playlist
* @return Playlist
*/
public static PlaylistData.Playlist restorePlaylistFromString(String serializedPlaylist) {
Gson gson = new Gson();
try {
return gson.fromJson(serializedPlaylist, PlaylistData.Playlist.class);
} catch (Exception e) {
return null;
}
}
/**
* Serialized Playlist class
*
* @param playlist Playlist to serialize
* @return String serialized playlist
*/
public static String playlistToStringStorage(PlaylistData.Playlist playlist) {
Gson gson = new Gson();
try {
return gson.toJson(playlist);
} catch (Exception e) {
return null;
}
}
/**
* Insert playlist info in database
*
* @param videoPlaylistExport VideoPlaylistExport
* @return boolean
*/
public boolean insertPlaylist(VideoPlaylistData.VideoPlaylistExport videoPlaylistExport) {
if (videoPlaylistExport.getPlaylist() == null) {
return true;
}
ContentValues values = new ContentValues();
values.put(Sqlite.COL_ACCT, videoPlaylistExport.getAcct());
values.put(Sqlite.COL_UUID, videoPlaylistExport.getUuid());
values.put(Sqlite.COL_PLAYLIST, playlistToStringStorage(videoPlaylistExport.getPlaylist()));
//Inserts playlist
try {
long id = checkExists(videoPlaylistExport.getPlaylist().getUuid());
if (id != -1) {
videoPlaylistExport.setPlaylistDBkey(id);
removeAllVideosInPlaylist(id);
} else {
long playlist_id = db.insertOrThrow(Sqlite.TABLE_LOCAL_PLAYLISTS, null, values);
videoPlaylistExport.setPlaylistDBkey(playlist_id);
}
for (VideoPlaylistData.VideoPlaylist videoPlaylist : videoPlaylistExport.getVideos()) {
//Insert videos
insertVideos(videoPlaylist.getVideo(), videoPlaylistExport);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Insert videos for playlists in database
*
* @param video Video to insert
* @param playlist VideoPlaylistExport targeted
* @return boolean
*/
private boolean insertVideos(VideoData.Video video, VideoPlaylistData.VideoPlaylistExport playlist) {
if (video == null || playlist == null) {
return true;
}
ContentValues values = new ContentValues();
values.put(Sqlite.COL_UUID, video.getUuid());
values.put(Sqlite.COL_PLAYLIST_ID, playlist.getPlaylistDBkey());
values.put(Sqlite.COL_VIDEO_DATA, videoToStringStorage(video));
//Inserts playlist
try {
db.insertOrThrow(Sqlite.TABLE_VIDEOS, null, values);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Check if playlist exists
*
* @param uuid String
* @return int
*/
private long checkExists(String uuid) {
try {
Cursor c = db.query(Sqlite.TABLE_LOCAL_PLAYLISTS, null, Sqlite.COL_UUID + " = \"" + uuid + "\"", null, null, null, null, "1");
VideoPlaylistData.VideoPlaylistExport videoPlaylistExport = cursorToSingleVideoPlaylistExport(c);
c.close();
return videoPlaylistExport != null ? videoPlaylistExport.getPlaylistDBkey() : -1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* Check if playlist exists
*
* @param videoUuid String
* @param playlistUuid String
* @return int
*/
private boolean checkVideoExists(String videoUuid, String playlistUuid) {
try {
String check_query = "SELECT * FROM " + Sqlite.TABLE_LOCAL_PLAYLISTS + " p INNER JOIN "
+ Sqlite.TABLE_VIDEOS + " v ON p.id = v." + Sqlite.COL_PLAYLIST_ID
+ " WHERE p." + Sqlite.COL_UUID + "=? AND v." + Sqlite.COL_UUID + "=? LIMIT 1";
Cursor c = db.rawQuery(check_query, new String[]{playlistUuid, videoUuid});
int count = c.getCount();
c.close();
return count > 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Remove all videos in playlist
*
* @param playlistDBid long db id
* @return int
*/
public int removeAllVideosInPlaylist(long playlistDBid) {
return db.delete(Sqlite.TABLE_VIDEOS, Sqlite.COL_PLAYLIST_ID + " = '" + playlistDBid + "'", null);
}
/**
* Remove a playlist with its uuid
*
* @param uuid String uuid of the Playlist
* @return int
*/
public int removePlaylist(String uuid) {
VideoPlaylistData.VideoPlaylistExport videoPlaylistExport = getSinglePlaylists(uuid);
db.delete(Sqlite.TABLE_VIDEOS, Sqlite.COL_PLAYLIST_ID + " = '" + videoPlaylistExport.getPlaylistDBkey() + "'", null);
return db.delete(Sqlite.TABLE_LOCAL_PLAYLISTS, Sqlite.COL_ID + " = '" + videoPlaylistExport.getPlaylistDBkey() + "'", null);
}
/**
* Returns a playlist from it's uid in db
*
* @return VideoPlaylistExport
*/
public VideoPlaylistData.VideoPlaylistExport getSinglePlaylists(String uuid) {
try {
Cursor c = db.query(Sqlite.TABLE_LOCAL_PLAYLISTS, null, Sqlite.COL_UUID + "='" + uuid + "'", null, null, null, Sqlite.COL_ID + " DESC", null);
return cursorToSingleVideoPlaylistExport(c);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Returns all playlists in db
*
* @return List<VideoPlaylistData.VideoPlaylistExport>
*/
public List<VideoPlaylistData.VideoPlaylistExport> getAllPlaylists() {
try {
Cursor c = db.query(Sqlite.TABLE_LOCAL_PLAYLISTS, null, null, null, null, null, Sqlite.COL_ID + " DESC", null);
return cursorToVideoPlaylistExport(c);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Returns all videos in a playlist
*
* @return List<VideoData.VideoExport>
*/
public List<VideoData.VideoExport> getAllVideosInPlaylist(VideoPlaylistData.VideoPlaylistExport videoPlaylistExport) {
try {
Cursor c = db.query(Sqlite.TABLE_VIDEOS, null, Sqlite.COL_PLAYLIST_ID + "='" + videoPlaylistExport.getPlaylistDBkey() + "'", null, null, null, Sqlite.COL_ID + " DESC", null);
return cursorToVideoExport(c);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Returns all videos in a playlist
*
* @return List<VideoData.VideoExport>
*/
public List<VideoData.VideoExport> getAllVideosInPlaylist(String uuid) {
try {
VideoPlaylistData.VideoPlaylistExport videoPlaylistExport = getSinglePlaylists(uuid);
Cursor c = db.query(Sqlite.TABLE_VIDEOS, null, Sqlite.COL_PLAYLIST_ID + "='" + videoPlaylistExport.getPlaylistDBkey() + "'", null, null, null, Sqlite.COL_ID + " DESC", null);
return cursorToVideoExport(c);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/***
* Method to hydrate VideoPlaylistExport from database
* @param c Cursor
* @return VideoPlaylistData.VideoPlaylistExport
*/
private VideoPlaylistData.VideoPlaylistExport cursorToSingleVideoPlaylistExport(Cursor c) {
//No element found
if (c.getCount() == 0) {
c.close();
return null;
}
c.moveToFirst();
VideoPlaylistData.VideoPlaylistExport videoPlaylistExport = new VideoPlaylistData.VideoPlaylistExport();
videoPlaylistExport.setAcct(c.getString(c.getColumnIndex(Sqlite.COL_ACCT)));
videoPlaylistExport.setUuid(c.getString(c.getColumnIndex(Sqlite.COL_UUID)));
videoPlaylistExport.setPlaylistDBkey(c.getInt(c.getColumnIndex(Sqlite.COL_ID)));
videoPlaylistExport.setPlaylist(restorePlaylistFromString(c.getString(c.getColumnIndex(Sqlite.COL_PLAYLIST))));
//Close the cursor
c.close();
return videoPlaylistExport;
}
/***
* Method to hydrate VideoPlaylistExport from database
* @param c Cursor
* @return List<VideoPlaylistData.VideoPlaylistExport>
*/
private List<VideoPlaylistData.VideoPlaylistExport> cursorToVideoPlaylistExport(Cursor c) {
//No element found
if (c.getCount() == 0) {
c.close();
return null;
}
List<VideoPlaylistData.VideoPlaylistExport> videoPlaylistExports = new ArrayList<>();
while (c.moveToNext()) {
VideoPlaylistData.VideoPlaylistExport videoPlaylistExport = new VideoPlaylistData.VideoPlaylistExport();
videoPlaylistExport.setAcct(c.getString(c.getColumnIndex(Sqlite.COL_ACCT)));
videoPlaylistExport.setUuid(c.getString(c.getColumnIndex(Sqlite.COL_UUID)));
videoPlaylistExport.setPlaylistDBkey(c.getInt(c.getColumnIndex(Sqlite.COL_ID)));
videoPlaylistExport.setPlaylist(restorePlaylistFromString(c.getString(c.getColumnIndex(Sqlite.COL_PLAYLIST))));
videoPlaylistExports.add(videoPlaylistExport);
}
//Close the cursor
c.close();
return videoPlaylistExports;
}
/***
* Method to hydrate Video from database
* @param c Cursor
* @return List<VideoData.Video>
*/
private List<VideoData.VideoExport> cursorToVideoExport(Cursor c) {
//No element found
if (c.getCount() == 0) {
c.close();
return null;
}
List<VideoData.VideoExport> videoExports = new ArrayList<>();
while (c.moveToNext()) {
VideoData.VideoExport videoExport = new VideoData.VideoExport();
videoExport.setPlaylistDBid(c.getInt(c.getColumnIndex(Sqlite.COL_PLAYLIST_ID)));
videoExport.setUuid(c.getString(c.getColumnIndex(Sqlite.COL_UUID)));
videoExport.setId(c.getInt(c.getColumnIndex(Sqlite.COL_ID)));
videoExport.setVideoData(restoreVideoFromString(c.getString(c.getColumnIndex(Sqlite.COL_VIDEO_DATA))));
videoExports.add(videoExport);
}
//Close the cursor
c.close();
return videoExports;
}
}

View File

@ -1,219 +0,0 @@
package app.fedilab.android.peertube.sqlite;
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* 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.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.Date;
import app.fedilab.android.peertube.client.entities.Token;
import app.fedilab.android.peertube.client.mastodon.MastodonAccount.Account;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.helper.HelperInstance;
@SuppressWarnings("UnusedReturnValue")
public class MastodonAccountDAO {
private final SQLiteDatabase db;
public Context context;
public MastodonAccountDAO(Context context, SQLiteDatabase db) {
//Creation of the DB with tables
this.context = context;
this.db = db;
}
/**
* Insert an Account in database
*
* @param account Account
* @return boolean
*/
public boolean insertAccount(Account account) {
ContentValues values = new ContentValues();
if (account.getCreatedAt() == null)
account.setCreatedAt(new Date());
if (account.getDescription() == null)
account.setDescription("");
values.put(Sqlite.COL_USER_ID, account.getId());
values.put(Sqlite.COL_USERNAME, account.getUsername());
values.put(Sqlite.COL_ACCT, account.getUsername() + "@" + account.getHost());
values.put(Sqlite.COL_DISPLAYED_NAME, account.getDisplayName() != null ? account.getDisplayName() : account.getUsername());
values.put(Sqlite.COL_FOLLOWERS_COUNT, account.getFollowersCount());
values.put(Sqlite.COL_FOLLOWING_COUNT, account.getFollowingCount());
values.put(Sqlite.COL_NOTE, account.getDescription());
values.put(Sqlite.COL_URL, account.getUrl());
values.put(Sqlite.COL_AVATAR, account.getAvatar());
values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(account.getCreatedAt()));
values.put(Sqlite.COL_INSTANCE, account.getHost());
values.put(Sqlite.COL_LOCKED, false);
values.put(Sqlite.COL_STATUSES_COUNT, 0);
values.put(Sqlite.COL_URL, "");
values.put(Sqlite.COL_AVATAR_STATIC, "");
values.put(Sqlite.COL_HEADER, "");
values.put(Sqlite.COL_HEADER_STATIC, "");
if (account.getSoftware() != null && account.getSoftware().toUpperCase().trim().compareTo("PEERTUBE") != 0) {
values.put(Sqlite.COL_SOFTWARE, account.getSoftware().toUpperCase().trim());
}
if (account.getClient_id() != null && account.getClient_secret() != null) {
values.put(Sqlite.COL_CLIENT_ID, account.getClient_id());
values.put(Sqlite.COL_CLIENT_SECRET, account.getClient_secret());
}
if (account.getRefresh_token() != null) {
values.put(Sqlite.COL_REFRESH_TOKEN, account.getRefresh_token());
}
if (account.getToken() != null)
values.put(Sqlite.COL_OAUTHTOKEN, account.getToken());
//Inserts account
try {
db.insertOrThrow(Sqlite.TABLE_USER_ACCOUNT, null, values);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Update an Account in database
*
* @param account Account
* @return boolean
*/
public int updateAccount(Account account) {
ContentValues values = new ContentValues();
if (account.getCreatedAt() == null)
account.setCreatedAt(new Date());
if (account.getDescription() == null)
account.setDescription("");
values.put(Sqlite.COL_USER_ID, account.getId());
values.put(Sqlite.COL_USERNAME, account.getUsername());
values.put(Sqlite.COL_ACCT, account.getUsername() + "@" + account.getHost());
values.put(Sqlite.COL_DISPLAYED_NAME, account.getDisplayName());
values.put(Sqlite.COL_FOLLOWERS_COUNT, account.getFollowersCount());
values.put(Sqlite.COL_FOLLOWING_COUNT, account.getFollowingCount());
values.put(Sqlite.COL_NOTE, account.getDescription());
values.put(Sqlite.COL_URL, account.getUrl());
values.put(Sqlite.COL_AVATAR, account.getAvatar());
values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(account.getCreatedAt()));
try {
return db.update(Sqlite.TABLE_USER_ACCOUNT,
values, Sqlite.COL_USERNAME + " = ? AND " + Sqlite.COL_INSTANCE + " =?",
new String[]{account.getUsername(), account.getHost()});
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* Update an Account token in database
*
* @param token Token
* @return boolean
*/
public int updateAccountToken(Token token) {
ContentValues values = new ContentValues();
if (token.getRefresh_token() != null) {
values.put(Sqlite.COL_REFRESH_TOKEN, token.getRefresh_token());
}
if (token.getAccess_token() != null)
values.put(Sqlite.COL_OAUTHTOKEN, token.getAccess_token());
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = HelperInstance.getLiveInstance(context);
try {
return db.update(Sqlite.TABLE_USER_ACCOUNT,
values, Sqlite.COL_USER_ID + " = ? AND " + Sqlite.COL_INSTANCE + " =?",
new String[]{userId, instance});
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
/**
* Update an Account in database
*
* @param account Account
* @return boolean
*/
public int updateAccountCredential(Account account) {
ContentValues values = new ContentValues();
if (account.getCreatedAt() == null)
account.setCreatedAt(new Date());
if (account.getDescription() == null)
account.setDescription("");
values.put(Sqlite.COL_USERNAME, account.getUsername());
values.put(Sqlite.COL_ACCT, account.getUsername() + "@" + account.getHost());
values.put(Sqlite.COL_DISPLAYED_NAME, account.getDisplayName());
values.put(Sqlite.COL_FOLLOWERS_COUNT, account.getFollowersCount());
values.put(Sqlite.COL_FOLLOWING_COUNT, account.getFollowingCount());
values.put(Sqlite.COL_NOTE, account.getDescription());
values.put(Sqlite.COL_URL, account.getUrl());
values.put(Sqlite.COL_AVATAR, account.getAvatar());
values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(account.getCreatedAt()));
if (account.getClient_id() != null && account.getClient_secret() != null) {
values.put(Sqlite.COL_CLIENT_ID, account.getClient_id());
values.put(Sqlite.COL_CLIENT_SECRET, account.getClient_secret());
}
if (account.getRefresh_token() != null) {
values.put(Sqlite.COL_REFRESH_TOKEN, account.getRefresh_token());
}
if (account.getToken() != null)
values.put(Sqlite.COL_OAUTHTOKEN, account.getToken());
return db.update(Sqlite.TABLE_USER_ACCOUNT,
values, Sqlite.COL_USER_ID + " = ? AND " + Sqlite.COL_INSTANCE + " =?",
new String[]{account.getId(), account.getHost()});
}
public int removeUser(Account account) {
return db.delete(Sqlite.TABLE_USER_ACCOUNT, Sqlite.COL_USER_ID + " = '" + account.getId() +
"' AND " + Sqlite.COL_INSTANCE + " = '" + account.getHost() + "'", null);
}
/**
* Test if the current user is already stored in data base
*
* @param account Account
* @return boolean
*/
public boolean userExist(Account account) {
Cursor mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_USER_ACCOUNT
+ " where " + Sqlite.COL_USERNAME + " = '" + account.getUsername() + "' AND " + Sqlite.COL_INSTANCE + " = '" + account.getHost() + "'", null);
mCount.moveToFirst();
int count = mCount.getInt(0);
mCount.close();
return (count > 0);
}
}

View File

@ -1,214 +0,0 @@
package app.fedilab.android.peertube.sqlite;
/* Copyright 2020 Thomas Schneider
*
* This file is a part of TubeLab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* 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.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Sqlite extends SQLiteOpenHelper {
public static final int DB_VERSION = 4;
public static final String DB_NAME = "mastodon_etalab_db";
/***
* List of tables to manage users and data
*/
//Table of owned accounts
static final String TABLE_USER_ACCOUNT = "USER_ACCOUNT";
static final String COL_USER_ID = "USER_ID";
static final String COL_USERNAME = "USERNAME";
static final String COL_ACCT = "ACCT";
static final String COL_DISPLAYED_NAME = "DISPLAYED_NAME";
static final String COL_LOCKED = "LOCKED";
static final String COL_CREATED_AT = "CREATED_AT";
static final String COL_FOLLOWERS_COUNT = "FOLLOWERS_COUNT";
static final String COL_FOLLOWING_COUNT = "FOLLOWING_COUNT";
static final String COL_STATUSES_COUNT = "STATUSES_COUNT";
static final String COL_NOTE = "NOTE";
static final String COL_URL = "URL";
static final String COL_AVATAR = "AVATAR";
static final String COL_AVATAR_STATIC = "AVATAR_STATIC";
static final String COL_HEADER = "HEADER";
static final String COL_HEADER_STATIC = "HEADER_STATIC";
static final String COL_INSTANCE = "INSTANCE";
static final String COL_OAUTHTOKEN = "OAUTH_TOKEN";
static final String COL_CLIENT_ID = "CLIENT_ID";
static final String COL_CLIENT_SECRET = "CLIENT_SECRET";
static final String COL_REFRESH_TOKEN = "REFRESH_TOKEN";
static final String COL_IS_MODERATOR = "IS_MODERATOR";
static final String COL_IS_ADMIN = "IS_ADMIN";
static final String COL_UPDATED_AT = "UPDATED_AT";
static final String COL_PRIVACY = "PRIVACY";
static final String COL_SENSITIVE = "SENSITIVE";
//Table for peertube favorites
static final String TABLE_PEERTUBE_FAVOURITES = "PEERTUBE_FAVOURITES";
static final String COL_ID = "ID";
static final String COL_UUID = "UUID";
static final String COL_CACHE = "CACHE";
static final String COL_DATE = "DATE";
static final String COL_USER_INSTANCE = "USER_INSTANCE";
static final String TABLE_BOOKMARKED_INSTANCES = "BOOKMARKED_INSTANCES";
static final String COL_ABOUT = "ABOUT";
static final String TABLE_LOCAL_PLAYLISTS = "LOCAL_PLAYLISTS";
static final String COL_PLAYLIST = "PLAYLIST";
static final String TABLE_VIDEOS = "VIDEOS";
static final String COL_VIDEO_DATA = "VIDEO_DATA";
static final String COL_PLAYLIST_ID = "PLAYLIST_ID";
static final String COL_SOFTWARE = "SOFTWARE";
private static final String CREATE_TABLE_USER_ACCOUNT = "CREATE TABLE " + TABLE_USER_ACCOUNT + " ("
+ COL_USER_ID + " TEXT, " + COL_USERNAME + " TEXT NOT NULL, " + COL_ACCT + " TEXT NOT NULL, "
+ COL_DISPLAYED_NAME + " TEXT NOT NULL, " + COL_LOCKED + " INTEGER NOT NULL, "
+ COL_FOLLOWERS_COUNT + " INTEGER NOT NULL, " + COL_FOLLOWING_COUNT + " INTEGER NOT NULL, " + COL_STATUSES_COUNT + " INTEGER NOT NULL, "
+ COL_NOTE + " TEXT NOT NULL, " + COL_URL + " TEXT NOT NULL, "
+ COL_AVATAR + " TEXT NOT NULL, " + COL_AVATAR_STATIC + " TEXT NOT NULL, "
+ COL_HEADER + " TEXT NOT NULL, " + COL_HEADER_STATIC + " TEXT NOT NULL, "
+ COL_IS_MODERATOR + " INTEGER DEFAULT 0, "
+ COL_IS_ADMIN + " INTEGER DEFAULT 0, "
+ COL_CLIENT_ID + " TEXT, " + COL_CLIENT_SECRET + " TEXT, " + COL_REFRESH_TOKEN + " TEXT,"
+ COL_UPDATED_AT + " TEXT, "
+ COL_PRIVACY + " TEXT, "
+ COL_SOFTWARE + " TEXT NOT NULL DEFAULT \"PEERTUBE\", "
+ COL_SENSITIVE + " INTEGER DEFAULT 0, "
+ COL_INSTANCE + " TEXT NOT NULL, " + COL_OAUTHTOKEN + " TEXT NOT NULL, " + COL_CREATED_AT + " TEXT NOT NULL)";
public static SQLiteDatabase db;
private static Sqlite sInstance;
private final String CREATE_TABLE_PEERTUBE_FAVOURITES = "CREATE TABLE "
+ TABLE_PEERTUBE_FAVOURITES + "("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_UUID + " TEXT NOT NULL, "
+ COL_INSTANCE + " TEXT NOT NULL, "
+ COL_CACHE + " TEXT NOT NULL, "
+ COL_DATE + " TEXT NOT NULL)";
private final String CREATE_TABLE_STORED_INSTANCES = "CREATE TABLE "
+ TABLE_BOOKMARKED_INSTANCES + "("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_INSTANCE + " TEXT NOT NULL, "
+ COL_USER_ID + " TEXT NOT NULL, "
+ COL_ABOUT + " TEXT NOT NULL, "
+ COL_USER_INSTANCE + " TEXT NOT NULL)";
private final String CREATE_TABLE_LOCAL_PLAYLISTS = "CREATE TABLE "
+ TABLE_LOCAL_PLAYLISTS + "("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_ACCT + " TEXT NOT NULL, "
+ COL_UUID + " TEXT NOT NULL, "
+ COL_PLAYLIST + " TEXT NOT NULL)";
private final String CREATE_TABLE_VIDEOS = "CREATE TABLE "
+ TABLE_VIDEOS + "("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_UUID + " TEXT NOT NULL, "
+ COL_VIDEO_DATA + " TEXT NOT NULL, "
+ COL_PLAYLIST_ID + " INTEGER, "
+ " FOREIGN KEY (" + COL_PLAYLIST_ID + ") REFERENCES " + COL_PLAYLIST + "(" + COL_ID + "));";
public Sqlite(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public static synchronized Sqlite getInstance(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
if (sInstance == null) {
sInstance = new Sqlite(context, name, factory, version);
}
return sInstance;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USER_ACCOUNT);
db.execSQL(CREATE_TABLE_PEERTUBE_FAVOURITES);
db.execSQL(CREATE_TABLE_STORED_INSTANCES);
db.execSQL(CREATE_TABLE_LOCAL_PLAYLISTS);
db.execSQL(CREATE_TABLE_VIDEOS);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
case 4:
dropColumn(TABLE_USER_ACCOUNT, new String[]{COL_SOFTWARE});
case 3:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_VIDEOS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCAL_PLAYLISTS);
case 2:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKMARKED_INSTANCES);
}
}
@SuppressWarnings("SameParameterValue")
private void dropColumn(
String tableName,
String[] colsToRemove) {
List<String> updatedTableColumns = getTableColumns(tableName);
// Remove the columns we don't want anymore from the table's list of columns
updatedTableColumns.removeAll(Arrays.asList(colsToRemove));
String columnsSeperated = TextUtils.join(",", updatedTableColumns);
db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tableName + "_old;");
// Creating the table on its new format (no redundant columns)
db.execSQL("CREATE TABLE " + tableName);
// Populating the table with the data
db.execSQL("INSERT INTO " + tableName + "(" + columnsSeperated + ") SELECT "
+ columnsSeperated + " FROM " + tableName + "_old;");
db.execSQL("DROP TABLE " + tableName + "_old;");
}
public List<String> getTableColumns(String tableName) {
ArrayList<String> columns = new ArrayList<>();
String cmd = "pragma table_info(" + tableName + ");";
Cursor cur = db.rawQuery(cmd, null);
while (cur.moveToNext()) {
columns.add(cur.getString(cur.getColumnIndex("name")));
}
cur.close();
return columns;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
case 1:
db.execSQL(CREATE_TABLE_STORED_INSTANCES);
case 2:
db.execSQL(CREATE_TABLE_LOCAL_PLAYLISTS);
db.execSQL(CREATE_TABLE_VIDEOS);
case 3:
db.execSQL("ALTER TABLE " + TABLE_USER_ACCOUNT + " ADD COLUMN " + COL_SOFTWARE + " TEXT NOT NULL DEFAULT \"PEERTUBE\"");
}
}
public SQLiteDatabase open() {
//opened with write access
db = getWritableDatabase();
return db;
}
public void close() {
//Close the db
if (db != null && db.isOpen()) {
db.close();
}
}
}

View File

@ -28,6 +28,7 @@ import java.util.List;
import app.fedilab.android.peertube.client.data.InstanceData;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.helper.HelperInstance;
import app.fedilab.android.sqlite.Sqlite;
@SuppressWarnings("UnusedReturnValue")
@ -181,7 +182,7 @@ public class StoredInstanceDAO {
//Take the first element
c.moveToFirst();
//New user
String aboutInstanceStr = c.getString(c.getColumnIndex(Sqlite.COL_ABOUT));
String aboutInstanceStr = c.getString(c.getColumnIndexOrThrow(Sqlite.COL_ABOUT));
InstanceData.AboutInstance aboutInstance = restoreAboutInstanceFromString(aboutInstanceStr);
//Close the cursor
c.close();
@ -202,8 +203,8 @@ public class StoredInstanceDAO {
}
List<InstanceData.AboutInstance> aboutInstances = new ArrayList<>();
while (c.moveToNext()) {
String aboutInstanceStr = c.getString(c.getColumnIndex(Sqlite.COL_ABOUT));
String instance = c.getString(c.getColumnIndex(Sqlite.COL_INSTANCE));
String aboutInstanceStr = c.getString(c.getColumnIndexOrThrow(Sqlite.COL_ABOUT));
String instance = c.getString(c.getColumnIndexOrThrow(Sqlite.COL_INSTANCE));
InstanceData.AboutInstance aboutInstance = restoreAboutInstanceFromString(aboutInstanceStr);
aboutInstance.setHost(instance);
aboutInstances.add(aboutInstance);

View File

@ -32,8 +32,6 @@ import app.fedilab.android.peertube.client.APIResponse;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.AccountData;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.sqlite.AccountDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
public class ChannelsVM extends AndroidViewModel {
@ -64,7 +62,7 @@ public class ChannelsVM extends AndroidViewModel {
SharedPreferences sharedpreferences = _mContext.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
SQLiteDatabase db = Sqlite.getInstance(_mContext.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String token = Helper.getToken(_mContext);
AccountData.Account account = new AccountDAO(_mContext, db).getAccountByToken(token);
AccountData.PeertubeAccount account = new AccountDAO(_mContext, db).getAccountByToken(token);
finalElement = account.getUsername() + "@" + account.getHost();
}
RetrofitPeertubeAPI retrofitPeertubeAPI;

View File

@ -28,7 +28,6 @@ import androidx.lifecycle.MutableLiveData;
import java.util.List;
import app.fedilab.android.peertube.client.data.InstanceData;
import app.fedilab.android.peertube.sqlite.Sqlite;
import app.fedilab.android.peertube.sqlite.StoredInstanceDAO;

View File

@ -26,7 +26,6 @@ import androidx.lifecycle.MutableLiveData;
import app.fedilab.android.peertube.client.APIResponse;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.AccountData.Account;
public class NotificationsVM extends AndroidViewModel {

View File

@ -16,7 +16,6 @@ package app.fedilab.android.peertube.viewmodel;
import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Looper;
@ -28,15 +27,13 @@ import androidx.lifecycle.MutableLiveData;
import java.util.ArrayList;
import java.util.List;
import app.fedilab.android.mastodon.client.entities.app.Account;
import app.fedilab.android.mastodon.client.entities.app.BaseAccount;
import app.fedilab.android.peertube.client.APIResponse;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.AccountData.Account;
import app.fedilab.android.peertube.client.data.PlaylistData.Playlist;
import app.fedilab.android.peertube.client.data.VideoPlaylistData;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.sqlite.AccountDAO;
import app.fedilab.android.peertube.sqlite.ManagePlaylistsDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
public class PlaylistsVM extends AndroidViewModel {
@ -53,11 +50,6 @@ public class PlaylistsVM extends AndroidViewModel {
return apiResponseMutableLiveData;
}
public LiveData<List<VideoPlaylistData.VideoPlaylistExport>> localePlaylist() {
videoPlaylistExportMutableLiveData = new MutableLiveData<>();
loadLocalePlaylist();
return videoPlaylistExportMutableLiveData;
}
public LiveData<APIResponse> videoExists(List<String> videoIds) {
@ -77,28 +69,13 @@ public class PlaylistsVM extends AndroidViewModel {
}
private void loadLocalePlaylist() {
Context _mContext = getApplication().getApplicationContext();
new Thread(() -> {
try {
SQLiteDatabase db = Sqlite.getInstance(_mContext.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<VideoPlaylistData.VideoPlaylistExport> videoPlaylistExports = new ManagePlaylistsDAO(_mContext, db).getAllPlaylists();
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> videoPlaylistExportMutableLiveData.setValue(videoPlaylistExports);
mainHandler.post(myRunnable);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
private void managePlaylists(action apiAction, Playlist playlist, String videoId) {
Context _mContext = getApplication().getApplicationContext();
new Thread(() -> {
try {
String token = Helper.getToken(_mContext);
SQLiteDatabase db = Sqlite.getInstance(_mContext.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Account account = new AccountDAO(_mContext, db).getAccountByToken(token);
BaseAccount account = new Account(_mContext).getAccountByToken(token);
int statusCode = -1;
APIResponse apiResponse;
if (account == null) {
@ -106,7 +83,7 @@ public class PlaylistsVM extends AndroidViewModel {
apiResponse = new APIResponse();
apiResponse.setPlaylists(new ArrayList<>());
} else {
apiResponse = new RetrofitPeertubeAPI(_mContext).playlistAction(apiAction, playlist != null ? playlist.getId() : null, videoId, account.getAcct(), null);
apiResponse = new RetrofitPeertubeAPI(_mContext).playlistAction(apiAction, playlist != null ? playlist.getId() : null, videoId, account.peertube_account.getAcct(), null);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
if (apiResponse != null) {

View File

@ -18,7 +18,6 @@ import static app.fedilab.android.peertube.viewmodel.PlaylistsVM.action.GET_LIST
import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Looper;
@ -27,18 +26,12 @@ import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import java.util.ArrayList;
import java.util.List;
import app.fedilab.android.peertube.client.APIResponse;
import app.fedilab.android.peertube.client.RetrofitPeertubeAPI;
import app.fedilab.android.peertube.client.data.AccountData;
import app.fedilab.android.peertube.client.data.ChannelData;
import app.fedilab.android.peertube.client.data.VideoData;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.helper.HelperInstance;
import app.fedilab.android.peertube.sqlite.ManagePlaylistsDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
public class TimelineVM extends AndroidViewModel {
@ -48,7 +41,7 @@ public class TimelineVM extends AndroidViewModel {
super(application);
}
public LiveData<APIResponse> getVideos(TimelineType action, String max_id, ChannelData.Channel forChannel, AccountData.Account forAccount) {
public LiveData<APIResponse> getVideos(TimelineType action, String max_id, ChannelData.Channel forChannel, AccountData.PeertubeAccount forAccount) {
apiResponseMutableLiveData = new MutableLiveData<>();
loadVideos(action, max_id, forChannel, forAccount);
return apiResponseMutableLiveData;
@ -85,12 +78,6 @@ public class TimelineVM extends AndroidViewModel {
return apiResponseMutableLiveData;
}
public LiveData<APIResponse> loadVideosInLocalPlaylist(String playlistUuid) {
apiResponseMutableLiveData = new MutableLiveData<>();
loadVideosInLocalPlayList(playlistUuid);
return apiResponseMutableLiveData;
}
public LiveData<APIResponse> getMyVideo(String instance, String videoId) {
apiResponseMutableLiveData = new MutableLiveData<>();
getSingle(instance, videoId, true);
@ -168,28 +155,8 @@ public class TimelineVM extends AndroidViewModel {
}).start();
}
private void loadVideosInLocalPlayList(String playlistUuid) {
Context _mContext = getApplication().getApplicationContext();
new Thread(() -> {
try {
SQLiteDatabase db = Sqlite.getInstance(_mContext.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<VideoData.VideoExport> videoExports = new ManagePlaylistsDAO(_mContext, db).getAllVideosInPlaylist(playlistUuid);
APIResponse apiResponse = new APIResponse();
List<VideoData.Video> videos = new ArrayList<>();
for (VideoData.VideoExport videoExport : videoExports) {
videos.add(videoExport.getVideoData());
}
apiResponse.setPeertubes(videos);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> apiResponseMutableLiveData.setValue(apiResponse);
mainHandler.post(myRunnable);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
private void loadVideos(TimelineType timeline, String max_id, ChannelData.Channel forChannel, AccountData.Account forAccount) {
private void loadVideos(TimelineType timeline, String max_id, ChannelData.Channel forChannel, AccountData.PeertubeAccount forAccount) {
Context _mContext = getApplication().getApplicationContext();
new Thread(() -> {
try {

View File

@ -22,7 +22,6 @@ import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
@ -42,6 +41,8 @@ import java.util.List;
import java.util.concurrent.ExecutionException;
import app.fedilab.android.R;
import app.fedilab.android.mastodon.client.entities.app.Account;
import app.fedilab.android.mastodon.client.entities.app.BaseAccount;
import app.fedilab.android.peertube.activities.PeertubeActivity;
import app.fedilab.android.peertube.activities.PeertubeMainActivity;
import app.fedilab.android.peertube.activities.ShowAccountActivity;
@ -56,8 +57,6 @@ import app.fedilab.android.peertube.client.entities.UserMe;
import app.fedilab.android.peertube.fragment.DisplayNotificationsFragment;
import app.fedilab.android.peertube.helper.Helper;
import app.fedilab.android.peertube.helper.NotificationHelper;
import app.fedilab.android.peertube.sqlite.AccountDAO;
import app.fedilab.android.peertube.sqlite.Sqlite;
public class NotificationsWorker extends Worker {
@ -78,8 +77,7 @@ public class NotificationsWorker extends Worker {
@Override
public Result doWork() {
Context applicationContext = getApplicationContext();
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<AccountData.Account> accounts = new AccountDAO(applicationContext, db).getAllPeertubeAccount();
List<BaseAccount> accounts = new Account(applicationContext).getPeertubeAccounts();
if (accounts == null || accounts.size() == 0) {
return Result.success();
}
@ -91,12 +89,11 @@ public class NotificationsWorker extends Worker {
@SuppressWarnings({"SwitchStatementWithoutDefaultBranch", "DuplicateBranchesInSwitch"})
private void fetchNotification() {
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<AccountData.Account> accounts = new AccountDAO(getApplicationContext(), db).getAllPeertubeAccount();
List<BaseAccount> accounts = new Account(getApplicationContext()).getPeertubeAccounts();
SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
for (AccountData.Account account : accounts) {
RetrofitPeertubeAPI retrofitPeertubeAPI = new RetrofitPeertubeAPI(getApplicationContext(), account.getHost(), account.getToken());
for (BaseAccount account : accounts) {
RetrofitPeertubeAPI retrofitPeertubeAPI = new RetrofitPeertubeAPI(getApplicationContext(), account.instance, account.token);
APIResponse apiResponse = retrofitPeertubeAPI.getNotifications();
if (apiResponse == null) {
return;
@ -107,8 +104,8 @@ public class NotificationsWorker extends Worker {
List<NotificationData.Notification> notifications = apiResponse.getPeertubeNotifications();
NotificationSettings notificationSettings = userMe.getNotificationSettings();
if (apiResponse.getPeertubeNotifications() != null && apiResponse.getPeertubeNotifications().size() > 0) {
String last_read = sharedpreferences.getString(Helper.LAST_NOTIFICATION_READ + account.getId() + account.getHost(), null);
editor.putString(Helper.LAST_NOTIFICATION_READ + account.getId() + account.getHost(), apiResponse.getPeertubeNotifications().get(0).getId());
String last_read = sharedpreferences.getString(Helper.LAST_NOTIFICATION_READ + account.user_id + account.instance, null);
editor.putString(Helper.LAST_NOTIFICATION_READ + account.user_id + account.instance, apiResponse.getPeertubeNotifications().get(0).getId());
editor.apply();
if (last_read != null) {
for (NotificationData.Notification notification : notifications) {
@ -116,7 +113,7 @@ public class NotificationsWorker extends Worker {
String message = "";
FutureTarget<Bitmap> futureBitmap = Glide.with(getApplicationContext())
.asBitmap()
.load("https://" + account.getHost() + account.getAvatar()).submit();
.load("https://" + account.instance + account.peertube_account.getAvatar()).submit();
Bitmap icon;
try {
icon = futureBitmap.get();
@ -133,7 +130,7 @@ public class NotificationsWorker extends Worker {
if (notification.getVideo().getChannel().getAvatar() != null) {
FutureTarget<Bitmap> futureBitmapChannel = Glide.with(getApplicationContext())
.asBitmap()
.load("https://" + account.getHost() + notification.getVideo().getChannel().getAvatar().getPath()).submit();
.load("https://" + account.instance + notification.getVideo().getChannel().getAvatar().getPath()).submit();
try {
icon = futureBitmapChannel.get();
} catch (Exception e) {
@ -149,7 +146,7 @@ public class NotificationsWorker extends Worker {
message = getApplicationContext().getString(R.string.peertube_video_from_subscription, notification.getVideo().getChannel().getDisplayName(), notification.getVideo().getName());
intent = new Intent(getApplicationContext(), PeertubeActivity.class);
Bundle b = new Bundle();
b.putParcelable("video", notification.getVideo());
b.putSerializable("video", notification.getVideo());
b.putString("peertube_instance", notification.getVideo().getChannel().getHost());
b.putBoolean("isMyVideo", false);
b.putString("video_id", notification.getVideo().getId());
@ -162,7 +159,7 @@ public class NotificationsWorker extends Worker {
if (notification.getComment().getAccount().getAvatar() != null) {
FutureTarget<Bitmap> futureBitmapChannel = Glide.with(getApplicationContext())
.asBitmap()
.load("https://" + account.getHost() + notification.getComment().getAccount().getAvatar().getPath()).submit();
.load("https://" + account.instance + notification.getComment().getAccount().getAvatar().getPath()).submit();
try {
icon = futureBitmapChannel.get();
} catch (Exception e) {
@ -178,7 +175,7 @@ public class NotificationsWorker extends Worker {
message = getApplicationContext().getString(R.string.peertube_comment_on_video, notification.getComment().getAccount().getDisplayName(), notification.getComment().getAccount().getUsername());
intent = new Intent(getApplicationContext(), PeertubeActivity.class);
Bundle b = new Bundle();
b.putParcelable("video", notification.getVideo());
b.putSerializable("video", notification.getVideo());
b.putString("peertube_instance", notification.getVideo().getChannel().getHost());
b.putBoolean("isMyVideo", false);
b.putString("video_id", notification.getVideo().getId());
@ -228,7 +225,7 @@ public class NotificationsWorker extends Worker {
if (notification.getVideo().getChannel().getAvatar() != null) {
FutureTarget<Bitmap> futureBitmapChannel = Glide.with(getApplicationContext())
.asBitmap()
.load("https://" + account.getHost() + notification.getVideo().getChannel().getAvatar().getPath()).submit();
.load("https://" + account.instance + notification.getVideo().getChannel().getAvatar().getPath()).submit();
icon = futureBitmapChannel.get();
} else {
@ -244,13 +241,13 @@ public class NotificationsWorker extends Worker {
}
Bundle b = new Bundle();
Actor actor = notification.getActorFollow().getFollower();
AccountData.Account accountAction = new AccountData.Account();
AccountData.PeertubeAccount accountAction = new AccountData.PeertubeAccount();
accountAction.setAvatar(actor.getAvatar());
accountAction.setDisplayName(actor.getDisplayName());
accountAction.setHost(actor.getHost());
accountAction.setUsername(actor.getName());
intent = new Intent(getApplicationContext(), ShowAccountActivity.class);
b.putParcelable("account", accountAction);
b.putSerializable("account", accountAction);
b.putString("accountAcct", accountAction.getUsername() + "@" + accountAction.getHost());
intent.putExtras(b);
}
@ -279,7 +276,7 @@ public class NotificationsWorker extends Worker {
message = Html.fromHtml(message, Html.FROM_HTML_MODE_LEGACY).toString();
else
message = Html.fromHtml(message).toString();
NotificationHelper.notify_user(getApplicationContext(), account, intent, icon, title, message);
NotificationHelper.notify_user(getApplicationContext(), account.peertube_account, intent, icon, title, message);
}
} else {
break;

View File

@ -23,7 +23,7 @@ import android.database.sqlite.SQLiteOpenHelper;
public class Sqlite extends SQLiteOpenHelper {
public static final int DB_VERSION = 8;
public static final int DB_VERSION = 9;
public static final String DB_NAME = "fedilab_db";
//Table of owned accounts
@ -88,6 +88,11 @@ public class Sqlite extends SQLiteOpenHelper {
public static final String TABLE_MUTED = "TABLE_MUTED";
public static final String COL_MUTED_ACCOUNTS = "MUTED_ACCOUNTS";
//Peertube bookmarked instances
public static final String TABLE_BOOKMARKED_INSTANCES = "BOOKMARKED_INSTANCES";
public static final String COL_ABOUT = "ABOUT";
public static final String COL_USER_INSTANCE = "USER_INSTANCE";
private static final String CREATE_TABLE_USER_ACCOUNT = "CREATE TABLE " + TABLE_USER_ACCOUNT + " ("
+ COL_USER_ID + " TEXT NOT NULL, "
+ COL_INSTANCE + " TEXT NOT NULL, "
@ -188,6 +193,14 @@ public class Sqlite extends SQLiteOpenHelper {
+ COL_TYPE + " TEXT NOT NULL, "
+ COL_MUTED_ACCOUNTS + " TEXT)";
private final String CREATE_TABLE_STORED_INSTANCES = "CREATE TABLE "
+ TABLE_BOOKMARKED_INSTANCES + "("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_INSTANCE + " TEXT NOT NULL, "
+ COL_USER_ID + " TEXT NOT NULL, "
+ COL_ABOUT + " TEXT NOT NULL, "
+ COL_USER_INSTANCE + " TEXT NOT NULL)";
public static SQLiteDatabase db;
private static Sqlite sInstance;
@ -217,6 +230,7 @@ public class Sqlite extends SQLiteOpenHelper {
db.execSQL(CREATE_TABLE_BOTTOM_MENU);
db.execSQL(CREATE_DOMAINS_TRACKING);
db.execSQL(CREATE_TABLE_MUTED);
db.execSQL(CREATE_TABLE_STORED_INSTANCES);
}
@Override
@ -243,6 +257,8 @@ public class Sqlite extends SQLiteOpenHelper {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DOMAINS_TRACKING);
case 7:
db.execSQL(CREATE_TABLE_MUTED);
case 8:
db.execSQL(CREATE_TABLE_STORED_INSTANCES);
default:
break;
}

View File

@ -64,6 +64,7 @@ import app.fedilab.android.mastodon.helper.ZipHelper;
import app.fedilab.android.mastodon.viewmodel.mastodon.AppsVM;
import app.fedilab.android.mastodon.viewmodel.mastodon.InstanceSocialVM;
import app.fedilab.android.mastodon.viewmodel.mastodon.NodeInfoVM;
import app.fedilab.android.peertube.activities.LoginActivity;
import es.dmoral.toasty.Toasty;
public class FragmentLoginMain extends Fragment {
@ -162,7 +163,8 @@ public class FragmentLoginMain extends Fragment {
}
binding.continueButton.setEnabled(false);
NodeInfoVM nodeInfoVM = new ViewModelProvider(requireActivity()).get(NodeInfoVM.class);
nodeInfoVM.getNodeInfo(binding.loginInstance.getText().toString()).observe(requireActivity(), nodeInfo -> {
String instance = binding.loginInstance.getText().toString();
nodeInfoVM.getNodeInfo(instance).observe(requireActivity(), nodeInfo -> {
if (nodeInfo != null) {
BaseMainActivity.software = nodeInfo.software.name.toUpperCase();
switch (nodeInfo.software.name.toUpperCase().trim()) {
@ -179,6 +181,9 @@ public class FragmentLoginMain extends Fragment {
case "PLEROMA":
apiLogin = Account.API.PLEROMA;
break;
case "PEERTUBE":
apiLogin = Account.API.PEERTUBE;
break;
default:
apiLogin = Account.API.UNKNOWN;
break;
@ -190,7 +195,14 @@ public class FragmentLoginMain extends Fragment {
}
binding.continueButton.setEnabled(true);
retrievesClientId(currentInstanceLogin);
if (apiLogin != Account.API.PEERTUBE) {
retrievesClientId(currentInstanceLogin);
} else {
Intent peertubeLogin = new Intent(requireActivity(), LoginActivity.class);
peertubeLogin.putExtra(Helper.ARG_INSTANCE, instance);
startActivity(peertubeLogin);
requireActivity().finish();
}
});
});
return root;

View File

@ -64,7 +64,6 @@
android:id="@+id/login_instance_container"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
@ -73,6 +72,7 @@
android:id="@+id/login_instance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:hint="@string/title_instance_login"
android:importantForAutofill="no"
android:inputType="textWebEmailAddress"

View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:key="app_prefs">
@ -58,11 +59,7 @@
</PreferenceCategory>
<PreferenceCategory android:title="@string/app_interface">
<androidx.preference.ListPreference
android:icon="@drawable/ic_baseline_color_lens_24"
android:key="@string/set_theme_choice"
android:summary="@string/set_theme_description"
android:title="@string/set_theme" />
<androidx.preference.ListPreference
android:icon="@drawable/ic_baseline_blur_on_24"
android:key="@string/set_video_sensitive_choice"
@ -83,4 +80,40 @@
android:summary="@string/set_cast_description"
android:title="@string/set_cast" />
</PreferenceCategory>
<PreferenceCategory android:title="@string/theming">
<ListPreference
app:defaultValue="SYSTEM"
app:dialogTitle="@string/type_of_theme"
app:entries="@array/set_theme_mode_value"
app:entryValues="@array/SET_THEME_MODE_VALUE"
app:key="@string/SET_THEME_BASE"
app:title="@string/type_of_theme"
app:useSimpleSummaryProvider="true" />
<SwitchPreferenceCompat
app:defaultValue="false"
app:key="@string/SET_DYNAMICCOLOR"
app:singleLineTitle="false"
app:summary="@string/set_dynamic_color_indication"
app:title="@string/set_dynamic_color" />
<ListPreference
app:defaultValue="LIGHT"
app:dialogTitle="@string/type_default_theme_light"
app:entries="@array/set_default_theme_light"
app:entryValues="@array/SET_DEFAULT_THEME_LIGHT"
app:key="@string/SET_THEME_DEFAULT_LIGHT"
app:title="@string/type_default_theme_light"
app:useSimpleSummaryProvider="true" />
<ListPreference
app:defaultValue="DARK"
app:dialogTitle="@string/type_default_theme_dark"
app:entries="@array/set_default_theme_dark"
app:entryValues="@array/SET_THEME_DEFAULT_DARK"
app:key="@string/SET_THEME_DEFAULT_DARK"
app:title="@string/type_default_theme_dark"
app:useSimpleSummaryProvider="true" />
</PreferenceCategory>
</androidx.preference.PreferenceScreen>