1
0
mirror of https://framagit.org/tom79/fedilab-tube synced 2025-06-05 21:09:11 +02:00

40 Commits

Author SHA1 Message Date
327f6f0e8d Release notes 2021-01-03 16:06:15 +01:00
d6f1a360d2 Release notes 2021-01-03 16:05:47 +01:00
24ec69d7f7 Merge branch 'l10n_develop' into 'develop'
New Crowdin updates

See merge request tom79/fedilab-tube!61
2021-01-03 16:01:01 +01:00
c80692bd34 New Crowdin updates 2021-01-03 16:01:00 +01:00
b5e9f70be6 Allow to reblog/unreblog, favourite/unfavourite, bookmark/unbookmark videos from mastodon/pleroma Accounts 2021-01-03 12:10:34 +01:00
d446081331 Small fix 2021-01-03 10:02:11 +01:00
8178cff72c Small fix 2021-01-02 18:28:13 +01:00
950d99b5de Prevent to check notifications for remote accounts 2021-01-02 18:20:36 +01:00
b7855cb1a2 Working post comments from Mastodon/Pleroma 2021-01-02 18:09:09 +01:00
b298fbfa3e Some changes 2021-01-02 13:38:58 +01:00
d83929f80a Some changes 2021-01-02 11:21:30 +01:00
b932ed2c13 Some fixes 2020-12-31 15:32:38 +01:00
36073d340d Allow connection with Mastodon & Pleroma accounts 2020-12-31 14:19:26 +01:00
0e14540b69 Allow connection of Mastodon & Pleroma accounts 2020-12-31 11:19:43 +01:00
57327a8ad0 Check rights 2020-12-30 16:20:49 +01:00
bbfa278d6b Implement logic 2020-12-30 15:37:09 +01:00
439decf6a9 Merge remote-tracking branch 'origin/develop' into develop 2020-12-30 12:21:49 +01:00
2277cc5f05 Some changes 2020-12-30 12:21:40 +01:00
4204ffccee Merge branch 'l10n_develop' into 'develop'
New Crowdin updates

See merge request tom79/fedilab-tube!60
2020-12-30 10:11:25 +01:00
31407e709d New Crowdin updates 2020-12-30 10:11:25 +01:00
44d26bb1cf Merge remote-tracking branch 'origin/develop' into develop 2020-12-29 17:11:56 +01:00
8a8a433023 Some changes 2020-12-29 17:11:36 +01:00
5c27292543 Fix #138 #155 2020-12-29 16:53:02 +01:00
e475348d39 Some fixes 2020-12-29 09:55:15 +01:00
9f8358e471 Merge branch 'l10n_develop' into 'develop'
New Crowdin updates

See merge request tom79/fedilab-tube!59
2020-12-28 17:36:02 +01:00
4fd8d42d85 Some fixes 2020-12-28 15:43:59 +01:00
498990c48a New translations strings.xml (French) 2020-12-28 15:43:37 +01:00
1cddf26c9a Some fixes 2020-12-28 15:39:18 +01:00
325a239b86 clean 2020-12-26 17:34:30 +01:00
2c4ef9c3ce New translations strings.xml (Russian) 2020-12-25 20:06:50 +01:00
4dbd191c4f Merge branch 'l10n_develop' into 'develop'
New Crowdin updates

See merge request tom79/fedilab-tube!58
2020-12-25 10:33:12 +01:00
01e489da10 New Crowdin updates 2020-12-25 10:33:12 +01:00
53a7062c6d clean 2020-12-24 17:10:16 +01:00
3425e1e593 Merge remote-tracking branch 'origin/develop' into develop 2020-12-24 16:40:35 +01:00
9970635ff8 Fix issue #154 2020-12-24 16:40:18 +01:00
c1f174a5b8 Merge branch 'l10n_develop' into 'develop'
New Crowdin updates

See merge request tom79/fedilab-tube!57
2020-12-24 15:32:59 +01:00
3587e7c524 New Crowdin updates 2020-12-24 15:32:59 +01:00
3911ad15a6 fix name 2020-12-24 12:01:59 +01:00
d40b35da59 Fix issue #158 2020-12-24 11:57:27 +01:00
ccb6e184cc Fix issue #151 2020-12-24 11:42:06 +01:00
86 changed files with 4491 additions and 285 deletions

17
.github/stale.yml vendored Normal file
View File

@ -0,0 +1,17 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 60
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- pinned
- security
# Label to use when marking an issue as stale
staleLabel: inactive
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

View File

@ -9,8 +9,8 @@ android {
minSdkVersion 21
targetSdkVersion 30
versionCode 33
versionName "1.10.2"
versionCode 34
versionName "1.11.0"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
@ -50,6 +50,7 @@ android {
buildConfigField "boolean", "surfing_mode", "false"
buildConfigField "boolean", "sepia_search", "false"
buildConfigField "boolean", "instance_switcher", "true"
buildConfigField "boolean", "allow_remote_connections", "false"
}
google_peertube_apps_educ {
applicationId "app.fedilab.fedilabtube"
@ -61,6 +62,7 @@ android {
buildConfigField "boolean", "surfing_mode", "false"
buildConfigField "boolean", "sepia_search", "false"
buildConfigField "boolean", "instance_switcher", "true"
buildConfigField "boolean", "allow_remote_connections", "false"
}
fdroid_full {
applicationId "app.fedilab.tubelab"
@ -72,6 +74,7 @@ android {
buildConfigField "boolean", "surfing_mode", "true"
buildConfigField "boolean", "sepia_search", "true"
buildConfigField "boolean", "instance_switcher", "true"
buildConfigField "boolean", "allow_remote_connections", "true"
}
google_full {
applicationId "app.fedilab.tubelab"
@ -83,6 +86,7 @@ android {
buildConfigField "boolean", "surfing_mode", "true"
buildConfigField "boolean", "sepia_search", "true"
buildConfigField "boolean", "instance_switcher", "true"
buildConfigField "boolean", "allow_remote_connections", "true"
}
queermotion {
applicationId "org.queermotion.peertube"
@ -94,6 +98,7 @@ android {
buildConfigField "boolean", "surfing_mode", "false"
buildConfigField "boolean", "sepia_search", "false"
buildConfigField "boolean", "instance_switcher", "false"
buildConfigField "boolean", "allow_remote_connections", "false"
}
bittube {
applicationId "app.fedilab.bittube"
@ -105,7 +110,7 @@ android {
buildConfigField "boolean", "surfing_mode", "false"
buildConfigField "boolean", "sepia_search", "false"
buildConfigField "boolean", "instance_switcher", "true"
buildConfigField "boolean", "allow_remote_connections", "false"
}
}
@ -160,14 +165,15 @@ dependencies {
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.browser:browser:1.3.0'
implementation 'androidx.documentfile:documentfile:1.0.1'
implementation project(path: ':torrentStream')
testImplementation 'junit:junit:4.13.1'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
implementation 'com.github.GrenderG:Toasty:1.4.2'
implementation 'com.google.android.exoplayer:exoplayer:2.12.1'
implementation 'com.google.android.exoplayer:extension-mediasession:2.12.1'
implementation 'com.google.android.exoplayer:exoplayer:2.12.2'
implementation 'com.google.android.exoplayer:extension-mediasession:2.12.2'
implementation "com.github.mabbas007:TagsEditText:1.0.5"
implementation "com.github.bumptech.glide:glide:4.11.0"
annotationProcessor "com.github.bumptech.glide:compiler:4.11.0"
@ -181,7 +187,6 @@ dependencies {
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.github.mancj:MaterialSearchBar:0.8.5'
implementation "com.github.TorrentStream:TorrentStream-Android:2.7.0"
implementation "io.github.kobakei:ratethisapp:1.2.0"
implementation 'com.github.vkay94:DoubleTapPlayerView:1.0.0'

View File

@ -7,6 +7,8 @@
<color name="tag_color">#bbF2690D</color>
<color name="tag_color_text">#FAFAFA</color>
<color name="positive_thumbs">#2b90d9</color>
<color name="favorite">#ca8f04</color>
<color name="bookmark">#795548</color>
<color name="negative_thumbs">#F44336</color>
<color name="backgroundDark">#DD000000</color>
<color name="red_1">#F44336</color>

View File

@ -7,6 +7,8 @@
<color name="tag_color">#bbF2690D</color>
<color name="tag_color_text">#FAFAFA</color>
<color name="positive_thumbs">#2b90d9</color>
<color name="favorite">#ca8f04</color>
<color name="bookmark">#795548</color>
<color name="negative_thumbs">#F44336</color>
<color name="backgroundDark">#DD000000</color>
<color name="red_1">#F44336</color>

View File

@ -7,6 +7,8 @@
<color name="tag_color_text">#FAFAFA</color>
<color name="positive_thumbs">#2b90d9</color>
<color name="negative_thumbs">#F44336</color>
<color name="favorite">#ca8f04</color>
<color name="bookmark">#795548</color>
<color name="backgroundDark">#DD000000</color>
<color name="red_1">#F44336</color>
<color name="gray_light">#80808080</color>

View File

@ -10,7 +10,9 @@
-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
@ -127,11 +129,26 @@
android:name=".WebviewConnectActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name" />
<activity
android:name=".MastodonWebviewConnectActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name" />
<activity
android:name=".LoginActivity"
android:configChanges="orientation|screenSize"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysHidden" />
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="backtotubelab"
android:scheme="tubelab" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity"

View File

@ -17,16 +17,16 @@ package app.fedilab.fedilabtube;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.View;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
@ -37,13 +37,13 @@ import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import org.jetbrains.annotations.NotNull;
import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.data.AccountData.Account;
import app.fedilab.fedilabtube.databinding.ActivityAccountBinding;
import app.fedilab.fedilabtube.fragment.DisplayAccountsFragment;
import app.fedilab.fedilabtube.fragment.DisplayChannelsFragment;
import app.fedilab.fedilabtube.fragment.DisplayNotificationsFragment;
@ -56,15 +56,14 @@ import app.fedilab.fedilabtube.sqlite.Sqlite;
public class AccountActivity extends AppCompatActivity {
private ViewPager mPager;
private TabLayout tabLayout;
private ActivityAccountBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
binding = ActivityAccountBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
@ -75,34 +74,27 @@ public class AccountActivity extends AppCompatActivity {
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
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);
TextView instanceView = findViewById(R.id.instance);
Account account = new AccountDAO(AccountActivity.this, db).getAccountByToken(token);
if (account == null) {
Helper.logoutCurrentUser(AccountActivity.this, null);
return;
}
ImageView profile_picture = findViewById(R.id.profile_picture);
TextView username = findViewById(R.id.username);
TextView displayname = findViewById(R.id.displayname);
setTitle(String.format("@%s", account.getUsername()));
Helper.loadGiF(AccountActivity.this, account.getAvatar().getPath(), profile_picture);
username.setText(String.format("@%s", account.getUsername()));
displayname.setText(account.getDisplayName());
Helper.loadGiF(AccountActivity.this, account.getAvatar().getPath(), binding.profilePicture);
binding.username.setText(String.format("@%s", account.getUsername()));
binding.displayname.setText(account.getDisplayName());
instanceView.setText(account.getHost());
FloatingActionButton edit_profile = findViewById(R.id.edit_profile);
edit_profile.setOnClickListener(v -> startActivity(new Intent(AccountActivity.this, MyAccountActivity.class)));
binding.instance.setText(account.getHost());
binding.editProfile.setOnClickListener(v -> startActivity(new Intent(AccountActivity.this, MyAccountActivity.class)));
Button logout_button = findViewById(R.id.logout_button);
logout_button.setOnClickListener(v -> {
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) -> {
@ -114,84 +106,93 @@ public class AccountActivity extends AppCompatActivity {
alertDialogLogoutAccount.show();
});
Button settings = findViewById(R.id.settings);
settings.setOnClickListener(v -> {
binding.settings.setOnClickListener(v -> {
Intent intent = new Intent(AccountActivity.this, SettingsActivity.class);
startActivity(intent);
});
tabLayout = findViewById(R.id.account_tabLayout);
mPager = findViewById(R.id.account_viewpager);
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_notifications)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_muted)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_channel)));
mPager.setOffscreenPageLimit(3);
if (Helper.isLoggedIn(AccountActivity.this)) {
binding.accountTabLayout.addTab(binding.accountTabLayout.newTab().setText(getString(R.string.title_notifications)));
binding.accountTabLayout.addTab(binding.accountTabLayout.newTab().setText(getString(R.string.title_muted)));
binding.accountTabLayout.addTab(binding.accountTabLayout.newTab().setText(getString(R.string.title_channel)));
binding.accountViewpager.setOffscreenPageLimit(3);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
binding.accountViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
TabLayout.Tab tab = tabLayout.getTabAt(position);
if (tab != null)
tab.select();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
mPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
Fragment fragment = null;
if (mPager.getAdapter() != null)
fragment = (Fragment) mPager.getAdapter().instantiateItem(mPager, tab.getPosition());
switch (tab.getPosition()) {
case 0:
if (fragment != null) {
DisplayNotificationsFragment displayNotificationsFragment = ((DisplayNotificationsFragment) fragment);
displayNotificationsFragment.scrollToTop();
}
break;
case 1:
if (fragment != null) {
DisplayAccountsFragment displayAccountsFragment = ((DisplayAccountsFragment) fragment);
displayAccountsFragment.scrollToTop();
}
break;
case 2:
if (fragment != null) {
DisplayChannelsFragment displayChannelsFragment = ((DisplayChannelsFragment) fragment);
displayChannelsFragment.scrollToTop();
}
break;
}
}
});
PagerAdapter mPagerAdapter = new AccountsPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
@Override
public void onPageSelected(int position) {
TabLayout.Tab tab = binding.accountTabLayout.getTabAt(position);
if (tab != null)
tab.select();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
binding.accountTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
binding.accountViewpager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
Fragment fragment = null;
if (binding.accountViewpager.getAdapter() != null)
fragment = (Fragment) binding.accountViewpager.getAdapter().instantiateItem(binding.accountViewpager, tab.getPosition());
switch (tab.getPosition()) {
case 0:
if (fragment != null) {
DisplayNotificationsFragment displayNotificationsFragment = ((DisplayNotificationsFragment) fragment);
displayNotificationsFragment.scrollToTop();
}
break;
case 1:
if (fragment != null) {
DisplayAccountsFragment displayAccountsFragment = ((DisplayAccountsFragment) fragment);
displayAccountsFragment.scrollToTop();
}
break;
case 2:
if (fragment != null) {
DisplayChannelsFragment displayChannelsFragment = ((DisplayChannelsFragment) fragment);
displayChannelsFragment.scrollToTop();
}
break;
}
}
});
PagerAdapter mPagerAdapter = new AccountsPagerAdapter(getSupportFragmentManager());
binding.accountViewpager.setAdapter(mPagerAdapter);
} else {
binding.accountTabLayout.setVisibility(View.GONE);
binding.accountViewpager.setVisibility(View.GONE);
binding.editProfile.setVisibility(View.GONE);
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));
else
binding.remoteAccount.setText(Html.fromHtml(getString(R.string.remote_account_from, account.getSoftware())));
}
}
@Override

View File

@ -41,11 +41,13 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import app.fedilab.fedilabtube.client.mastodon.RetrofitMastodonAPI;
import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.entities.Error;
import app.fedilab.fedilabtube.client.entities.Oauth;
import app.fedilab.fedilabtube.client.entities.OauthParams;
import app.fedilab.fedilabtube.client.entities.Token;
import app.fedilab.fedilabtube.client.entities.WellKnownNodeinfo;
import app.fedilab.fedilabtube.databinding.ActivityLoginBinding;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.helper.HelperAcadInstance;
@ -117,7 +119,6 @@ public class LoginActivity extends AppCompatActivity {
binding.loginPasswdContainer.setLayoutParams(layoutParamsP);
}
if (!BuildConfig.full_instances) {
binding.loginUid.setOnFocusChangeListener((v, hasFocus) -> {
if (!hasFocus) {
@ -169,7 +170,27 @@ public class LoginActivity extends AppCompatActivity {
}
});
}
if (BuildConfig.allow_remote_connections) {
binding.loginInstance.setOnFocusChangeListener((v, hasFocus) -> {
if (!hasFocus) {
if (binding.loginInstance.getText() != null) {
new Thread(() -> {
String testInstance = binding.loginInstance.getText().toString();
WellKnownNodeinfo.NodeInfo instanceNodeInfo = null;
if (BuildConfig.allow_remote_connections) {
instanceNodeInfo = new RetrofitPeertubeAPI(LoginActivity.this, testInstance, null).getNodeInfo();
}
if (instanceNodeInfo != null &&
(instanceNodeInfo.getSoftware().getName().toUpperCase().trim().compareTo("MASTODON") == 0 ||
instanceNodeInfo.getSoftware().getName().toUpperCase().trim().compareTo("PLEROMA") == 0)
) {
connectToFediverse(testInstance, instanceNodeInfo);
}
}).start();
}
}
});
}
binding.loginButton.setOnClickListener(v -> {
if (!BuildConfig.full_instances) {
@ -211,7 +232,7 @@ public class LoginActivity extends AppCompatActivity {
return;
}
binding.loginButton.setEnabled(false);
String instance, host;
String instance;
if (!BuildConfig.full_instances) {
String[] emailArray = binding.loginUid.getText().toString().split("@");
if (emailArray.length > 1 && !Arrays.asList(HelperAcadInstance.valideEmails).contains(emailArray[1])) {
@ -221,21 +242,19 @@ public class LoginActivity extends AppCompatActivity {
}
instance = HelperInstance.getLiveInstance(LoginActivity.this);
host = instance;
} else {
if (binding.loginInstance.getText() == null || binding.loginInstance.getText().toString().trim().length() == 0) {
Toasty.error(LoginActivity.this, getString(R.string.not_valide_instance)).show();
binding.loginButton.setEnabled(true);
return;
}
instance = host = binding.loginInstance.getText().toString().trim().toLowerCase();
instance = binding.loginInstance.getText().toString().trim().toLowerCase();
}
if (instance.startsWith("http")) {
try {
URL url = new URL(instance);
instance = url.getHost();
host = instance;
} catch (MalformedURLException e) {
e.printStackTrace();
}
@ -243,7 +262,6 @@ public class LoginActivity extends AppCompatActivity {
try {
URL url = new URL("https://" + instance);
instance = url.getHost();
host = instance;
} catch (MalformedURLException e) {
e.printStackTrace();
}
@ -254,66 +272,123 @@ public class LoginActivity extends AppCompatActivity {
return;
}
String finalInstance = instance;
String finalHost = host;
if (BuildConfig.full_instances) {
new Thread(() -> {
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);
Toasty.error(LoginActivity.this, getString(R.string.client_error), Toast.LENGTH_LONG).show();
});
return;
}
client_id = oauth.getClient_id();
client_secret = oauth.getClient_secret();
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.CLIENT_ID, client_id);
editor.putString(Helper.CLIENT_SECRET, client_secret);
editor.apply();
OauthParams oauthParams = new OauthParams();
oauthParams.setClient_id(client_id);
oauthParams.setClient_secret(client_secret);
oauthParams.setGrant_type("password");
oauthParams.setScope("user");
oauthParams.setUsername(binding.loginUid.getText().toString().trim());
if (binding.loginPasswd.getText() != null) {
oauthParams.setPassword(binding.loginPasswd.getText().toString());
}
try {
Token token = new RetrofitPeertubeAPI(LoginActivity.this, finalInstance, null).manageToken(oauthParams);
proceedLogin(token, finalHost);
} catch (final Exception | Error e) {
oauthParams.setUsername(binding.loginUid.getText().toString().toLowerCase().trim());
try {
Token token = new RetrofitPeertubeAPI(LoginActivity.this, finalInstance, null).manageToken(oauthParams);
proceedLogin(token, finalHost);
} catch (Error error) {
Error.displayError(LoginActivity.this, error);
error.printStackTrace();
runOnUiThread(() -> binding.loginButton.setEnabled(true));
}
WellKnownNodeinfo.NodeInfo instanceNodeInfo = null;
if (BuildConfig.allow_remote_connections) {
instanceNodeInfo = new RetrofitPeertubeAPI(LoginActivity.this, finalInstance, null).getNodeInfo();
}
connectToFediverse(finalInstance, instanceNodeInfo);
}).start();
}
}
});
}
/**
* Oauth process for Peertube
*
* @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";
}
if (oauth == null) {
runOnUiThread(() -> {
binding.loginButton.setEnabled(true);
Toasty.error(LoginActivity.this, getString(R.string.client_error), Toast.LENGTH_LONG).show();
});
return;
}
client_id = oauth.getClient_id();
client_secret = oauth.getClient_secret();
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.CLIENT_ID, client_id);
editor.putString(Helper.CLIENT_SECRET, client_secret);
editor.apply();
OauthParams oauthParams = new OauthParams();
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");
}
if (binding.loginUid.getText() != null) {
oauthParams.setUsername(binding.loginUid.getText().toString().trim());
}
if (binding.loginPasswd.getText() != null) {
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);
} catch (final Exception | Error e) {
oauthParams.setUsername(binding.loginUid.getText().toString().toLowerCase().trim());
try {
if (software.compareTo("PEERTUBE") == 0) {
Token token = new RetrofitPeertubeAPI(LoginActivity.this, finalInstance, null).manageToken(oauthParams);
proceedLogin(token, finalInstance, software.compareTo("PEERTUBE") == 0 ? null : software);
}
} catch (Error error) {
Error.displayError(LoginActivity.this, error);
error.printStackTrace();
runOnUiThread(() -> binding.loginButton.setEnabled(true));
}
}
}
@SuppressLint("ApplySharedPref")
private void proceedLogin(Token token, String host) {
private void proceedLogin(Token token, String host, String software) {
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_INSTANCE, host);
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);
updateCredential(LoginActivity.this, token.getAccess_token(), client_id, client_secret, token.getRefresh_token(), host, software);
} else {
binding.loginButton.setEnabled(true);
}

View File

@ -100,6 +100,7 @@ import su.litvak.chromecast.api.v2.MediaStatus;
import static app.fedilab.fedilabtube.MainActivity.TypeOfConnection.NORMAL;
import static app.fedilab.fedilabtube.MainActivity.TypeOfConnection.SURFING;
import static app.fedilab.fedilabtube.helper.Helper.isLoggedInType;
import static app.fedilab.fedilabtube.helper.Helper.peertubeInformation;
@ -320,6 +321,7 @@ public class MainActivity extends AppCompatActivity implements ChromeCastsListen
int tryFind = 0;
while (ChromeCasts.get().isEmpty() && tryFind < 5) {
try {
//noinspection BusyWait
Thread.sleep(1000);
tryFind++;
} catch (InterruptedException ignored) {
@ -559,7 +561,7 @@ public class MainActivity extends AppCompatActivity implements ChromeCastsListen
private void refreshToken() {
new Thread(() -> {
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String tokenStr = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
String tokenStr = Helper.getToken(MainActivity.this);
String instance = HelperInstance.getLiveInstance(MainActivity.this);
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String instanceShar = sharedpreferences.getString(Helper.PREF_INSTANCE, null);
@ -710,6 +712,7 @@ public class MainActivity extends AppCompatActivity implements ChromeCastsListen
mostLikedItem.setVisible(false);
incognitoItem.setVisible(false);
break;
case REMOTE_ACCOUNT:
case NORMAL:
accountItem.setVisible(true);
if (Helper.isLoggedIn(MainActivity.this)) {
@ -763,7 +766,7 @@ public class MainActivity extends AppCompatActivity implements ChromeCastsListen
new Thread(() -> {
try {
typeOfConnection = NORMAL;
if (!Helper.isLoggedIn(MainActivity.this)) {
if (!Helper.canMakeAction(MainActivity.this)) {
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
List<Account> accounts = new AccountDAO(MainActivity.this, db).getAllAccount();
if (accounts != null && accounts.size() > 0) {
@ -799,7 +802,7 @@ public class MainActivity extends AppCompatActivity implements ChromeCastsListen
if (typeOfConnection == SURFING) {
SwitchAccountHelper.switchDialog(MainActivity.this, false);
} else {
if (Helper.isLoggedIn(MainActivity.this)) {
if (Helper.canMakeAction(MainActivity.this)) {
intent = new Intent(MainActivity.this, AccountActivity.class);
} else {
intent = new Intent(MainActivity.this, LoginActivity.class);
@ -939,7 +942,8 @@ public class MainActivity extends AppCompatActivity implements ChromeCastsListen
public enum TypeOfConnection {
UNKNOWN,
NORMAL,
SURFING
SURFING,
REMOTE_ACCOUNT,
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

View File

@ -0,0 +1,194 @@
/* 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.fedilabtube;
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 androidx.appcompat.app.AppCompatActivity;
import app.fedilab.fedilabtube.client.mastodon.RetrofitMastodonAPI;
import app.fedilab.fedilabtube.client.entities.Error;
import app.fedilab.fedilabtube.client.entities.OauthParams;
import app.fedilab.fedilabtube.client.entities.Token;
import app.fedilab.fedilabtube.helper.Helper;
import es.dmoral.toasty.Toasty;
public class MastodonWebviewConnectActivity extends AppCompatActivity {
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);
if (Build.VERSION.SDK_INT >= 21) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
} else {
CookieManager.getInstance().setAcceptCookie(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];
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

@ -74,6 +74,8 @@ import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.frostwire.jlibtorrent.SessionManager;
import com.github.se_bastiaan.torrentstream.StreamStatus;
import com.github.se_bastiaan.torrentstream.Torrent;
import com.github.se_bastiaan.torrentstream.TorrentOptions;
@ -99,8 +101,9 @@ import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.DefaultTimeBar;
import com.google.android.exoplayer2.ui.PlayerControlView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.upstream.FileDataSource;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoListener;
@ -117,6 +120,8 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -127,7 +132,9 @@ import app.fedilab.fedilabtube.client.data.AccountData.Account;
import app.fedilab.fedilabtube.client.data.CaptionData.Caption;
import app.fedilab.fedilabtube.client.data.CommentData;
import app.fedilab.fedilabtube.client.data.CommentData.Comment;
import app.fedilab.fedilabtube.client.data.InstanceData;
import app.fedilab.fedilabtube.client.data.PlaylistData;
import app.fedilab.fedilabtube.client.data.PluginData;
import app.fedilab.fedilabtube.client.data.VideoData;
import app.fedilab.fedilabtube.client.entities.Error;
import app.fedilab.fedilabtube.client.entities.File;
@ -135,6 +142,7 @@ import app.fedilab.fedilabtube.client.entities.MenuItemView;
import app.fedilab.fedilabtube.client.entities.PlaylistExist;
import app.fedilab.fedilabtube.client.entities.Report;
import app.fedilab.fedilabtube.client.entities.UserSettings;
import app.fedilab.fedilabtube.client.mastodon.RetrofitMastodonAPI;
import app.fedilab.fedilabtube.databinding.ActivityPeertubeBinding;
import app.fedilab.fedilabtube.drawer.CommentListAdapter;
import app.fedilab.fedilabtube.drawer.MenuAdapter;
@ -150,6 +158,7 @@ import app.fedilab.fedilabtube.viewmodel.PlaylistsVM;
import app.fedilab.fedilabtube.viewmodel.PostActionsVM;
import app.fedilab.fedilabtube.viewmodel.SearchVM;
import app.fedilab.fedilabtube.viewmodel.TimelineVM;
import app.fedilab.fedilabtube.viewmodel.mastodon.MastodonPostActionsVM;
import app.fedilab.fedilabtube.webview.CustomWebview;
import app.fedilab.fedilabtube.webview.MastalabWebChromeClient;
import app.fedilab.fedilabtube.webview.MastalabWebViewClient;
@ -167,6 +176,7 @@ import static app.fedilab.fedilabtube.client.RetrofitPeertubeAPI.ActionType.REPL
import static app.fedilab.fedilabtube.client.RetrofitPeertubeAPI.ActionType.REPORT_ACCOUNT;
import static app.fedilab.fedilabtube.client.RetrofitPeertubeAPI.ActionType.REPORT_VIDEO;
import static app.fedilab.fedilabtube.helper.Helper.CAST_ID;
import static app.fedilab.fedilabtube.helper.Helper.canMakeAction;
import static app.fedilab.fedilabtube.helper.Helper.getAttColor;
import static app.fedilab.fedilabtube.helper.Helper.isLoggedIn;
import static app.fedilab.fedilabtube.helper.Helper.loadGiF;
@ -209,6 +219,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
private boolean isRemote;
private boolean willPlayFromIntent;
private String chromeCastVideoURL;
private app.fedilab.fedilabtube.client.mastodon.Status status;
public static void hideKeyboard(Activity activity) {
if (activity != null && activity.getWindow() != null) {
@ -235,7 +246,8 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
@Override
public void onStreamStarted(Torrent torrent) {
startStream(peertube, torrent.getVideoFile().getAbsolutePath(), null, autoPlay, -1, null, null, true);
}
@Override
@ -245,10 +257,45 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
@Override
public void onStreamReady(Torrent torrent) {
if (torrent.getVideoFile() != null) {
for (int i = 0; i < torrent.getFileNames().length; i++) {
torrent.getTorrentHandle().renameFile(i, torrent.getFileNames()[0].replaceAll("[^a-zA-Z0-9/.-]", "_"));
}
startStream(peertube, torrent.getVideoFile().getAbsolutePath().replaceAll("[^a-zA-Z0-9/.-]", "_"), null, autoPlay, -1, null, null, true);
PlayerControlView controlView = binding.doubleTapPlayerView.findViewById(R.id.exo_controller);
ConstraintLayout torrent_info = controlView.findViewById(R.id.torrent_info);
TextView dowload_rate = controlView.findViewById(R.id.dowload_rate);
TextView upload_rate = controlView.findViewById(R.id.upload_rate);
torrent_info.setVisibility(View.VISIBLE);
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
SessionManager sessionManager = torrentStream.getSessionManager();
if (sessionManager != null) {
long upload = sessionManager.uploadRate();
long download = sessionManager.downloadRate();
runOnUiThread(() -> {
dowload_rate.setText(String.format("▼ %s", Helper.rateSize(PeertubeActivity.this, download)));
upload_rate.setText(String.format("▲ %s", Helper.rateSize(PeertubeActivity.this, upload)));
});
}
}
}, 0, 1000);
} else {
Toasty.error(PeertubeActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
}
}
@Override
public void onStreamProgress(Torrent torrent, StreamStatus status) {
if (binding != null) {
PlayerControlView controlView = binding.doubleTapPlayerView.findViewById(R.id.exo_controller);
TextView peers_number = controlView.findViewById(R.id.peers_number);
peers_number.setText(getString(R.string.peers, status.peers));
}
}
@Override
@ -267,13 +314,13 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
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);
if (Helper.isLoggedIn(PeertubeActivity.this) && !sepiaSearch) {
if (Helper.canMakeAction(PeertubeActivity.this) && !sepiaSearch) {
Account account = new AccountDAO(PeertubeActivity.this, db).getAccountByToken(token);
Helper.loadGiF(PeertubeActivity.this, account.getAvatar() != null ? account.getAvatar().getPath() : null, binding.myPp);
}
isRemote = false;
TorrentOptions torrentOptions = new TorrentOptions.Builder()
.saveLocation(getCacheDir())
.saveLocation(getCacheDir() + "/torrent/")
.autoDownload(true)
.removeFilesAfterStop(true)
.build();
@ -296,7 +343,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
ConstraintLayout.LayoutParams.MATCH_PARENT,
0,
3.0f
4.0f
);
binding.videoContainer.setLayoutParams(param);
}
@ -317,12 +364,21 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
sepiaSearch = b.getBoolean("sepia_search", false);
peertube = b.getParcelable("video");
}
new Thread(() -> {
String videoId = peertube != null ? peertube.getUuid() : videoUuid;
new RetrofitPeertubeAPI(PeertubeActivity.this).postView(videoId);
}).start();
willPlayFromIntent = manageIntentUrl(intent);
if (BuildConfig.allow_remote_connections && Helper.isLoggedInType(PeertubeActivity.this) == MainActivity.TypeOfConnection.REMOTE_ACCOUNT) {
binding.peertubeLikeCount.setVisibility(View.GONE);
binding.peertubeDislikeCount.setVisibility(View.GONE);
binding.peertubePlaylist.setVisibility(View.GONE);
binding.peertubeReblog.setVisibility(View.VISIBLE);
binding.peertubeFavorite.setVisibility(View.VISIBLE);
binding.peertubeBookmark.setVisibility(View.VISIBLE);
} else {
binding.peertubePlaylist.setVisibility(View.VISIBLE);
}
binding.peertubeDescriptionMore.setOnClickListener(v -> {
if (show_more_content != null && peertube != null) {
if (binding.peertubeDescriptionMore.getText().toString().compareTo(getString(R.string.show_more)) == 0) {
@ -334,7 +390,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
}
}
});
if (!Helper.isLoggedIn(PeertubeActivity.this) || sepiaSearch) {
if (!Helper.canMakeAction(PeertubeActivity.this) || sepiaSearch) {
binding.writeCommentContainer.setVisibility(View.GONE);
}
playInMinimized = sharedpreferences.getBoolean(getString(R.string.set_video_minimize_choice), true);
@ -443,7 +499,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
openFullscreenDialog();
}
binding.postCommentButton.setOnClickListener(v -> {
if (isLoggedIn(PeertubeActivity.this) && !sepiaSearch) {
if (canMakeAction(PeertubeActivity.this) && !sepiaSearch) {
openPostComment(null, 0);
} else {
if (sepiaSearch) {
@ -667,13 +723,42 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
if (autoFullscreen && autoPlay) {
openFullscreenDialog();
}
binding.peertubePlaylist.setVisibility(View.VISIBLE);
TimelineVM feedsViewModel = new ViewModelProvider(PeertubeActivity.this).get(TimelineVM.class);
if (!isRemote) {
feedsViewModel.getVideo(sepiaSearch ? peertubeInstance : null, videoUuid, isMyVideo).observe(PeertubeActivity.this, this::manageVIewVideo);
}
CaptionsVM captionsViewModel = new ViewModelProvider(PeertubeActivity.this).get(CaptionsVM.class);
captionsViewModel.getCaptions(sepiaSearch ? peertubeInstance : null, videoUuid).observe(PeertubeActivity.this, this::manageCaptions);
//Post view count
new Thread(() -> {
String videoId = peertube != null ? peertube.getUuid() : videoUuid;
new RetrofitPeertubeAPI(PeertubeActivity.this).postView(videoId);
}).start();
//manage plugin
new Thread(() -> {
String videoInstance = peertubeInstance != null ? peertubeInstance : peertube.getAccount().getHost();
InstanceData.InstanceConfig instanceConfig = new RetrofitPeertubeAPI(PeertubeActivity.this, videoInstance, null).getConfigInstance();
if (instanceConfig != null && instanceConfig.getPlugin() != null && instanceConfig.getPlugin().getRegistered() != null) {
for (PluginData.PluginInfo pluginInfo : instanceConfig.getPlugin().getRegistered()) {
if (pluginInfo.getName().compareTo("player-watermark") == 0) {
PluginData.WaterMark getWaterMark = new RetrofitPeertubeAPI(PeertubeActivity.this, videoInstance, null).getWaterMark();
if (getWaterMark != null && getWaterMark.getDescription() != null && getWaterMark.getDescription().getWatermarkImageUrl() != null) {
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
Glide.with(binding.watermark.getContext())
.asDrawable()
.load(getWaterMark.getDescription().getWatermarkImageUrl())
.into(binding.watermark);
binding.watermark.setVisibility(View.VISIBLE);
};
mainHandler.post(myRunnable);
}
}
}
}
}).start();
new Thread(() -> {
try {
RetrofitPeertubeAPI api;
@ -1012,10 +1097,11 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
PlaylistsVM viewModel = new ViewModelProvider(this).get(PlaylistsVM.class);
viewModel.videoExists(videoIds).observe(this, this::manageVIewPlaylist);
if (!Helper.isLoggedIn(PeertubeActivity.this) || sepiaSearch) {
if (!Helper.canMakeAction(PeertubeActivity.this) || sepiaSearch) {
binding.writeCommentContainer.setVisibility(View.GONE);
}
if (peertube.isNsfw()) {
binding.videoSensitive.setVisibility(View.VISIBLE);
} else {
@ -1137,6 +1223,36 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
changeColor();
initResolution();
binding.peertubeReblog.setOnClickListener(v -> {
if (status != null) {
MastodonPostActionsVM mastodonPostActionsVM = new ViewModelProvider(PeertubeActivity.this).get(MastodonPostActionsVM.class);
RetrofitMastodonAPI.actionType type = status.isReblogged() ? RetrofitMastodonAPI.actionType.UNBOOST : RetrofitMastodonAPI.actionType.BOOST;
mastodonPostActionsVM.post(type, status).observe(PeertubeActivity.this, this::manageVIewPostActionsMastodon);
} else {
Toasty.error(PeertubeActivity.this, getString(R.string.federation_issue), Toasty.LENGTH_LONG).show();
}
});
binding.peertubeFavorite.setOnClickListener(v -> {
if (status != null) {
MastodonPostActionsVM mastodonPostActionsVM = new ViewModelProvider(PeertubeActivity.this).get(MastodonPostActionsVM.class);
RetrofitMastodonAPI.actionType type = status.isFavourited() ? RetrofitMastodonAPI.actionType.UNFAVOURITE : RetrofitMastodonAPI.actionType.FAVOURITE;
mastodonPostActionsVM.post(type, status).observe(PeertubeActivity.this, this::manageVIewPostActionsMastodon);
} else {
Toasty.error(PeertubeActivity.this, getString(R.string.federation_issue), Toasty.LENGTH_LONG).show();
}
});
binding.peertubeBookmark.setOnClickListener(v -> {
if (status != null) {
MastodonPostActionsVM mastodonPostActionsVM = new ViewModelProvider(PeertubeActivity.this).get(MastodonPostActionsVM.class);
RetrofitMastodonAPI.actionType type = status.isBookmarked() ? RetrofitMastodonAPI.actionType.UNBOOKMARK : RetrofitMastodonAPI.actionType.BOOKMARK;
mastodonPostActionsVM.post(type, status).observe(PeertubeActivity.this, this::manageVIewPostActionsMastodon);
} else {
Toasty.error(PeertubeActivity.this, getString(R.string.federation_issue), Toasty.LENGTH_LONG).show();
}
});
binding.peertubeLikeCount.setOnClickListener(v -> {
if (isLoggedIn(PeertubeActivity.this) && !sepiaSearch) {
String newState = peertube.getMyRating().equals("like") ? "none" : "like";
@ -1188,6 +1304,11 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
}
});
if (BuildConfig.allow_remote_connections && Helper.isLoggedInType(PeertubeActivity.this) == MainActivity.TypeOfConnection.REMOTE_ACCOUNT) {
String url = "https://" + peertube.getChannel().getHost() + "/videos/watch/" + peertube.getUuid();
MastodonPostActionsVM postActionsVM = new ViewModelProvider(PeertubeActivity.this).get(MastodonPostActionsVM.class);
postActionsVM.searchRemoteStatus(url).observe(PeertubeActivity.this, this::retrieveRemoteStatus);
}
if (mode != Helper.VIDEO_MODE_WEBVIEW) {
@ -1288,51 +1409,85 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
});
}
private void stream(VideoData.Video video, String resolution, boolean autoPlay, long position, Uri subtitles, String lang) {
String videoURL = video.getFileUrl(resolution, PeertubeActivity.this);
if (videoURL != null && !videoURL.endsWith("m3u8")) {
if (videoURL.endsWith(".torrent")) {
torrentStream.startStream(videoURL);
return;
} else {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
int video_cache = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB);
ProgressiveMediaSource videoSource;
SingleSampleMediaSource subtitleSource = null;
if (video_cache == 0) {
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(PeertubeActivity.this,
Util.getUserAgent(PeertubeActivity.this, null), null);
if (subtitles != null) {
MediaItem.Subtitle mediaSubtitle = new MediaItem.Subtitle(subtitles, MimeTypes.TEXT_VTT, lang);
subtitleSource = new SingleSampleMediaSource.Factory(dataSourceFactory).createMediaSource(mediaSubtitle, C.TIME_UNSET);
}
MediaItem mediaItem = new MediaItem.Builder().setUri(videoURL).build();
videoSource = new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(mediaItem);
} else {
CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(PeertubeActivity.this);
MediaItem mediaItem = new MediaItem.Builder().setUri(videoURL).build();
videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory)
.createMediaSource(mediaItem);
if (subtitles != null) {
MediaItem.Subtitle mediaSubtitle = new MediaItem.Subtitle(subtitles, MimeTypes.TEXT_VTT, lang, Format.NO_VALUE);
subtitleSource = new SingleSampleMediaSource.Factory(cacheDataSourceFactory).createMediaSource(mediaSubtitle, C.TIME_UNSET);
}
}
if (lang != null && subtitleSource != null) {
MergingMediaSource mergedSource =
new MergingMediaSource(videoSource, subtitleSource);
player.setMediaSource(mergedSource);
} else {
player.setMediaSource(videoSource);
/**
* Manage video to play with different factors
*
* @param video VideoData.Video
* @param localTorrentUrl String if not null that will be used
* @param resolution String the current resolution asked
* @param autoPlay boolean
* @param position int current position
* @param subtitles Uri uri for subtitles
* @param lang String ("en","fr", etc.)
*/
private void stream(VideoData.Video video, String localTorrentUrl, String resolution, boolean autoPlay, long position, Uri subtitles, String lang) {
String videoURL = localTorrentUrl == null ? video.getFileUrl(resolution, PeertubeActivity.this) : localTorrentUrl;
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
int video_cache = sharedpreferences.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB);
if (videoURL != null && (videoURL.endsWith(".torrent") || videoURL.startsWith("magnet"))) {
torrentStream.startStream(videoURL);
return;
} else {
ProgressiveMediaSource videoSource = null;
HlsMediaSource hlsMediaSource = null;
SingleSampleMediaSource subtitleSource = null;
DataSource.Factory dataSourceFactory = null;
if (localTorrentUrl != null) {
DataSpec dataSpec = new DataSpec(Uri.fromFile(new java.io.File(localTorrentUrl)));
FileDataSource fileDataSource = new FileDataSource();
try {
fileDataSource.open(dataSpec);
dataSourceFactory = () -> fileDataSource;
} catch (FileDataSource.FileDataSourceException e) {
e.printStackTrace();
}
}
} else {
MediaItem mediaItem = new MediaItem.Builder().setUri(Uri.parse(videoURL)).build();
HlsMediaSource hlsMediaSource = new HlsMediaSource.Factory(new DefaultHttpDataSourceFactory(System.getProperty("http.agent")))
.createMediaSource(mediaItem);
player.setMediaSource(hlsMediaSource);
if (video_cache == 0 || dataSourceFactory != null) {
if (dataSourceFactory == null) {
dataSourceFactory = new DefaultDataSourceFactory(PeertubeActivity.this,
Util.getUserAgent(PeertubeActivity.this, null), null);
}
if (subtitles != null) {
MediaItem.Subtitle mediaSubtitle = new MediaItem.Subtitle(subtitles, MimeTypes.TEXT_VTT, lang);
subtitleSource = new SingleSampleMediaSource.Factory(dataSourceFactory).createMediaSource(mediaSubtitle, C.TIME_UNSET);
}
MediaItem mediaItem = new MediaItem.Builder().setUri(Uri.parse(videoURL)).build();
if (videoURL != null && !videoURL.endsWith("m3u8")) {
videoSource = new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(mediaItem);
} else {
hlsMediaSource = new HlsMediaSource.Factory(dataSourceFactory)
.createMediaSource(mediaItem);
}
} else {
CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(PeertubeActivity.this);
MediaItem mediaItem = new MediaItem.Builder().setUri(videoURL).build();
videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory)
.createMediaSource(mediaItem);
if (subtitles != null) {
MediaItem.Subtitle mediaSubtitle = new MediaItem.Subtitle(subtitles, MimeTypes.TEXT_VTT, lang, Format.NO_VALUE);
subtitleSource = new SingleSampleMediaSource.Factory(cacheDataSourceFactory).createMediaSource(mediaSubtitle, C.TIME_UNSET);
}
if (videoURL != null && !videoURL.endsWith("m3u8")) {
videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory).createMediaSource(mediaItem);
} else {
hlsMediaSource = new HlsMediaSource.Factory(cacheDataSourceFactory)
.createMediaSource(mediaItem);
}
}
if (lang != null && subtitleSource != null && videoSource != null) {
MergingMediaSource mergedSource =
new MergingMediaSource(videoSource, subtitleSource);
player.setMediaSource(mergedSource);
} else if (lang != null && subtitleSource != null) {
MergingMediaSource mergedSource =
new MergingMediaSource(hlsMediaSource, subtitleSource);
player.setMediaSource(mergedSource);
} else if (videoSource != null) {
player.setMediaSource(videoSource);
} else {
player.setMediaSource(hlsMediaSource);
}
}
player.prepare();
if (position > 0) {
@ -1346,14 +1501,14 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
private void fetchComments() {
if (peertube.isCommentsEnabled()) {
if (Helper.isLoggedIn(PeertubeActivity.this)) {
if (Helper.canMakeAction(PeertubeActivity.this)) {
binding.postCommentButton.setVisibility(View.VISIBLE);
} else {
binding.postCommentButton.setVisibility(View.GONE);
}
CommentVM commentViewModel = new ViewModelProvider(PeertubeActivity.this).get(CommentVM.class);
commentViewModel.getThread(sepiaSearch ? peertubeInstance : null, videoUuid, max_id).observe(PeertubeActivity.this, this::manageVIewComment);
if (Helper.isLoggedIn(PeertubeActivity.this) && !sepiaSearch) {
if (Helper.canMakeAction(PeertubeActivity.this) && !sepiaSearch) {
binding.writeCommentContainer.setVisibility(View.VISIBLE);
}
binding.peertubeComments.setVisibility(View.VISIBLE);
@ -1398,13 +1553,13 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
finish();
});
dialogBuilder.setPositiveButton(R.string.play, (dialog, id) -> {
stream(video, resolution, autoPlay, position, subtitles, lang);
stream(video, null, resolution, autoPlay, position, subtitles, lang);
dialog.dismiss();
});
alertDialog = dialogBuilder.create();
alertDialog.show();
} else {
stream(video, resolution, autoPlay, position, subtitles, lang);
stream(video, torrentLocal, resolution, autoPlay, position, subtitles, lang);
}
@ -1424,7 +1579,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
ConstraintLayout.LayoutParams.MATCH_PARENT,
0,
3.0f
4.0f
);
binding.videoContainer.setLayoutParams(param);
}
@ -1915,19 +2070,30 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
private void sendComment(Comment comment, int position) {
if (isLoggedIn(PeertubeActivity.this) && !sepiaSearch) {
if (canMakeAction(PeertubeActivity.this) && !sepiaSearch) {
if (comment == null) {
String commentStr = binding.addCommentWrite.getText() != null ? binding.addCommentWrite.getText().toString() : "";
if (commentStr.trim().length() > 0) {
PostActionsVM viewModelComment = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class);
viewModelComment.comment(ADD_COMMENT, peertube.getId(), null, commentStr).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(ADD_COMMENT, 0, apiResponse1));
if (Helper.isLoggedIn(PeertubeActivity.this)) {
PostActionsVM viewModelComment = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class);
viewModelComment.comment(ADD_COMMENT, peertube.getId(), null, commentStr).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(ADD_COMMENT, 0, apiResponse1));
} else {//Remote account is posting a message
String url = "https://" + peertube.getChannel().getHost() + "/videos/watch/" + peertube.getUuid();
MastodonPostActionsVM viewModelCommentMastodon = new ViewModelProvider(PeertubeActivity.this).get(MastodonPostActionsVM.class);
viewModelCommentMastodon.comment(url, commentStr).observe(PeertubeActivity.this, status -> manageVIewPostActionsMastodon(ADD_COMMENT, position, status));
}
binding.addCommentWrite.setText("");
}
} else {
String commentView = binding.addCommentWrite.getText() != null ? binding.addCommentWrite.getText().toString() : "";
if (commentView.trim().length() > 0) {
PostActionsVM viewModelComment = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class);
viewModelComment.comment(REPLY, peertube.getId(), comment.getId(), commentView).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(REPLY, position, apiResponse1));
if (Helper.isLoggedIn(PeertubeActivity.this)) {
PostActionsVM viewModelComment = new ViewModelProvider(PeertubeActivity.this).get(PostActionsVM.class);
viewModelComment.comment(REPLY, peertube.getId(), comment.getId(), commentView).observe(PeertubeActivity.this, apiResponse1 -> manageVIewPostActions(REPLY, position, apiResponse1));
} else {//Remote account is posting a message
MastodonPostActionsVM viewModelCommentMastodon = new ViewModelProvider(PeertubeActivity.this).get(MastodonPostActionsVM.class);
viewModelCommentMastodon.comment(comment.getUrl(), commentView).observe(PeertubeActivity.this, status -> manageVIewPostActionsMastodon(REPLY, position, status));
}
binding.addCommentWrite.setText("");
}
}
@ -1967,6 +2133,7 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
binding.replyThread.startAnimation(animate);
}
public void openPostComment(Comment comment, int position) {
if (comment != null) {
binding.replyContent.setVisibility(View.VISIBLE);
@ -2017,8 +2184,10 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
binding.postComment.startAnimation(animateComment);
if (comment != null) {
binding.addCommentWrite.setText(String.format("@%s ", comment.getAccount().getAcct()));
binding.addCommentWrite.setSelection(binding.addCommentWrite.getText() != null ? binding.addCommentWrite.getText().length() : 0);
} else {
binding.addCommentWrite.setText(String.format("@%s ", peertube.getAccount().getAcct()));
}
binding.addCommentWrite.setSelection(binding.addCommentWrite.getText() != null ? binding.addCommentWrite.getText().length() : 0);
binding.send.setOnClickListener(null);
binding.send.setOnClickListener(v -> sendComment(comment, position));
@ -2053,6 +2222,45 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
binding.postComment.startAnimation(animateComment);
}
public void manageVIewPostActionsMastodon(app.fedilab.fedilabtube.client.mastodon.Status status) {
if (status != null) {
this.status = status;
changeColorMastodon();
binding.peertubeFavorite.setText(String.valueOf(status.getFavouriteCount()));
binding.peertubeReblog.setText(String.valueOf(status.getReblogsCount()));
} else {
Toasty.error(PeertubeActivity.this, getString(R.string.toast_error), Toasty.LENGTH_LONG).show();
}
}
public void manageVIewPostActionsMastodon(RetrofitPeertubeAPI.ActionType statusAction, int position, app.fedilab.fedilabtube.client.mastodon.Status status) {
if (peertube.isCommentsEnabled() && statusAction == ADD_COMMENT) {
if (status != null) {
Comment comment = app.fedilab.fedilabtube.client.mastodon.Status.convertStatusToComment(status);
comments.add(0, comment);
commentListAdapter.notifyItemInserted(0);
}
} else if (peertube.isCommentsEnabled() && statusAction == REPLY) {
if (status != null) {
Comment comment = app.fedilab.fedilabtube.client.mastodon.Status.convertStatusToComment(status);
if (commentsThread == null) {
commentsThread = new ArrayList<>();
}
commentsThread.add(position + 1, comment);
commentReplyListAdapter.notifyItemInserted(position + 1);
}
}
}
public void retrieveRemoteStatus(app.fedilab.fedilabtube.client.mastodon.Status status) {
this.status = status;
if (status != null) {
changeColorMastodon();
binding.peertubeFavorite.setText(String.valueOf(status.getFavouriteCount()));
binding.peertubeReblog.setText(String.valueOf(status.getReblogsCount()));
}
}
@SuppressWarnings({"unused", "RedundantSuppression"})
public void manageVIewPostActions(RetrofitPeertubeAPI.ActionType statusAction, int position, APIResponse apiResponse) {
@ -2130,6 +2338,47 @@ public class PeertubeActivity extends AppCompatActivity implements CommentListAd
}
}
private void changeColorMastodon() {
Drawable reblog = ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_baseline_repeat_24);
Drawable favorite = ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_baseline_star_24);
Drawable bookmark = ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_baseline_bookmark_24);
int color = getAttColor(this, android.R.attr.colorControlNormal);
if (reblog != null) {
reblog.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
DrawableCompat.setTint(reblog, color);
}
if (favorite != null) {
favorite.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
DrawableCompat.setTint(favorite, color);
}
if (bookmark != null) {
bookmark.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
DrawableCompat.setTint(bookmark, color);
}
if (status.isReblogged()) {
reblog.setColorFilter(getResources().getColor(R.color.positive_thumbs), PorterDuff.Mode.SRC_ATOP);
DrawableCompat.setTint(reblog, getResources().getColor(R.color.positive_thumbs));
}
if (status.isFavourited()) {
favorite.setColorFilter(getResources().getColor(R.color.favorite), PorterDuff.Mode.SRC_ATOP);
DrawableCompat.setTint(favorite, getResources().getColor(R.color.favorite));
}
if (status.isBookmarked()) {
bookmark.setColorFilter(getResources().getColor(R.color.bookmark), PorterDuff.Mode.SRC_ATOP);
DrawableCompat.setTint(bookmark, getResources().getColor(R.color.bookmark));
}
binding.peertubeReblog.setCompoundDrawablesWithIntrinsicBounds(null, reblog, null, null);
binding.peertubeFavorite.setCompoundDrawablesWithIntrinsicBounds(null, favorite, null, null);
binding.peertubeBookmark.setCompoundDrawablesWithIntrinsicBounds(null, bookmark, null, null);
}
private void changeColor() {
Drawable thumbUp = ContextCompat.getDrawable(PeertubeActivity.this, R.drawable.ic_baseline_thumb_up_alt_24);

View File

@ -455,6 +455,10 @@ public class PeertubeEditUploadActivity extends AppCompatActivity {
videoParams.setChannelId(channelToSendId);
videoParams.setPrivacy(finalPrivacyToSend.getId());
List<String> tags = binding.pVideoTags.getTags();
if (tags.size() > 5) {
Toasty.error(PeertubeEditUploadActivity.this, getString(R.string.max_tag_size), Toast.LENGTH_LONG).show();
return;
}
videoParams.setTags(tags);
binding.setUploadSubmit.setEnabled(false);
MyVideoVM myVideoVM = new ViewModelProvider(PeertubeEditUploadActivity.this).get(MyVideoVM.class);

View File

@ -321,7 +321,7 @@ public class PeertubeUploadActivity extends AppCompatActivity {
}
try {
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
String token = Helper.getToken(PeertubeUploadActivity.this);
new MultipartUploadRequest(PeertubeUploadActivity.this, "https://" + HelperInstance.getLiveInstance(PeertubeUploadActivity.this) + "/api/v1/videos/upload")
.setMethod("POST")

View File

@ -19,6 +19,7 @@ import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
@ -91,7 +92,9 @@ public class WebviewConnectActivity extends AppCompatActivity {
} else {
CookieManager.getInstance().setAcceptCookie(true);
}
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.login);
final ProgressBar pbar = findViewById(R.id.progress_bar);
webView.setWebChromeClient(new WebChromeClient() {
@ -137,9 +140,11 @@ public class WebviewConnectActivity extends AppCompatActivity {
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());
updateCredential(WebviewConnectActivity.this, token.getAccess_token(), clientId, clientSecret, token.getRefresh_token(), new URL(url).getHost(), null);
finish();
}
} catch (Exception e) {
@ -154,6 +159,17 @@ public class WebviewConnectActivity extends AppCompatActivity {
}
@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()) {

View File

@ -25,6 +25,7 @@ import app.fedilab.fedilabtube.client.data.CommentData;
import app.fedilab.fedilabtube.client.data.InstanceData;
import app.fedilab.fedilabtube.client.data.NotificationData;
import app.fedilab.fedilabtube.client.data.PlaylistData;
import app.fedilab.fedilabtube.client.data.PluginData;
import app.fedilab.fedilabtube.client.data.VideoData;
import app.fedilab.fedilabtube.client.data.VideoPlaylistData;
import app.fedilab.fedilabtube.client.entities.CaptionsParams;
@ -70,6 +71,9 @@ public interface PeertubeService {
@GET(".well-known/nodeinfo")
Call<WellKnownNodeinfo> getWellKnownNodeinfo();
@GET("plugins/peertube-plugin-player-watermark/public-settings")
Call<PluginData.WaterMark> waterMark();
//Instance info
@GET("config/about")
Call<InstanceData.InstanceInfo> configAbout();

View File

@ -55,6 +55,7 @@ import app.fedilab.fedilabtube.client.data.CommentData;
import app.fedilab.fedilabtube.client.data.InstanceData;
import app.fedilab.fedilabtube.client.data.NotificationData;
import app.fedilab.fedilabtube.client.data.PlaylistData;
import app.fedilab.fedilabtube.client.data.PluginData;
import app.fedilab.fedilabtube.client.data.VideoData;
import app.fedilab.fedilabtube.client.data.VideoPlaylistData;
import app.fedilab.fedilabtube.client.entities.AccountCreation;
@ -98,9 +99,9 @@ public class RetrofitPeertubeAPI {
private final Context _context;
private final String instance;
private final String count;
private final String showNSFWVideos;
private String token;
private Set<String> selection;
private String showNSFWVideos = "both";
public RetrofitPeertubeAPI(Context context) {
_context = context;
@ -136,7 +137,7 @@ public class RetrofitPeertubeAPI {
}
public static void updateCredential(Activity activity, String token, String client_id, String client_secret, String refresh_token, String host) {
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;
String instance = host;
@ -164,7 +165,8 @@ public class RetrofitPeertubeAPI {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_ID, account.getId());
editor.putString(Helper.PREF_KEY_NAME, account.getUsername());
if (!host.startsWith("tube")) {
boolean remote_account = software != null && software.toUpperCase().trim().compareTo("PEERTUBE") != 0;
if (!remote_account) {
editor.putString(Helper.PREF_INSTANCE, host);
}
editor.apply();
@ -172,7 +174,7 @@ public class RetrofitPeertubeAPI {
new AccountDAO(activity, db).updateAccountCredential(account);
else {
if (account.getUsername() != null && account.getCreatedAt() != null)
new AccountDAO(activity, db).insertAccount(account);
new AccountDAO(activity, db).insertAccount(account, software);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
@ -200,7 +202,7 @@ public class RetrofitPeertubeAPI {
.build();
SharedPreferences sharedpreferences = _context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
if (token == null) {
token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
token = Helper.getToken(_context);
}
selection = sharedpreferences.getStringSet(_context.getString(R.string.set_video_language_choice), null);
return retrofit.create(PeertubeService.class);
@ -240,6 +242,8 @@ public class RetrofitPeertubeAPI {
SharedPreferences sharedpreferences = _context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, tokenReply.getAccess_token());
editor.putString(Helper.PREF_SOFTWARE, null);
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);
@ -267,6 +271,9 @@ public class RetrofitPeertubeAPI {
* POST a view count for a video
*/
public void postView(String videoUuid) {
if (videoUuid == null) {
return;
}
PeertubeService peertubeService = init();
Call<String> postViewCall = peertubeService.postView(videoUuid);
try {
@ -729,6 +736,26 @@ public class RetrofitPeertubeAPI {
}
/**
* Get watermark info
*
* @return PluginData.WaterMark
*/
public PluginData.WaterMark getWaterMark() {
PeertubeService peertubeService = init();
Call<PluginData.WaterMark> waterMarkCall = peertubeService.waterMark();
try {
Response<PluginData.WaterMark> response = waterMarkCall.execute();
if (response.isSuccessful() && response.body() != null) {
return response.body();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Get video quota
*
@ -1619,6 +1646,9 @@ public class RetrofitPeertubeAPI {
error.setStatusCode(responseCode);
error.setError(_context.getString(R.string.toast_error));
}
if (responseCode == 404 || responseCode == 502) {
error.setError(_context.getString(R.string.instance_not_availabe));
}
apiResponse.setError(error);
}

View File

@ -77,7 +77,7 @@ public class AccountData {
private String client_id;
private String client_secret;
private String refresh_token;
private String software;
public Account() {
}
@ -241,6 +241,14 @@ 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;

View File

@ -1,4 +1,18 @@
package app.fedilab.fedilabtube.client.data;
/* 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;
@ -366,6 +380,16 @@ public class InstanceData {
public static class InstanceConfig {
@SerializedName("user")
private User user;
@SerializedName("plugin")
private PluginData.Plugin plugin;
public PluginData.Plugin getPlugin() {
return plugin;
}
public void setPlugin(PluginData.Plugin plugin) {
this.plugin = plugin;
}
public User getUser() {
return user;
@ -376,6 +400,7 @@ public class InstanceData {
}
}
public static class User {
@SerializedName("videoQuota")
private long videoQuota;

View File

@ -0,0 +1,125 @@
package app.fedilab.fedilabtube.client.data;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/* 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>. */
@SuppressWarnings("ALL")
public class PluginData {
public static class Plugin {
@SerializedName("registered")
private List<PluginInfo> registered;
@SerializedName("registeredExternalAuths")
private List<PluginInfo> registeredExternalAuths;
@SerializedName("registeredIdAndPassAuths")
private List<PluginInfo> registeredIdAndPassAuths;
public List<PluginInfo> getRegistered() {
return registered;
}
public void setRegistered(List<PluginInfo> registered) {
this.registered = registered;
}
public List<PluginInfo> getRegisteredExternalAuths() {
return registeredExternalAuths;
}
public void setRegisteredExternalAuths(List<PluginInfo> registeredExternalAuths) {
this.registeredExternalAuths = registeredExternalAuths;
}
public List<PluginInfo> getRegisteredIdAndPassAuths() {
return registeredIdAndPassAuths;
}
public void setRegisteredIdAndPassAuths(List<PluginInfo> registeredIdAndPassAuths) {
this.registeredIdAndPassAuths = registeredIdAndPassAuths;
}
}
public static class WaterMark {
@SerializedName("publicSettings")
private PublicSettings description;
public PublicSettings getDescription() {
return description;
}
public void setDescription(PublicSettings description) {
this.description = description;
}
}
public static class PublicSettings {
@SerializedName("watermark-image-url")
private String watermarkImageUrl;
@SerializedName("watermark-target-url")
private String watermarkTargetUrl;
public String getWatermarkImageUrl() {
return watermarkImageUrl;
}
public void setWatermarkImageUrl(String watermarkImageUrl) {
this.watermarkImageUrl = watermarkImageUrl;
}
public String getWatermarkTargetUrl() {
return watermarkTargetUrl;
}
public void setWatermarkTargetUrl(String watermarkTargetUrl) {
this.watermarkTargetUrl = watermarkTargetUrl;
}
}
public static class PluginInfo {
@SerializedName("description")
private String description;
@SerializedName("name")
private String name;
@SerializedName("version")
private String version;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
}

View File

@ -40,6 +40,10 @@ public class OauthParams {
private String access_token;
@SerializedName("response_type")
private String response_type;
@SerializedName("code")
private String code;
@SerializedName("redirect_uri")
private String redirect_uri;
public String getClient_secret() {
return client_secret;
@ -120,4 +124,20 @@ public class OauthParams {
public void setResponse_type(String response_type) {
this.response_type = response_type;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getRedirect_uri() {
return redirect_uri;
}
public void setRedirect_uri(String redirect_uri) {
this.redirect_uri = redirect_uri;
}
}

View File

@ -0,0 +1,255 @@
package app.fedilab.fedilabtube.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.fedilabtube.client.data.AccountData;
import app.fedilab.fedilabtube.client.entities.Avatar;
@SuppressWarnings({"unused", "RedundantSuppression"})
public class MastodonAccount {
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);
}
}
public static AccountData.Account convertToPeertubeAccount(MastodonAccount.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;
}
}

View File

@ -0,0 +1,102 @@
package app.fedilab.fedilabtube.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.fedilabtube.client.entities.Oauth;
import app.fedilab.fedilabtube.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 {
@POST("apps")
Call<Oauth> getOauth(
@Query("client_name") String client_name,
@Query("redirect_uris") String redirect_uris,
@Query("scopes") String scopes,
@Query("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
);
@POST("statuses")
Call<Status> postReply(
@Header("Authorization") String credentials,
@Query("in_reply_to_id") String inReplyToId,
@Query("status") String content,
@Query("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

@ -0,0 +1,44 @@
package app.fedilab.fedilabtube.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

@ -0,0 +1,336 @@
package app.fedilab.fedilabtube.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 app.fedilab.fedilabtube.MainActivity;
import app.fedilab.fedilabtube.R;
import app.fedilab.fedilabtube.client.APIResponse;
import app.fedilab.fedilabtube.client.entities.Error;
import app.fedilab.fedilabtube.client.entities.Oauth;
import app.fedilab.fedilabtube.client.entities.OauthParams;
import app.fedilab.fedilabtube.client.entities.Token;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.sqlite.MastodonAccountDAO;
import app.fedilab.fedilabtube.sqlite.Sqlite;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitMastodonAPI {
private final String finalUrl;
private final String finalUrl2;
private final Context _context;
private String instance;
private String token;
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 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 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, MainActivity.class);
mainActivity.putExtra(Helper.INTENT_ACTION, Helper.ADD_USER_INTENT);
activity.startActivity(mainActivity);
activity.finish();
};
mainHandler.post(myRunnable);
}).start();
}
private MastodonService init() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(finalUrl)
.addConverterFactory(GsonConverterFactory.create())
.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())
.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();
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) throws Error {
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;
}
public enum actionType {
BOOST,
UNBOOST,
FAVOURITE,
UNFAVOURITE,
BOOKMARK,
UNBOOKMARK
}
private String getToken() {
if (token != null) {
return "Bearer " + token;
} else {
return null;
}
}
}

View File

@ -0,0 +1,149 @@
package app.fedilab.fedilabtube.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.fedilabtube.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

@ -66,7 +66,6 @@ import es.dmoral.toasty.Toasty;
import static app.fedilab.fedilabtube.client.RetrofitPeertubeAPI.ActionType.MUTE;
import static app.fedilab.fedilabtube.client.RetrofitPeertubeAPI.ActionType.REPLY;
import static app.fedilab.fedilabtube.helper.Helper.isLoggedIn;
public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
@ -247,6 +246,9 @@ public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
if (context instanceof PeertubeActivity && !isThread) {
holder.binding.mainContainer.setOnClickListener(v -> ((PeertubeActivity) context).openCommentThread(comment));
holder.binding.commentContent.setOnClickListener(v -> ((PeertubeActivity) context).openCommentThread(comment));
holder.binding.replyButton.setOnClickListener(v -> ((PeertubeActivity) context).openCommentThread(comment));
} else if (context instanceof PeertubeActivity) {
holder.binding.replyButton.setOnClickListener(v -> ((PeertubeActivity) context).openPostComment(comment, i));
}
if (comment.getTotalReplies() > 0) {
holder.binding.numberOfReplies.setVisibility(View.VISIBLE);
@ -275,7 +277,11 @@ public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
String avatarUrl;
if (instance != null) {
avatarUrl = comment.getAccount().getAvatar() != null ? "https://" + instance + comment.getAccount().getAvatar().getPath() : null;
if (comment.getAccount().getAvatar() != null && comment.getAccount().getAvatar().getPath().startsWith("http")) {
avatarUrl = comment.getAccount().getAvatar().getPath();
} else {
avatarUrl = comment.getAccount().getAvatar() != null ? "https://" + instance + comment.getAccount().getAvatar().getPath() : null;
}
} else {
avatarUrl = comment.getAccount().getAvatar() != null ? comment.getAccount().getAvatar().getPath() : null;
}
@ -300,7 +306,7 @@ public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
holder.binding.postReplyButton.setVisibility(View.GONE);
}
holder.binding.postReplyButton.setOnClickListener(v -> {
if (isLoggedIn(context) && !sepiaSearch) {
if (Helper.canMakeAction(context) && !sepiaSearch) {
((PeertubeActivity) context).openPostComment(comment, i);
} else {
if (sepiaSearch) {
@ -311,9 +317,8 @@ public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
}
});
if (isLoggedIn(context) && !sepiaSearch) {
if (Helper.canMakeAction(context) && !sepiaSearch) {
holder.binding.replyButton.setVisibility(View.VISIBLE);
holder.binding.replyButton.setOnClickListener(v -> ((PeertubeActivity) context).openPostComment(comment, i));
} else {
holder.binding.replyButton.setVisibility(View.GONE);
}

View File

@ -79,7 +79,12 @@ public class OwnAccountsAdapter extends ArrayAdapter<Account> {
holder.account_un.setText(String.format("@%s", account.getAcct()));
//Profile picture
Helper.loadGiF(holder.account_pp.getContext(), "https://" + account.getHost() + account.getAvatar().getPath(), holder.account_pp);
if (account.getAvatar() != null && account.getAvatar().getPath().startsWith("http")) {
Helper.loadGiF(holder.account_pp.getContext(), account.getAvatar().getPath(), holder.account_pp);
} else {
Helper.loadGiF(holder.account_pp.getContext(), "https://" + account.getHost() + account.getAvatar().getPath(), holder.account_pp);
}
return convertView;
}

View File

@ -77,6 +77,7 @@ import es.dmoral.toasty.Toasty;
import jp.wasabeef.glide.transformations.BlurTransformation;
import static android.content.Context.DOWNLOAD_SERVICE;
import static android.content.Context.MODE_PRIVATE;
public class Helper {
@ -102,16 +103,22 @@ public class Helper {
public static final String SET_SHARE_DETAILS = "set_share_details";
public static final String NOTIFICATION_INTERVAL = "notification_interval";
public static final String LAST_NOTIFICATION_READ = "last_notification_read";
public static final String REDIRECT_CONTENT_WEB = "tubelab://backtotubelab";
public static final int DEFAULT_VIDEO_CACHE_MB = 100;
@SuppressWarnings({"unused", "RedundantSuppression"})
public static final String TAG = "mastodon_etalab";
public static final String ID = "id";
public static final String CLIENT_ID = "client_id";
public static final String CLIENT_SECRET = "client_secret";
public static final String REDIRECT_URI = "redirect_uri";
public static final String WEBSITE_VALUE = "https://fedilab.app";
public static final String CLIENT_NAME_VALUE = "TubeLab";
public static final String OAUTH_SCOPES_PEERTUBE = "openid profile";
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";
@ -337,7 +344,7 @@ public class Helper {
} else {
webView = rootView.findViewById(webviewId);
}
final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUseWideViewPort(true);
@ -416,7 +423,7 @@ public class Helper {
* @param account Account
*/
public static void logoutCurrentUser(Activity activity, Account account) {
SharedPreferences sharedpreferences = activity.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences sharedpreferences = activity.getSharedPreferences(APP_PREFS, MODE_PRIVATE);
//Current user
SQLiteDatabase db = Sqlite.getInstance(activity.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
@ -454,7 +461,7 @@ public class Helper {
* @param activity Activity
*/
public static void logoutNoRemoval(Activity activity) {
SharedPreferences sharedpreferences = activity.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences sharedpreferences = activity.getSharedPreferences(APP_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(PREF_KEY_OAUTH_TOKEN, null);
editor.putString(CLIENT_ID, null);
@ -482,11 +489,46 @@ public class Helper {
* @return boolean
*/
public static boolean isLoggedIn(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String prefKeyOauthTokenT = sharedpreferences.getString(PREF_KEY_OAUTH_TOKEN, null);
return (prefKeyOauthTokenT != null);
return isLoggedInType(context) == MainActivity.TypeOfConnection.NORMAL;
}
/**
* Some actions like following writing comment can be performed with remote accounts
*
* @param context Context
* @return boolean
*/
public static boolean canMakeAction(Context context) {
return (isLoggedInType(context) == MainActivity.TypeOfConnection.NORMAL || isLoggedInType(context) == MainActivity.TypeOfConnection.REMOTE_ACCOUNT);
}
/**
* Returns boolean depending if the user is authenticated
*
* @param context Context
* @return MainActivity.TypeOfConnection
*/
public static MainActivity.TypeOfConnection isLoggedInType(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
String prefKeyOauthTokenT = sharedpreferences.getString(PREF_KEY_OAUTH_TOKEN, null);
String prefSoftware = sharedpreferences.getString(PREF_SOFTWARE, null);
if (prefKeyOauthTokenT != null && prefSoftware == null) {
return MainActivity.TypeOfConnection.NORMAL;
} else if (prefKeyOauthTokenT != null) {
return MainActivity.TypeOfConnection.REMOTE_ACCOUNT;
} else {
return MainActivity.TypeOfConnection.UNKNOWN;
}
}
public static String getToken(Context context) {
if (isLoggedInType(context) == MainActivity.TypeOfConnection.NORMAL) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
return sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
} else {
return null;
}
}
/**
* Converts dp to pixel
@ -512,7 +554,7 @@ public class Helper {
public static boolean isOwner(Context context, Account account) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
String userName = sharedpreferences.getString(Helper.PREF_KEY_NAME, "");
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, "");
if (instance != null && userName != null) {
@ -523,7 +565,7 @@ public class Helper {
}
public static boolean isVideoOwner(Context context, VideoData.Video video) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
String userName = sharedpreferences.getString(Helper.PREF_KEY_NAME, "");
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, "");
if (video == null) {
@ -550,7 +592,7 @@ public class Helper {
if (files == null || files.size() == 0) {
return null;
}
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
int video_quality = sharedpreferences.getInt(Helper.SET_QUALITY_MODE, Helper.QUALITY_HIGH);
if (video_quality == QUALITY_HIGH) {
return files.get(0);
@ -628,4 +670,25 @@ public class Helper {
return String.format(Locale.getDefault(), "%s%s", df.format(rounded), context.getString(R.string.mb));
}
}
public static String rateSize(Context context, long size) {
if (size > 1000000000) {
float rounded = (float) size / 1000000000;
DecimalFormat df = new DecimalFormat("#.#");
return String.format(Locale.getDefault(), "%s%s", df.format(rounded), context.getString(R.string.gb));
} else if (size > 1000000) {
float rounded = (float) size / 1000000;
DecimalFormat df = new DecimalFormat("#.#");
return String.format(Locale.getDefault(), "%s%s", df.format(rounded), context.getString(R.string.mb));
} else if (size > 1000) {
float rounded = (float) size / 1000000;
DecimalFormat df = new DecimalFormat("#.#");
return String.format(Locale.getDefault(), "%s%s", df.format(rounded), context.getString(R.string.kb));
} else {
float rounded = (float) size / 1000000;
DecimalFormat df = new DecimalFormat("#.#");
return String.format(Locale.getDefault(), "%s%s", df.format(rounded), context.getString(R.string.b));
}
}
}

View File

@ -53,9 +53,14 @@ public class SwitchAccountHelper {
builderSingle.setAdapter(accountsListAdapter, (dialog, which) -> {
final AccountData.Account 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_INSTANCE, account.getHost());
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.apply();

View File

@ -51,7 +51,7 @@ public class AccountDAO {
* @param account Account
* @return boolean
*/
public boolean insertAccount(Account account) {
public boolean insertAccount(Account account, String software) {
ContentValues values = new ContentValues();
if (account.getCreatedAt() == null)
account.setCreatedAt(new Date());
@ -74,6 +74,9 @@ public class AccountDAO {
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());
@ -233,6 +236,23 @@ public class AccountDAO {
}
/**
* 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
*
@ -314,6 +334,7 @@ public class AccountDAO {
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)));
@ -354,6 +375,7 @@ public class AccountDAO {
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)));

View File

@ -0,0 +1,222 @@
package app.fedilab.fedilabtube.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.fedilabtube.client.mastodon.MastodonAccount.Account;
import app.fedilab.fedilabtube.client.entities.Token;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.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

@ -15,13 +15,19 @@ package app.fedilab.fedilabtube.sqlite;
* 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 = 3;
public static final int DB_VERSION = 4;
public static final String DB_NAME = "mastodon_etalab_db";
/***
* List of tables to manage users and data
@ -67,6 +73,7 @@ public class Sqlite extends SQLiteOpenHelper {
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, "
@ -79,8 +86,11 @@ public class Sqlite extends SQLiteOpenHelper {
+ 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 "
@ -136,15 +146,44 @@ public class Sqlite extends SQLiteOpenHelper {
@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) {
@ -153,6 +192,8 @@ public class Sqlite extends SQLiteOpenHelper {
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\"");
}
}

View File

@ -26,6 +26,7 @@ import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import app.fedilab.fedilabtube.AccountActivity;
import app.fedilab.fedilabtube.client.APIResponse;
import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.data.AccountData;
@ -63,7 +64,7 @@ public class ChannelsVM extends AndroidViewModel {
if (type == RetrofitPeertubeAPI.DataType.MY_CHANNELS) {
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 = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
String token = Helper.getToken(_mContext);
AccountData.Account account = new AccountDAO(_mContext, db).getAccountByToken(token);
finalElement = account.getUsername() + "@" + account.getHost();
}

View File

@ -97,8 +97,7 @@ public class PlaylistsVM extends AndroidViewModel {
Context _mContext = getApplication().getApplicationContext();
new Thread(() -> {
try {
SharedPreferences sharedpreferences = _mContext.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
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);
int statusCode = -1;

View File

@ -0,0 +1,116 @@
package app.fedilab.fedilabtube.viewmodel.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 android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import app.fedilab.fedilabtube.client.entities.Error;
import app.fedilab.fedilabtube.client.mastodon.RetrofitMastodonAPI;
import app.fedilab.fedilabtube.client.mastodon.Status;
public class MastodonPostActionsVM extends AndroidViewModel {
private MutableLiveData<Status> statusMutableLiveData;
public MastodonPostActionsVM(@NonNull Application application) {
super(application);
}
public LiveData<Status> post(RetrofitMastodonAPI.actionType type, Status status) {
statusMutableLiveData = new MutableLiveData<>();
postAction(type, status);
return statusMutableLiveData;
}
public LiveData<Status> comment(String url, String content) {
statusMutableLiveData = new MutableLiveData<>();
postComment(url, content);
return statusMutableLiveData;
}
public LiveData<Status> searchRemoteStatus(String url) {
statusMutableLiveData = new MutableLiveData<>();
search(url);
return statusMutableLiveData;
}
private void search(String videoURL) {
Context _mContext = getApplication().getApplicationContext();
new Thread(() -> {
try {
RetrofitMastodonAPI mastodonAPI = new RetrofitMastodonAPI(_mContext);
Status status = null;
try {
status = mastodonAPI.search(videoURL);
} catch (Error error) {
error.printStackTrace();
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Status finalStatus = status;
Runnable myRunnable = () -> statusMutableLiveData.setValue(finalStatus);
mainHandler.post(myRunnable);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
private void postComment(String videoURL, String content) {
Context _mContext = getApplication().getApplicationContext();
new Thread(() -> {
try {
RetrofitMastodonAPI mastodonAPI = new RetrofitMastodonAPI(_mContext);
Status status = null;
try {
status = mastodonAPI.commentAction(videoURL, content);
} catch (Error error) {
error.printStackTrace();
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Status finalStatus = status;
Runnable myRunnable = () -> statusMutableLiveData.setValue(finalStatus);
mainHandler.post(myRunnable);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
private void postAction(RetrofitMastodonAPI.actionType type, Status status) {
Context _mContext = getApplication().getApplicationContext();
new Thread(() -> {
try {
RetrofitMastodonAPI mastodonAPI = new RetrofitMastodonAPI(_mContext);
Status statusReply = mastodonAPI.postAction(type, status);
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> statusMutableLiveData.setValue(statusReply);
mainHandler.post(myRunnable);
} catch (Exception | Error e) {
e.printStackTrace();
}
}).start();
}
}

View File

@ -79,7 +79,7 @@ public class NotificationsWorker extends Worker {
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).getAllAccount();
List<AccountData.Account> accounts = new AccountDAO(applicationContext, db).getAllPeertubeAccount();
if (accounts == null || accounts.size() == 0) {
return Result.success();
}
@ -92,7 +92,7 @@ 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).getAllAccount();
List<AccountData.Account> accounts = new AccountDAO(getApplicationContext(), db).getAllPeertubeAccount();
SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
for (AccountData.Account account : accounts) {

View File

@ -1,8 +1,8 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="?attr/colorControlNormal"
android:viewportWidth="24"
android:tint="?attr/colorControlNormal"
android:viewportHeight="24">
<path
android:fillColor="@android:color/white"

View File

@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="?attr/colorControlNormal"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@android:color/white"
android:pathData="M7,7h10v3l4,-4 -4,-4v3L5,5v6h2L7,7zM17,17L7,17v-3l-4,4 4,4v-3h12v-6h-2v4z" />
</vector>

View File

@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="?attr/colorControlNormal"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@android:color/white"
android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z" />
</vector>

View File

@ -159,6 +159,16 @@
app:tabTextColor="@android:color/white" />
</com.google.android.material.appbar.AppBarLayout>
<TextView
android:id="@+id/remote_account"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:autoLink="web"
android:gravity="center"
android:textSize="16sp"
android:visibility="gone" />
<androidx.viewpager.widget.ViewPager
android:id="@+id/account_viewpager"
@ -175,5 +185,6 @@
android:layout_margin="@dimen/fab_margin_button"
android:src="@drawable/ic_baseline_add_24"
android:tint="@android:color/white"
android:visibility="gone" />
android:visibility="gone"
tools:ignore="ContentDescription" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View File

@ -49,7 +49,6 @@
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.github.vkay94.dtpv.DoubleTapPlayerView
android:id="@+id/doubleTapPlayerView"
android:animateLayoutChanges="true"
@ -67,6 +66,15 @@
app:yt_playerView="@+id/doubleTapPlayerView"
android:gravity="center" />
<ImageView
android:id="@+id/watermark"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_gravity="top|start"
android:contentDescription="@string/watermark"
android:scaleType="fitCenter"
android:visibility="gone" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/cast_controller"
android:layout_width="match_parent"
@ -264,6 +272,54 @@
app:drawableTopCompat="@drawable/ic_baseline_thumb_down_alt_24"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/peertube_reblog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:drawablePadding="5dp"
android:gravity="center_horizontal"
android:text="0"
android:visibility="gone"
app:drawableTopCompat="@drawable/ic_baseline_repeat_24"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/peertube_favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:drawablePadding="5dp"
android:gravity="center_horizontal"
android:text="0"
android:visibility="gone"
app:drawableTopCompat="@drawable/ic_baseline_star_24"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/peertube_bookmark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:drawablePadding="5dp"
android:gravity="center_horizontal"
android:text=""
android:visibility="gone"
app:drawableTopCompat="@drawable/ic_baseline_bookmark_24"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/peertube_playlist"

View File

@ -83,7 +83,6 @@
android:layout_height="wrap_content"
android:labelFor="@+id/p_video_tags"
android:text="@string/tags" />
<mabbas007.tagsedittext.TagsEditText
android:id="@+id/p_video_tags"
android:layout_width="match_parent"
@ -93,8 +92,9 @@
android:minLines="2"
TagsEditText:allowSpaceInTag="true"
TagsEditText:tagsCloseImagePadding="@dimen/defaultTagsCloseImagePadding"
TagsEditText:tagsBackground="?colorAccent"
TagsEditText:tagsCloseImageRight="@drawable/tag_close"
TagsEditText:tagsTextColor="?colorAccent"
TagsEditText:tagsTextColor="@color/white"
TagsEditText:tagsTextSize="@dimen/defaultTagsTextSize" />
</LinearLayout>

View File

@ -55,6 +55,44 @@
</LinearLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/torrent_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="@+id/seekbar_controller"
app:layout_constraintEnd_toEndOf="parent">
<TextView
android:id="@+id/dowload_rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:textColor="#FFBEBEBE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/upload_rate"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/upload_rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:textColor="#FFBEBEBE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/peers_number"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/peers_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:textColor="#FFBEBEBE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<LinearLayout
android:id="@+id/seekbar_controller"
app:layout_constraintBottom_toBottomOf="parent"

View File

@ -135,6 +135,9 @@
<string name="action_follow">Subscribe</string>
<string name="action_mute">كتم</string>
<string name="unlimited">Unlimited</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -353,4 +356,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -131,6 +131,9 @@
<string name="action_follow">Abonnieren</string>
<string name="action_mute">Lautlos</string>
<string name="unlimited">Unbegrenzt</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Gesamtes Video-Kontingent</string>
@ -349,4 +352,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -131,6 +131,9 @@
<string name="action_follow">Subscribe</string>
<string name="action_mute">Σίγαση</string>
<string name="unlimited">Unlimited</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -348,4 +351,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -131,6 +131,9 @@
<string name="action_follow">Subscribe</string>
<string name="action_mute">Silenciar</string>
<string name="unlimited">Unlimited</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -349,4 +352,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -131,6 +131,9 @@
<string name="action_follow">S\'abonner</string>
<string name="action_mute">Masquer</string>
<string name="unlimited">Illimité</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">Mo</string>
<string name="gb">Go</string>
<string name="total_video_quota">Quota vidéo total</string>
@ -276,7 +279,7 @@
<string name="report_account">Signaler le compte</string>
<string-array name="settings_video_mode">
<item>Normal</item>
<item>Torrent</item>
<item>Navigateur</item>
<item>Magnet</item>
<item>Torrent</item>
</string-array>
@ -349,4 +352,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -131,6 +131,9 @@
<string name="action_follow">Iscriviti</string>
<string name="action_mute">Silenzia</string>
<string name="unlimited">Illimitato</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -349,4 +352,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -130,6 +130,9 @@
<string name="action_follow">Subscribe</string>
<string name="action_mute">ミュート</string>
<string name="unlimited">Unlimited</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -348,4 +351,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -130,6 +130,9 @@
<string name="action_follow">Subscribe</string>
<string name="action_mute">뮤트</string>
<string name="unlimited">Unlimited</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -348,4 +351,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -1,15 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
<string name="set_cast">Enable Chromecast (beta)</string>
<string name="please_wait">Please wait</string>
<string name="set_cast_description">Allow to discover Chromecast devices on the network.</string>
<string name="set_video_in_list">Video lijst</string>
<string name="set_cast">Chromecast (beta) inschakelen</string>
<string name="please_wait">Even geduld aub</string>
<string name="set_cast_description">Detecteren van Chromecast apparaten op het netwerk toestaan.</string>
<string name="set_video_in_list">Videos in lijst</string>
<string name="set_video_in_list_description">Wijzig de lay-out voor het weergeven van video\'s in een lijst</string>
<string name="no_instances">Geen instanties !</string>
<string name="show_more">Meer weergeven</string>
<string name="show_less">Minder weergeven</string>
<string name="cast">ChromeCast</string>
<string name="chromecast_choice">ChromeCast choice</string>
<string name="chromecast_choice">ChromeCast keuze</string>
<string name="set_play_screen_lock">Schermvergrendeling</string>
<string name="set_play_screen_lock_description">Video\'s laten doorspelen terwijl het scherm vergrendeld is</string>
<string name="save">Opslaan</string>
@ -23,7 +23,7 @@
<string name="set_autoplay_next_video">De volgende video automatisch afspelen</string>
<string name="set_autoplay_next_video_description">Wanneer een video eindigt, begin dan met de volgende voorgestelde video.</string>
<string name="add_public_reply">Voeg een openbaar antwoord toe</string>
<string name="originally_published">Originally published</string>
<string name="originally_published">Oorspronkelijk gepubliceerd op</string>
<string name="activity">Activiteit</string>
<string name="app">App</string>
<string name="notif_new_video">Nieuwe video uit uw abonnementen</string>
@ -87,9 +87,9 @@
<item>6 uren</item>
<item>12 uren</item>
</string-array>
<string name="_retry">Retry</string>
<string name="refresh_token_failed">Token refresh failed!</string>
<string name="refresh_token_failed_message">You can retry this action or simply disconnect the current account</string>
<string name="_retry">Opnieuw proberen</string>
<string name="refresh_token_failed">Token vernieuwen mislukt!</string>
<string name="refresh_token_failed_message">U kunt deze actie opnieuw uitproberen of het huidige account gewoon loskoppelen</string>
<string name="yes">Ja</string>
<string name="no">Geen</string>
<string name="cancel">Annuleren</string>
@ -128,15 +128,18 @@
<string name="toast_error_loading_account">Er ging wat mis tijdens het omschakelen van accounts!</string>
<string name="toast_error_search">Er ging wat mis tijdens het zoeken!</string>
<string name="nothing_to_do">Er valt niets te doen</string>
<string name="action_follow">Subscribe</string>
<string name="action_follow">Abonneren</string>
<string name="action_mute">Negeren</string>
<string name="unlimited">Unlimited</string>
<string name="unlimited">Onbeperkt</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
<string name="daily_video_quota">Daily video quota</string>
<string name="nsfw_title_warning">Mature or explicit content</string>
<string name="nsfw_message_warning">This video contains mature or explicit content. Are you sure you want to watch it?</string>
<string name="total_video_quota">Totaal videoquotum</string>
<string name="daily_video_quota">Dagelijks videoquotum</string>
<string name="nsfw_title_warning">Expliciete inhoud, of inhoud voor volwassenen</string>
<string name="nsfw_message_warning">Deze video bevat volwassen of expliciete inhoud. Weet u zeker dat u deze wilt bekijken?</string>
<string name="search">Zoek</string>
<string name="delete">Verwijderen</string>
<string name="action_lists_confirm_delete">Weet je zeker dat je deze lijst definitief wilt verwijderen?</string>
@ -236,10 +239,10 @@
<string name="send_comment">Reactie versturen</string>
<string name="all">Alle</string>
<!-- end languages -->
<string name="playback_speed">Playback speed</string>
<string name="playback_speed">Afspeelsnelheid</string>
<string name="normal">Normaal</string>
<string name="delete_history">Delete videos history</string>
<string name="delete_history_confirm">Are you sure you want to delete all your videos history?</string>
<string name="delete_history">Videogeschiedenis verwijderen</string>
<string name="delete_history_confirm">Weet je zeker dat je al je video geschiedenis wil verwijderen?</string>
<string name="export_list">Exporteren</string>
<string name="import_list">Importeren</string>
<string name="export_notification_title">Export succesvol!</string>
@ -296,7 +299,7 @@
<string name="agreement_check_peertube">Ik ben minstens 16 jaar oud en ga akkoord met de %1$s van dit geval</string>
<string name="edit_profile">Profiel bewerken</string>
<string name="make_an_action">Maak een actie</string>
<string name="action_unfollow">Unsubscribe</string>
<string name="action_unfollow">Abonnement beëindigen</string>
<string name="display_nsfw_videos">Gevoelige video\'s weergeven</string>
<string name="fullscreen">Volledig scherm</string>
<string name="bookmark_peertube_empty">Er zijn geen video\'s in uw favorieten!</string>
@ -347,6 +350,11 @@
<string name="set_video_language">Taalfilter</string>
<string name="set_video_language_description">Filtervideo\'s met verschillende talen</string>
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="live_not_started">Deze live is nog niet gestart!</string>
<string name="remote_account">Account van een ander netwerk!</string>
<string name="instance_not_availabe">Instantie is niet beschikbaar!</string>
<string name="max_tag_size">De video mag niet meer dan 5 tags hebben!</string>
<string name="watermark">Watermerk</string>
<string name="toast_code_error">Er is een fout opgetreden! De instantie gaf geen autorisatiecode terug!</string>
<string name="remote_account_from"><b>%1$s</b> extern account verbonden met de app.\n\nU kunt doorgaan naar bepaalde acties.</string>
</resources>

View File

@ -133,6 +133,9 @@
<string name="action_follow">Subskrybuj</string>
<string name="action_mute">Wycisz</string>
<string name="unlimited">Bez ograniczeń</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Całkowity limit filmów</string>
@ -351,4 +354,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -131,6 +131,9 @@
<string name="action_follow">Subscribe</string>
<string name="action_mute">Silenciar</string>
<string name="unlimited">Unlimited</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -349,4 +352,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -132,6 +132,9 @@
<string name="action_follow">Subscribe</string>
<string name="action_mute">Mod silențios</string>
<string name="unlimited">Unlimited</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -350,4 +353,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -1,15 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
<string name="set_cast">Enable Chromecast (beta)</string>
<string name="please_wait">Please wait</string>
<string name="set_cast_description">Allow to discover Chromecast devices on the network.</string>
<string name="set_cast">Включить Chromecast (бета-версия)</string>
<string name="please_wait">Пожалуйста подождите</string>
<string name="set_cast_description">Позволяет обнаружить устройства Chromecast в сети.</string>
<string name="set_video_in_list">Видео в списке</string>
<string name="set_video_in_list_description">Изменить расположение для отображения видео в списке</string>
<string name="no_instances">Нет экземпляров !</string>
<string name="show_more">Показать еще</string>
<string name="show_less">Показать меньше</string>
<string name="cast">ChromeCast</string>
<string name="chromecast_choice">ChromeCast choice</string>
<string name="chromecast_choice">Выбор ChromeCast</string>
<string name="set_play_screen_lock">Блокировка экрана</string>
<string name="set_play_screen_lock_description">Продолжать воспроизведение видео, когда экран заблокирован</string>
<string name="save">Сохранить</string>
@ -133,6 +133,9 @@
<string name="action_follow">Подписка</string>
<string name="action_mute">Игнорировать</string>
<string name="unlimited">Без ограничений</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">МБ</string>
<string name="gb">ГБ</string>
<string name="total_video_quota">Общая квота видео</string>
@ -348,7 +351,12 @@
<string name="set_video_minimize_description">Уменьшить размер видео, когда приложение находится в фоновом режиме (Android N+)</string>
<string name="set_video_language">Добавить языковой фильтр</string>
<string name="set_video_language_description">Фильтровать видео с разными языками</string>
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="live">Прямой эфир</string>
<string name="live_not_started">Этот прямой эфир ещё не начался!</string>
<string name="remote_account">Аккаунт из другой сети!</string>
<string name="instance_not_availabe">Экземпляр недоступен!</string>
<string name="max_tag_size">На видео не должно быть более 5 тегов!</string>
<string name="watermark">Водяной знак</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -131,6 +131,9 @@
<string name="action_follow">Subscribe</string>
<string name="action_mute">Tysta</string>
<string name="unlimited">Unlimited</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -349,4 +352,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -130,6 +130,9 @@
<string name="action_follow">Subscribe</string>
<string name="action_mute">静言</string>
<string name="unlimited">Unlimited</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -347,4 +350,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -130,6 +130,9 @@
<string name="action_follow">Subscribe</string>
<string name="action_mute">靜音</string>
<string name="unlimited">Unlimited</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -348,4 +351,9 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -170,6 +170,10 @@
<string name="action_mute">Mute</string>
<string name="unlimited">Unlimited</string>
<string name="peers">%1$d Peers</string>
<string name="b">B</string>
<string name="kb">KB</string>
<string name="mb">MB</string>
<string name="gb">GB</string>
<string name="total_video_quota">Total video quota</string>
@ -446,4 +450,10 @@
<string name="live">Live</string>
<string name="live_not_started">This live has not started!</string>
<string name="remote_account">Account from another network!</string>
<string name="instance_not_availabe">Instance is not available!</string>
<string name="max_tag_size">The video should not have more than 5 tags!</string>
<string name="watermark">Watermark</string>
<string name="toast_code_error">An error occurred! The instance did not return an authorisation code!</string>
<string name="remote_account_from"><b>%1$s</b> remote account connected with the app.\n\nYou can proceed to some limited actions.</string>
</resources>

View File

@ -7,6 +7,8 @@
<color name="tag_color">#bb864692</color>
<color name="tag_color_text">#FAFAFA</color>
<color name="positive_thumbs">#2b90d9</color>
<color name="favorite">#ca8f04</color>
<color name="bookmark">#795548</color>
<color name="negative_thumbs">#F44336</color>
<color name="backgroundDark">#DD000000</color>
<color name="red_1">#F44336</color>

View File

@ -9,6 +9,8 @@ buildscript {
classpath 'com.android.tools.build:gradle:4.1.1'
def nav_version = "2.3.0"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
classpath 'de.undercouch:gradle-download-task:4.0.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}

View File

@ -1,2 +1,3 @@
include ':torrentStream'
include ':app'
rootProject.name = "Fedilab Tube"

View File

@ -0,0 +1,12 @@
Added:
- Allow to connect Mastodon or Pleroma accounts
- Videos can be reblogged, added to favorites or bookmarked (with undo actions)
- For torrent mode: display download, upload rates with number of seeders
- Watermarks (from plugins) are displayed at the top left of videos.
Changed:
- Restrict videos to 5 tags
- Change message when an instance is not available
Fixed:
- Some crashes

1
torrentStream/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build

View File

@ -0,0 +1,73 @@
/*
* Copyright (C) 2015-2018 Sébastiaan (github.com/se-bastiaan)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
apply plugin: 'de.undercouch.download'
group='com.github.TorrentStream'
android {
compileSdkVersion 30
defaultConfig {
minSdkVersion 15
targetSdkVersion 30
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
abortOnError true
}
}
ext {
libtorrentVersion = '1.2.11.0'
}
// Custom task which downloads the appropriate version of JAR files for jlibtorrent
task downloadDependencies(type: Download) {
def baseUrl = "https://github.com/frostwire/frostwire-jlibtorrent" +
"/releases/download/release%2F$libtorrentVersion"
def platforms = ['arm', 'arm64', 'x86', 'x86_64']
def urls = platforms.collect { "$baseUrl/jlibtorrent-android-$it-${libtorrentVersion}.jar" }
urls.add("$baseUrl/jlibtorrent-${libtorrentVersion}.jar")
src urls
dest 'libs'
overwrite false
}
// Add our custom task as a dependency to the build
// You may need to run gradle sync for IDE warnings to disappear
preBuild.dependsOn(downloadDependencies)
// Add deletion of libs folder to clean task
clean {
delete 'libs'
}
dependencies {
api fileTree(dir: 'libs', include: ['*.jar'])
implementation fileTree(dir: "libs", include: ["*.jar"])
}

Binary file not shown.

17
torrentStream/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/Sebastiaan/Development/Android/SDK/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@ -0,0 +1,3 @@
<manifest package="com.github.se_bastiaan.torrentstream">
</manifest>

View File

@ -0,0 +1,33 @@
/*
* Copyright (C) 2015-2018 Sébastiaan (github.com/se-bastiaan)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.se_bastiaan.torrentstream;
public class StreamStatus {
public final float progress;
public final int bufferProgress;
public final int seeds;
public final int peers;
public final int downloadSpeed;
StreamStatus(float progress, int bufferProgress, int seeds, int peers, int downloadSpeed) {
this.progress = progress;
this.bufferProgress = bufferProgress;
this.seeds = seeds;
this.peers = peers;
this.downloadSpeed = downloadSpeed;
}
}

View File

@ -0,0 +1,527 @@
/*
* Copyright (C) 2015-2018 Sébastiaan (github.com/se-bastiaan)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.se_bastiaan.torrentstream;
import com.frostwire.jlibtorrent.AlertListener;
import com.frostwire.jlibtorrent.FileStorage;
import com.frostwire.jlibtorrent.Priority;
import com.frostwire.jlibtorrent.TorrentFlags;
import com.frostwire.jlibtorrent.TorrentHandle;
import com.frostwire.jlibtorrent.TorrentInfo;
import com.frostwire.jlibtorrent.TorrentStatus;
import com.frostwire.jlibtorrent.alerts.Alert;
import com.frostwire.jlibtorrent.alerts.AlertType;
import com.frostwire.jlibtorrent.alerts.BlockFinishedAlert;
import com.frostwire.jlibtorrent.alerts.PieceFinishedAlert;
import com.github.se_bastiaan.torrentstream.listeners.TorrentListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Torrent implements AlertListener {
private final static Integer MAX_PREPARE_COUNT = 20;
private final static Integer MIN_PREPARE_COUNT = 2;
private final static Integer DEFAULT_PREPARE_COUNT = 5;
private final static Integer SEQUENTIAL_CONCURRENT_PIECES_COUNT = 5;
private final List<WeakReference<TorrentInputStream>> torrentStreamReferences;
private final TorrentHandle torrentHandle;
private final TorrentListener listener;
private final Long prepareSize;
private Integer piecesToPrepare;
private Integer lastPieceIndex;
private Integer firstPieceIndex;
private Integer selectedFileIndex = -1;
private Integer interestedPieceIndex = 0;
private Double prepareProgress = 0d;
private Double progressStep = 0d;
private List<Integer> preparePieces;
private Boolean[] hasPieces;
private State state = State.RETRIEVING_META;
/**
* The constructor for a new Torrent
* <p/>
* First the largest file in the download is selected as the file for playback
* <p/>
* After setting this priority, the first and last index of the pieces that make up this file are determined.
* And last: amount of pieces that are needed for playback are calculated (needed for playback means: make up 10 megabyte of the file)
*
* @param torrentHandle jlibtorrent TorrentHandle
*/
public Torrent(TorrentHandle torrentHandle, TorrentListener listener, Long prepareSize) {
this.torrentHandle = torrentHandle;
this.listener = listener;
this.prepareSize = prepareSize;
torrentStreamReferences = new ArrayList<>();
if (selectedFileIndex == -1) {
setLargestFile();
}
if (this.listener != null) {
this.listener.onStreamPrepared(this);
}
}
/**
* Reset piece priorities of selected file to normal
*/
private void resetPriorities() {
Priority[] priorities = torrentHandle.piecePriorities();
for (int i = 0; i < priorities.length; i++) {
if (i >= firstPieceIndex && i <= lastPieceIndex) {
torrentHandle.piecePriority(i, Priority.NORMAL);
} else {
torrentHandle.piecePriority(i, Priority.IGNORE);
}
}
}
/**
* Get LibTorrent torrent handle of this torrent
*
* @return {@link TorrentHandle}
*/
public TorrentHandle getTorrentHandle() {
return torrentHandle;
}
public File getVideoFile() {
return new File(torrentHandle.savePath() + "/" + torrentHandle.torrentFile().files().filePath(selectedFileIndex));
}
/**
* Get an InputStream for the video file.
* Read is be blocked until the requested piece(s) is downloaded.
*
* @return {@link InputStream}
*/
public InputStream getVideoStream() throws FileNotFoundException {
File file = getVideoFile();
TorrentInputStream inputStream = new TorrentInputStream(this, new FileInputStream(file));
torrentStreamReferences.add(new WeakReference<>(inputStream));
return inputStream;
}
/**
* Get the location of the file that is being downloaded
*
* @return {@link File} The file location
*/
public File getSaveLocation() {
return new File(torrentHandle.savePath() + "/" + torrentHandle.name());
}
/**
* Resume the torrent download
*/
public void resume() {
torrentHandle.resume();
}
/**
* Pause the torrent download
*/
public void pause() {
torrentHandle.pause();
}
/**
* Set the selected file index to the largest file in the torrent
*/
public void setLargestFile() {
setSelectedFileIndex(-1);
}
/**
* Set the index of the file that should be downloaded
* If the given index is -1, then the largest file is chosen
*
* @param selectedFileIndex {@link Integer} Index of the file
*/
public void setSelectedFileIndex(Integer selectedFileIndex) {
TorrentInfo torrentInfo = torrentHandle.torrentFile();
FileStorage fileStorage = torrentInfo.files();
if (selectedFileIndex == -1) {
long highestFileSize = 0;
int selectedFile = -1;
for (int i = 0; i < fileStorage.numFiles(); i++) {
long fileSize = fileStorage.fileSize(i);
if (highestFileSize < fileSize) {
highestFileSize = fileSize;
torrentHandle.filePriority(selectedFile, Priority.IGNORE);
selectedFile = i;
torrentHandle.filePriority(i, Priority.NORMAL);
} else {
torrentHandle.filePriority(i, Priority.IGNORE);
}
}
selectedFileIndex = selectedFile;
} else {
for (int i = 0; i < fileStorage.numFiles(); i++) {
if (i == selectedFileIndex) {
torrentHandle.filePriority(i, Priority.NORMAL);
} else {
torrentHandle.filePriority(i, Priority.IGNORE);
}
}
}
this.selectedFileIndex = selectedFileIndex;
Priority[] piecePriorities = torrentHandle.piecePriorities();
int firstPieceIndexLocal = -1;
int lastPieceIndexLocal = -1;
for (int i = 0; i < piecePriorities.length; i++) {
if (piecePriorities[i] != Priority.IGNORE) {
if (firstPieceIndexLocal == -1) {
firstPieceIndexLocal = i;
}
piecePriorities[i] = Priority.IGNORE;
} else {
if (firstPieceIndexLocal != -1 && lastPieceIndexLocal == -1) {
lastPieceIndexLocal = i - 1;
}
}
}
if (lastPieceIndexLocal == -1) {
lastPieceIndexLocal = piecePriorities.length - 1;
}
int pieceCount = lastPieceIndexLocal - firstPieceIndexLocal + 1;
int pieceLength = torrentHandle.torrentFile().pieceLength();
int activePieceCount;
if (pieceLength > 0) {
activePieceCount = (int) (prepareSize / pieceLength);
if (activePieceCount < MIN_PREPARE_COUNT) {
activePieceCount = MIN_PREPARE_COUNT;
} else if (activePieceCount > MAX_PREPARE_COUNT) {
activePieceCount = MAX_PREPARE_COUNT;
}
} else {
activePieceCount = DEFAULT_PREPARE_COUNT;
}
if (pieceCount < activePieceCount) {
activePieceCount = pieceCount / 2;
}
this.firstPieceIndex = firstPieceIndexLocal;
this.interestedPieceIndex = this.firstPieceIndex;
this.lastPieceIndex = lastPieceIndexLocal;
piecesToPrepare = activePieceCount;
}
/**
* Get the filenames of the files in the torrent
*
* @return {@link String[]}
*/
public String[] getFileNames() {
FileStorage fileStorage = torrentHandle.torrentFile().files();
String[] fileNames = new String[fileStorage.numFiles()];
for (int i = 0; i < fileStorage.numFiles(); i++) {
fileNames[i] = fileStorage.fileName(i);
}
return fileNames;
}
/**
* Prepare torrent for playback. Prioritize the first {@code piecesToPrepare} pieces and the last {@code piecesToPrepare} pieces
* from {@code firstPieceIndex} and {@code lastPieceIndex}. Ignore all other pieces.
*/
public void startDownload() {
if (state == State.STREAMING || state == State.STARTING) return;
state = State.STARTING;
List<Integer> indices = new ArrayList<>();
Priority[] priorities = torrentHandle.piecePriorities();
for (int i = 0; i < priorities.length; i++) {
if (priorities[i] != Priority.IGNORE) {
torrentHandle.piecePriority(i, Priority.NORMAL);
}
}
for (int i = 0; i < piecesToPrepare; i++) {
indices.add(lastPieceIndex - i);
torrentHandle.piecePriority(lastPieceIndex - i, Priority.SEVEN);
torrentHandle.setPieceDeadline(lastPieceIndex - i, 1000);
}
for (int i = 0; i < piecesToPrepare; i++) {
indices.add(firstPieceIndex + i);
torrentHandle.piecePriority(firstPieceIndex + i, Priority.SEVEN);
torrentHandle.setPieceDeadline(firstPieceIndex + i, 1000);
}
preparePieces = indices;
hasPieces = new Boolean[lastPieceIndex - firstPieceIndex + 1];
Arrays.fill(hasPieces, false);
TorrentInfo torrentInfo = torrentHandle.torrentFile();
TorrentStatus status = torrentHandle.status();
double blockCount = indices.size() * torrentInfo.pieceLength() / status.blockSize();
progressStep = 100 / blockCount;
torrentStreamReferences.clear();
torrentHandle.resume();
listener.onStreamStarted(this);
}
/**
* Check if the piece that contains the specified bytes were downloaded already
*
* @param bytes The bytes you're interested in
* @return {@code true} if downloaded, {@code false} if not
*/
public boolean hasBytes(long bytes) {
if (hasPieces == null) {
return false;
}
int pieceIndex = (int) (bytes / torrentHandle.torrentFile().pieceLength());
return hasPieces[pieceIndex];
}
/**
* Set the bytes of the selected file that you're interested in
* The piece of that specific offset is selected and that piece plus the 1 preceding and the 3 after it.
* These pieces will then be prioritised, which results in continuing the sequential download after that piece
*
* @param bytes The bytes you're interested in
*/
public void setInterestedBytes(long bytes) {
if (hasPieces == null && bytes >= 0) {
return;
}
int pieceIndex = (int) (bytes / torrentHandle.torrentFile().pieceLength());
interestedPieceIndex = pieceIndex;
if (!hasPieces[pieceIndex] && torrentHandle.piecePriority(pieceIndex + firstPieceIndex) != Priority.SEVEN) {
interestedPieceIndex = pieceIndex;
int pieces = 5;
for (int i = pieceIndex; i < hasPieces.length; i++) {
// Set full priority to first found piece that is not confirmed finished
if (!hasPieces[i]) {
torrentHandle.piecePriority(i + firstPieceIndex, Priority.SEVEN);
torrentHandle.setPieceDeadline(i + firstPieceIndex, 1000);
pieces--;
if (pieces == 0) {
break;
}
}
}
}
}
/**
* Checks if the interesting pieces are downloaded already
*
* @return {@code true} if the 5 pieces that were selected using `setInterestedBytes` are all reported complete including the `nextPieces`, {@code false} if not
*/
public boolean hasInterestedBytes(int nextPieces) {
for (int i = 0; i < 5 + nextPieces; i++) {
int index = interestedPieceIndex + i;
if (hasPieces.length <= index || index < 0) {
continue;
}
if (!hasPieces[interestedPieceIndex + i]) {
return false;
}
}
return true;
}
/**
* Checks if the interesting pieces are downloaded already
*
* @return {@code true} if the 5 pieces that were selected using `setInterestedBytes` are all reported complete, {@code false} if not
*/
public boolean hasInterestedBytes() {
return hasInterestedBytes(5);
}
/**
* Get the index of the piece we're currently interested in
*
* @return Interested piece index
*/
public int getInterestedPieceIndex() {
return interestedPieceIndex;
}
/**
* Get amount of pieces to prepare
*
* @return Amount of pieces to prepare
*/
public Integer getPiecesToPrepare() {
return piecesToPrepare;
}
/**
* Start sequential mode downloading
*/
private void startSequentialMode() {
resetPriorities();
if (hasPieces == null) {
torrentHandle.setFlags(torrentHandle.flags().and_(TorrentFlags.SEQUENTIAL_DOWNLOAD));
} else {
for (int i = firstPieceIndex + piecesToPrepare; i < firstPieceIndex + piecesToPrepare + SEQUENTIAL_CONCURRENT_PIECES_COUNT; i++) {
torrentHandle.piecePriority(i, Priority.SEVEN);
torrentHandle.setPieceDeadline(i, 1000);
}
}
}
/**
* Get current torrent state
*
* @return {@link State}
*/
public State getState() {
return state;
}
/**
* Piece finished
*
* @param alert
*/
private void pieceFinished(PieceFinishedAlert alert) {
if (state == State.STREAMING && hasPieces != null) {
int pieceIndex = alert.pieceIndex() - firstPieceIndex;
hasPieces[pieceIndex] = true;
if (pieceIndex >= interestedPieceIndex) {
for (int i = pieceIndex; i < hasPieces.length; i++) {
// Set full priority to first found piece that is not confirmed finished
if (!hasPieces[i]) {
torrentHandle.piecePriority(i + firstPieceIndex, Priority.SEVEN);
torrentHandle.setPieceDeadline(i + firstPieceIndex, 1000);
break;
}
}
}
} else {
Iterator<Integer> piecesIterator = preparePieces.iterator();
while (piecesIterator.hasNext()) {
int index = piecesIterator.next();
if (index == alert.pieceIndex()) {
piecesIterator.remove();
}
}
if (hasPieces != null) {
hasPieces[alert.pieceIndex() - firstPieceIndex] = true;
}
if (preparePieces.size() == 0) {
startSequentialMode();
prepareProgress = 100d;
sendStreamProgress();
state = State.STREAMING;
if (listener != null) {
listener.onStreamReady(this);
}
}
}
}
private void blockFinished(BlockFinishedAlert alert) {
for (Integer index : preparePieces) {
if (index == alert.pieceIndex()) {
prepareProgress += progressStep;
break;
}
}
sendStreamProgress();
}
private void sendStreamProgress() {
TorrentStatus status = torrentHandle.status();
float progress = status.progress() * 100;
int seeds = status.numSeeds();
int peers = status.numPeers();
int downloadSpeed = status.downloadPayloadRate();
if (listener != null && prepareProgress >= 1) {
listener.onStreamProgress(this, new StreamStatus(progress, prepareProgress.intValue(), seeds, peers, downloadSpeed));
}
}
@Override
public int[] types() {
return new int[]{
AlertType.PIECE_FINISHED.swig(),
AlertType.BLOCK_FINISHED.swig()
};
}
@Override
public void alert(Alert<?> alert) {
switch (alert.type()) {
case PIECE_FINISHED:
pieceFinished((PieceFinishedAlert) alert);
break;
case BLOCK_FINISHED:
blockFinished((BlockFinishedAlert) alert);
break;
default:
break;
}
Iterator<WeakReference<TorrentInputStream>> i = torrentStreamReferences.iterator();
while (i.hasNext()) {
WeakReference<TorrentInputStream> reference = i.next();
TorrentInputStream inputStream = reference.get();
if (inputStream == null) {
i.remove();
continue;
}
inputStream.alert(alert);
}
}
public enum State {UNKNOWN, RETRIEVING_META, STARTING, STREAMING}
}

View File

@ -0,0 +1,116 @@
package com.github.se_bastiaan.torrentstream;
import com.frostwire.jlibtorrent.AlertListener;
import com.frostwire.jlibtorrent.alerts.Alert;
import com.frostwire.jlibtorrent.alerts.AlertType;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
class TorrentInputStream extends FilterInputStream implements AlertListener {
private final Torrent torrent;
private boolean stopped;
private long location;
TorrentInputStream(Torrent torrent, InputStream inputStream) {
super(inputStream);
this.torrent = torrent;
}
@Override
protected void finalize() throws Throwable {
synchronized (this) {
stopped = true;
notifyAll();
}
super.finalize();
}
private synchronized boolean waitForPiece(long offset) {
while (!Thread.currentThread().isInterrupted() && !stopped) {
try {
if (torrent.hasBytes(offset)) {
return true;
}
wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
return false;
}
@Override
public synchronized int read() throws IOException {
if (!waitForPiece(location)) {
return -1;
}
location++;
return super.read();
}
@Override
public synchronized int read(byte[] buffer, int offset, int length) throws IOException {
int pieceLength = torrent.getTorrentHandle().torrentFile().pieceLength();
for (int i = 0; i < length; i += pieceLength) {
if (!waitForPiece(location + i)) {
return -1;
}
}
location += length;
return super.read(buffer, offset, length);
}
@Override
public void close() throws IOException {
synchronized (this) {
stopped = true;
notifyAll();
}
super.close();
}
@Override
public synchronized long skip(long n) throws IOException {
location += n;
return super.skip(n);
}
@Override
public boolean markSupported() {
return false;
}
private synchronized void pieceFinished() {
notifyAll();
}
@Override
public int[] types() {
return new int[]{
AlertType.PIECE_FINISHED.swig(),
};
}
@Override
public void alert(Alert<?> alert) {
switch (alert.type()) {
case PIECE_FINISHED:
pieceFinished();
break;
default:
break;
}
}
}

View File

@ -0,0 +1,151 @@
/*
* Copyright (C) 2015-2018 Sébastiaan (github.com/se-bastiaan)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.se_bastiaan.torrentstream;
import java.io.File;
public final class TorrentOptions {
String saveLocation = "/";
String proxyHost;
String proxyUsername;
String proxyPassword;
String peerFingerprint;
Integer maxDownloadSpeed = 0;
Integer maxUploadSpeed = 0;
Integer maxConnections = 200;
Integer maxDht = 88;
Integer listeningPort = -1;
Boolean removeFiles = false;
Boolean anonymousMode = false;
Boolean autoDownload = true;
Long prepareSize = 15 * 1024L * 1024L;
private TorrentOptions() {
// Unused
}
private TorrentOptions(TorrentOptions torrentOptions) {
this.saveLocation = torrentOptions.saveLocation;
this.proxyHost = torrentOptions.proxyHost;
this.proxyUsername = torrentOptions.proxyUsername;
this.proxyPassword = torrentOptions.proxyPassword;
this.peerFingerprint = torrentOptions.peerFingerprint;
this.maxDownloadSpeed = torrentOptions.maxDownloadSpeed;
this.maxUploadSpeed = torrentOptions.maxUploadSpeed;
this.maxConnections = torrentOptions.maxConnections;
this.maxDht = torrentOptions.maxDht;
this.listeningPort = torrentOptions.listeningPort;
this.removeFiles = torrentOptions.removeFiles;
this.anonymousMode = torrentOptions.anonymousMode;
this.autoDownload = torrentOptions.autoDownload;
this.prepareSize = torrentOptions.prepareSize;
}
public Builder toBuilder() {
return new Builder(this);
}
public static class Builder {
private TorrentOptions torrentOptions;
public Builder() {
torrentOptions = new TorrentOptions();
}
private Builder(TorrentOptions torrentOptions) {
torrentOptions = new TorrentOptions(torrentOptions);
}
public Builder saveLocation(String saveLocation) {
torrentOptions.saveLocation = saveLocation;
return this;
}
public Builder saveLocation(File saveLocation) {
torrentOptions.saveLocation = saveLocation.getAbsolutePath();
return this;
}
public Builder maxUploadSpeed(Integer maxUploadSpeed) {
torrentOptions.maxUploadSpeed = maxUploadSpeed;
return this;
}
public Builder maxDownloadSpeed(Integer maxDownloadSpeed) {
torrentOptions.maxDownloadSpeed = maxDownloadSpeed;
return this;
}
public Builder maxConnections(Integer maxConnections) {
torrentOptions.maxConnections = maxConnections;
return this;
}
public Builder maxActiveDHT(Integer maxActiveDHT) {
torrentOptions.maxDht = maxActiveDHT;
return this;
}
public Builder removeFilesAfterStop(Boolean b) {
torrentOptions.removeFiles = b;
return this;
}
public Builder prepareSize(Long prepareSize) {
torrentOptions.prepareSize = prepareSize;
return this;
}
public Builder listeningPort(Integer port) {
torrentOptions.listeningPort = port;
return this;
}
public Builder proxy(String host, String username, String password) {
torrentOptions.proxyHost = host;
torrentOptions.proxyUsername = username;
torrentOptions.proxyPassword = password;
return this;
}
public Builder peerFingerprint(String peerId) {
torrentOptions.peerFingerprint = peerId;
torrentOptions.anonymousMode = false;
return this;
}
public Builder anonymousMode(Boolean enable) {
torrentOptions.anonymousMode = enable;
if (torrentOptions.anonymousMode)
torrentOptions.peerFingerprint = null;
return this;
}
public Builder autoDownload(Boolean enable) {
torrentOptions.autoDownload = enable;
return this;
}
public TorrentOptions build() {
return torrentOptions;
}
}
}

View File

@ -0,0 +1,542 @@
/*
* Copyright (C) 2015-2018 Sébastiaan (github.com/se-bastiaan)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.se_bastiaan.torrentstream;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import com.frostwire.jlibtorrent.Priority;
import com.frostwire.jlibtorrent.SessionManager;
import com.frostwire.jlibtorrent.SessionParams;
import com.frostwire.jlibtorrent.SettingsPack;
import com.frostwire.jlibtorrent.TorrentHandle;
import com.frostwire.jlibtorrent.TorrentInfo;
import com.frostwire.jlibtorrent.alerts.AddTorrentAlert;
import com.frostwire.jlibtorrent.swig.settings_pack;
import com.github.se_bastiaan.torrentstream.exceptions.DirectoryModifyException;
import com.github.se_bastiaan.torrentstream.exceptions.NotInitializedException;
import com.github.se_bastiaan.torrentstream.exceptions.TorrentInfoException;
import com.github.se_bastiaan.torrentstream.listeners.DHTStatsAlertListener;
import com.github.se_bastiaan.torrentstream.listeners.TorrentAddedAlertListener;
import com.github.se_bastiaan.torrentstream.listeners.TorrentListener;
import com.github.se_bastiaan.torrentstream.utils.FileUtils;
import com.github.se_bastiaan.torrentstream.utils.ThreadUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
public final class TorrentStream {
private static final String LIBTORRENT_THREAD_NAME = "TORRENTSTREAM_LIBTORRENT", STREAMING_THREAD_NAME = "TORRENTSTREAMER_STREAMING";
private static TorrentStream sThis;
private final List<TorrentListener> listeners = new ArrayList<>();
private CountDownLatch initialisingLatch;
private SessionManager torrentSession;
private Boolean initialising = false, initialised = false, isStreaming = false, isCanceled = false;
private TorrentOptions torrentOptions;
private Torrent currentTorrent;
private final TorrentAddedAlertListener torrentAddedAlertListener = new TorrentAddedAlertListener() {
@Override
public void torrentAdded(AddTorrentAlert alert) {
InternalTorrentListener listener = new InternalTorrentListener();
TorrentHandle th = torrentSession.find(alert.handle().infoHash());
currentTorrent = new Torrent(th, listener, torrentOptions.prepareSize);
torrentSession.addListener(currentTorrent);
}
};
private String currentTorrentUrl;
private Integer dhtNodes = 0;
private final DHTStatsAlertListener dhtStatsAlertListener = new DHTStatsAlertListener() {
@Override
public void stats(int totalDhtNodes) {
dhtNodes = totalDhtNodes;
}
};
private HandlerThread libTorrentThread, streamingThread;
private Handler libTorrentHandler, streamingHandler;
private TorrentStream(TorrentOptions options) {
torrentOptions = options;
initialise();
}
public static TorrentStream init(TorrentOptions options) {
sThis = new TorrentStream(options);
return sThis;
}
public static TorrentStream getInstance() throws NotInitializedException {
if (sThis == null)
throw new NotInitializedException();
return sThis;
}
/**
* Obtain internal session manager
*
* @return {@link SessionManager}
*/
public SessionManager getSessionManager() {
return torrentSession;
}
private void initialise() {
if (libTorrentThread != null && torrentSession != null) {
resumeSession();
} else {
if ((initialising || initialised) && libTorrentThread != null) {
libTorrentThread.interrupt();
}
initialising = true;
initialised = false;
initialisingLatch = new CountDownLatch(1);
libTorrentThread = new HandlerThread(LIBTORRENT_THREAD_NAME);
libTorrentThread.start();
libTorrentHandler = new Handler(libTorrentThread.getLooper());
libTorrentHandler.post(new Runnable() {
@Override
public void run() {
torrentSession = new SessionManager();
setOptions(torrentOptions);
torrentSession.addListener(dhtStatsAlertListener);
torrentSession.startDht();
initialising = false;
initialised = true;
initialisingLatch.countDown();
}
});
}
}
/**
* Resume TorrentSession
*/
public void resumeSession() {
if (libTorrentThread != null && torrentSession != null) {
libTorrentHandler.removeCallbacksAndMessages(null);
//resume torrent session if needed
if (torrentSession.isPaused()) {
libTorrentHandler.post(new Runnable() {
@Override
public void run() {
torrentSession.resume();
}
});
}
if (!torrentSession.isDhtRunning()) {
libTorrentHandler.post(new Runnable() {
@Override
public void run() {
torrentSession.startDht();
}
});
}
}
}
/**
* Pause TorrentSession
*/
public void pauseSession() {
if (!isStreaming)
libTorrentHandler.post(new Runnable() {
@Override
public void run() {
torrentSession.pause();
}
});
}
/**
* Get torrent metadata, either by downloading the .torrent or fetching the magnet
*
* @param torrentUrl {@link String} URL to .torrent or magnet link
* @return {@link TorrentInfo}
*/
private TorrentInfo getTorrentInfo(String torrentUrl) throws TorrentInfoException {
if (torrentUrl.startsWith("magnet")) {
byte[] data = torrentSession.fetchMagnet(torrentUrl, 30);
if (data != null)
try {
return TorrentInfo.bdecode(data);
} catch (IllegalArgumentException e) {
throw new TorrentInfoException(e);
}
} else if (torrentUrl.startsWith("http") || torrentUrl.startsWith("https")) {
try {
URL url = new URL(torrentUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setInstanceFollowRedirects(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
byte[] responseByteArray = new byte[0];
if (connection.getResponseCode() == 200) {
responseByteArray = getBytesFromInputStream(inputStream);
}
inputStream.close();
connection.disconnect();
if (responseByteArray.length > 0) {
return TorrentInfo.bdecode(responseByteArray);
}
} catch (IOException | IllegalArgumentException e) {
throw new TorrentInfoException(e);
}
} else if (torrentUrl.startsWith("file")) {
Uri path = Uri.parse(torrentUrl);
File file = new File(path.getPath());
try {
FileInputStream fileInputStream = new FileInputStream(file);
byte[] responseByteArray = getBytesFromInputStream(fileInputStream);
fileInputStream.close();
if (responseByteArray.length > 0) {
return TorrentInfo.bdecode(responseByteArray);
}
} catch (IOException | IllegalArgumentException e) {
throw new TorrentInfoException(e);
}
}
return null;
}
private byte[] getBytesFromInputStream(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
/**
* Start stream download for specified torrent
*
* @param torrentUrl {@link String} .torrent or magnet link
*/
public void startStream(final String torrentUrl) {
if (!initialising && !initialised)
initialise();
if (libTorrentHandler == null || isStreaming) return;
isCanceled = false;
streamingThread = new HandlerThread(STREAMING_THREAD_NAME);
streamingThread.start();
streamingHandler = new Handler(streamingThread.getLooper());
streamingHandler.post(new Runnable() {
@Override
public void run() {
isStreaming = true;
if (initialisingLatch != null) {
try {
initialisingLatch.await();
initialisingLatch = null;
} catch (InterruptedException e) {
isStreaming = false;
return;
}
}
currentTorrentUrl = torrentUrl;
File saveDirectory = new File(torrentOptions.saveLocation);
if (!saveDirectory.isDirectory() && !saveDirectory.mkdirs()) {
for (final TorrentListener listener : listeners) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onStreamError(null, new DirectoryModifyException());
}
});
}
isStreaming = false;
return;
}
torrentSession.removeListener(torrentAddedAlertListener);
TorrentInfo torrentInfo = null;
try {
torrentInfo = getTorrentInfo(torrentUrl);
} catch (final TorrentInfoException e) {
for (final TorrentListener listener : listeners) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onStreamError(null, e);
}
});
}
}
torrentSession.addListener(torrentAddedAlertListener);
if (torrentInfo == null) {
for (final TorrentListener listener : listeners) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onStreamError(null, new TorrentInfoException(null));
}
});
}
isStreaming = false;
return;
}
Priority[] priorities = new Priority[torrentInfo.numFiles()];
for (int i = 0; i < priorities.length; i++) {
priorities[i] = Priority.IGNORE;
}
if (!currentTorrentUrl.equals(torrentUrl) || isCanceled) {
return;
}
torrentSession.download(torrentInfo, saveDirectory, null, priorities, null);
}
});
}
/**
* Stop current torrent stream
*/
public void stopStream() {
//remove all callbacks from handler
if (libTorrentHandler != null)
libTorrentHandler.removeCallbacksAndMessages(null);
if (streamingHandler != null)
streamingHandler.removeCallbacksAndMessages(null);
isCanceled = true;
isStreaming = false;
if (currentTorrent != null) {
final File saveLocation = currentTorrent.getSaveLocation();
currentTorrent.pause();
torrentSession.removeListener(currentTorrent);
torrentSession.remove(currentTorrent.getTorrentHandle());
currentTorrent = null;
if (torrentOptions.removeFiles) {
new Thread(new Runnable() {
@Override
public void run() {
int tries = 0;
while (!FileUtils.recursiveDelete(saveLocation) && tries < 5) {
tries++;
try {
Thread.sleep(1000); // If deleted failed then something is still using the file, wait and then retry
} catch (InterruptedException e) {
for (final TorrentListener listener : listeners) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onStreamError(currentTorrent, new DirectoryModifyException());
}
});
}
}
}
}
}).start();
}
}
if (streamingThread != null)
streamingThread.interrupt();
for (final TorrentListener listener : listeners) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onStreamStopped();
}
});
}
}
public TorrentOptions getOptions() {
return torrentOptions;
}
public void setOptions(TorrentOptions options) {
torrentOptions = options;
SettingsPack settingsPack = new SettingsPack()
.anonymousMode(torrentOptions.anonymousMode)
.connectionsLimit(torrentOptions.maxConnections)
.downloadRateLimit(torrentOptions.maxDownloadSpeed)
.uploadRateLimit(torrentOptions.maxUploadSpeed)
.activeDhtLimit(torrentOptions.maxDht);
if (torrentOptions.listeningPort != -1) {
String ifStr = String.format(Locale.ENGLISH, "%s:%d", "0.0.0.0", torrentOptions.listeningPort);
settingsPack.setString(settings_pack.string_types.listen_interfaces.swigValue(), ifStr);
}
if (torrentOptions.proxyHost != null) {
settingsPack.setString(settings_pack.string_types.proxy_hostname.swigValue(), torrentOptions.proxyHost);
if (torrentOptions.proxyUsername != null) {
settingsPack.setString(settings_pack.string_types.proxy_username.swigValue(), torrentOptions.proxyUsername);
if (torrentOptions.proxyPassword != null) {
settingsPack.setString(settings_pack.string_types.proxy_password.swigValue(), torrentOptions.proxyPassword);
}
}
}
if (torrentOptions.peerFingerprint != null) {
settingsPack.setString(settings_pack.string_types.peer_fingerprint.swigValue(), torrentOptions.peerFingerprint);
}
if (!torrentSession.isRunning()) {
SessionParams sessionParams = new SessionParams(settingsPack);
torrentSession.start(sessionParams);
} else {
torrentSession.applySettings(settingsPack);
}
}
public boolean isStreaming() {
return isStreaming;
}
public String getCurrentTorrentUrl() {
return currentTorrentUrl;
}
public Integer getTotalDhtNodes() {
return dhtNodes;
}
public Torrent getCurrentTorrent() {
return currentTorrent;
}
public void addListener(TorrentListener listener) {
if (listener != null)
listeners.add(listener);
}
public void removeListener(TorrentListener listener) {
if (listener != null)
listeners.remove(listener);
}
protected class InternalTorrentListener implements TorrentListener {
public void onStreamStarted(final Torrent torrent) {
for (final TorrentListener listener : listeners) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onStreamStarted(torrent);
}
});
}
}
public void onStreamError(final Torrent torrent, final Exception e) {
for (final TorrentListener listener : listeners) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onStreamError(torrent, e);
}
});
}
}
public void onStreamReady(final Torrent torrent) {
for (final TorrentListener listener : listeners) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onStreamReady(torrent);
}
});
}
}
public void onStreamProgress(final Torrent torrent, final StreamStatus status) {
for (final TorrentListener listener : listeners) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onStreamProgress(torrent, status);
}
});
}
}
@Override
public void onStreamStopped() {
// Not used
}
@Override
public void onStreamPrepared(final Torrent torrent) {
if (torrentOptions.autoDownload) {
torrent.startDownload();
}
for (final TorrentListener listener : listeners) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onStreamPrepared(torrent);
}
});
}
}
}
}

View File

@ -0,0 +1,25 @@
/*
* Copyright (C) 2015-2018 Sébastiaan (github.com/se-bastiaan)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.se_bastiaan.torrentstream.exceptions;
public class DirectoryModifyException extends Exception {
public DirectoryModifyException() {
super("Could not create or delete save directory");
}
}

View File

@ -0,0 +1,25 @@
/*
* Copyright (C) 2015-2018 Sébastiaan (github.com/se-bastiaan)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.se_bastiaan.torrentstream.exceptions;
public class NotInitializedException extends Exception {
public NotInitializedException() {
super("TorrentStreamer is not initialized. Call init() first before getting an instance.");
}
}

View File

@ -0,0 +1,25 @@
/*
* Copyright (C) 2015-2018 Sébastiaan (github.com/se-bastiaan)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.se_bastiaan.torrentstream.exceptions;
public class TorrentInfoException extends Exception {
public TorrentInfoException(Throwable cause) {
super("No torrent info could be found or read", cause);
}
}

View File

@ -0,0 +1,57 @@
/*
*
* * This file is part of TorrentStreamer-Android.
* *
* * TorrentStreamer-Android is free software: you can redistribute it and/or modify
* * it under the terms of the GNU Lesser General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* * (at your option) any later version.
* *
* * TorrentStreamer-Android 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 Lesser General Public License for more details.
* *
* * You should have received a copy of the GNU Lesser General Public License
* * along with TorrentStreamer-Android. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.github.se_bastiaan.torrentstream.listeners;
import com.frostwire.jlibtorrent.AlertListener;
import com.frostwire.jlibtorrent.DhtRoutingBucket;
import com.frostwire.jlibtorrent.alerts.Alert;
import com.frostwire.jlibtorrent.alerts.AlertType;
import com.frostwire.jlibtorrent.alerts.DhtStatsAlert;
import java.util.ArrayList;
public abstract class DHTStatsAlertListener implements AlertListener {
@Override
public int[] types() {
return new int[]{AlertType.DHT_STATS.swig()};
}
public void alert(Alert<?> alert) {
if (alert instanceof DhtStatsAlert) {
DhtStatsAlert dhtAlert = (DhtStatsAlert) alert;
stats(countTotalDHTNodes(dhtAlert));
}
}
public abstract void stats(int totalDhtNodes);
private int countTotalDHTNodes(DhtStatsAlert alert) {
final ArrayList<DhtRoutingBucket> routingTable = alert.routingTable();
int totalNodes = 0;
if (routingTable != null) {
for (DhtRoutingBucket bucket : routingTable) {
totalNodes += bucket.numNodes();
}
}
return totalNodes;
}
}

View File

@ -0,0 +1,42 @@
/*
* Copyright (C) 2015-2018 Sébastiaan (github.com/se-bastiaan)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.se_bastiaan.torrentstream.listeners;
import com.frostwire.jlibtorrent.AlertListener;
import com.frostwire.jlibtorrent.alerts.AddTorrentAlert;
import com.frostwire.jlibtorrent.alerts.Alert;
import com.frostwire.jlibtorrent.alerts.AlertType;
public abstract class TorrentAddedAlertListener implements AlertListener {
@Override
public int[] types() {
return new int[]{AlertType.ADD_TORRENT.swig()};
}
@Override
public void alert(Alert<?> alert) {
switch (alert.type()) {
case ADD_TORRENT:
torrentAdded((AddTorrentAlert) alert);
break;
default:
break;
}
}
public abstract void torrentAdded(AddTorrentAlert alert);
}

View File

@ -0,0 +1,34 @@
/*
* Copyright (C) 2015-2018 Sébastiaan (github.com/se-bastiaan)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.se_bastiaan.torrentstream.listeners;
import com.github.se_bastiaan.torrentstream.StreamStatus;
import com.github.se_bastiaan.torrentstream.Torrent;
public interface TorrentListener {
void onStreamPrepared(Torrent torrent);
void onStreamStarted(Torrent torrent);
void onStreamError(Torrent torrent, Exception e);
void onStreamReady(Torrent torrent);
void onStreamProgress(Torrent torrent, StreamStatus status);
void onStreamStopped();
}

View File

@ -0,0 +1,48 @@
/*
*
* * This file is part of TorrentStreamer-Android.
* *
* * TorrentStreamer-Android is free software: you can redistribute it and/or modify
* * it under the terms of the GNU Lesser General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* * (at your option) any later version.
* *
* * TorrentStreamer-Android 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 Lesser General Public License for more details.
* *
* * You should have received a copy of the GNU Lesser General Public License
* * along with TorrentStreamer-Android. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.github.se_bastiaan.torrentstream.utils;
import java.io.File;
public final class FileUtils {
private FileUtils() throws InstantiationException {
throw new InstantiationException("This class is not created for instantiation");
}
/**
* Delete every item below the File location
*
* @param file Location
* @return {@code true} when successful delete
*/
public static boolean recursiveDelete(File file) {
if (file.isDirectory()) {
String[] children = file.list();
if (children == null) return false;
for (String child : children) {
recursiveDelete(new File(file, child));
}
}
return file.delete();
}
}

View File

@ -0,0 +1,42 @@
/*
*
* * This file is part of TorrentStreamer-Android.
* *
* * TorrentStreamer-Android is free software: you can redistribute it and/or modify
* * it under the terms of the GNU Lesser General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* * (at your option) any later version.
* *
* * TorrentStreamer-Android 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 Lesser General Public License for more details.
* *
* * You should have received a copy of the GNU Lesser General Public License
* * along with TorrentStreamer-Android. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.github.se_bastiaan.torrentstream.utils;
import android.os.Handler;
import android.os.Looper;
public final class ThreadUtils {
private ThreadUtils() throws InstantiationException {
throw new InstantiationException("This class is not created for instantiation");
}
/**
* Execute the given {@link Runnable} on the ui thread.
*
* @param runnable The runnable to execute.
*/
public static void runOnUiThread(Runnable runnable) {
Thread uiThread = Looper.getMainLooper().getThread();
if (Thread.currentThread() != uiThread) new Handler(Looper.getMainLooper()).post(runnable);
else runnable.run();
}
}