Compare commits

..
25 Commits
Author SHA1 Message Date
Akinwale Ariwodola 7cf97feb9e fix channel list adapters 2020-05-14 04:14:06 +01:00
Akinwale Ariwodola d1faaa9362 don't display invites history if none exist 2020-05-14 03:47:51 +01:00
Akinwale Ariwodola aad718c714 purchase_uri for free content 2020-05-14 03:43:08 +01:00
Akinwale Ariwodola 6bed7bfd2f display text and markdown content 2020-05-14 03:36:46 +01:00
Akinwale Ariwodola df4785fb5f tweak about page layout 2020-05-14 02:24:00 +01:00
Akinwale Ariwodola 9eb7177a15 tweak player loading and playback when loading new claims 2020-05-14 02:18:54 +01:00
Akinwale Ariwodola 103565d57c SDK 0.73.1. Finish file view experience. 2020-05-14 01:59:29 +01:00
Akinwale Ariwodola da4591fb2e remove debug log 2020-05-12 17:22:22 +01:00
Akinwale Ariwodola 6ac4a25715 sdk 0.72.0. Customize player view and controls. 2020-05-12 17:17:42 +01:00
Akinwale Ariwodola b4599ec7c5 add Invites page 2020-05-11 19:38:21 +01:00
Akinwale Ariwodola bc2e8b7ec0 phone number verification and rewards page 2020-05-10 23:11:48 +01:00
Akinwale Ariwodola 2df4d76927 Channel management and channel creation / editing 2020-05-07 19:06:59 +01:00
Akinwale Ariwodola f45c517048 Channel follow/unfollow fixes. Display stream cost. 2020-05-05 01:25:30 +01:00
Akinwale Ariwodola c78f669fb1 Handle lbry:// url scheme. Properly set URL bar values. SDK 0.71.0. 2020-05-03 22:39:04 +01:00
Akinwale Ariwodola 78dd587901 Send tip dialog. Channel page share and follow/unfollow. 2020-05-03 13:46:31 +01:00
Akinwale Ariwodola 8cb51f5c17 Search cache. File view updates. Floating wallet balance. 2020-05-02 17:41:23 +01:00
Akinwale Ariwodola f4b28c4d90 display no related content view when none loaded 2020-05-01 16:52:29 +01:00
Akinwale Ariwodola cfa7e07eba Editor's Choice. Reposts. Some ontent page tweaks. 2020-05-01 13:49:56 +01:00
Akinwale Ariwodola 5ceb081972 Wallet sync get and set preferences, update interval. 2020-05-01 04:44:40 +01:00
Akinwale Ariwodola 1d1c761d3f Finish Following and All Content views. Add customize your tags view. 2020-04-30 19:05:37 +01:00
Akinwale Ariwodola 59584c1be7 Fix first time wallet sync. add Discover dialog to Following page. 2020-04-29 01:35:51 +01:00
Akinwale Ariwodola 10175470de fix Gitlab CI script 2020-04-28 14:39:57 +01:00
Akinwale Ariwodola 2604baa221 add printVersionName gradle task 2020-04-28 14:34:50 +01:00
Akinwale Ariwodola 1adf073de6 update gitlab CI script 2020-04-28 14:31:03 +01:00
Akinwale Ariwodola cf052f9c80 initial native rewrite commit 2020-04-28 14:25:39 +01:00
278 changed files with 3757 additions and 34363 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
.buildozer
.buildozer-downloads
.gradle
-1
View File
@@ -60,7 +60,6 @@ buck-out/
# Other Files
app/google-services.json
app/twitter.properties
*.log
.vagrant
*.hprof
+13 -21
View File
@@ -8,13 +8,10 @@ build apk:
stage: build
image: lbry/android-base:platform-28
before_script:
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install build-essential ca-certificates curl git gpg-agent openjdk-8-jdk software-properties-common wget zipalign git-secret
- git secret reveal
- apt-get -y update && apt-get -y install build-essential ca-certificates curl git gpg-agent openjdk-8-jdk software-properties-common wget zipalign
- chmod u+x $CI_PROJECT_DIR/gradlew
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -p $CI_PROJECT_DIR -q printVersionName --console=plain | tail -1)
- export ANDROID_SDK_ROOT=~/.buildozer/android/platform/android-sdk-23
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1)
artifacts:
paths:
- bin/browser-*-release__arm.apk
@@ -22,7 +19,12 @@ build apk:
expire_in: 1 week
script:
- export PATH=/usr/bin:$PATH
- export ANDROID_SDK_ROOT=~/.buildozer/android/platform/android-sdk-23
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install git-secret
- git secret reveal
- yarn
- chmod u+x ./release.sh
- ./release.sh
- cp bin/browser-$BUILD_VERSION-release__arm.apk /dev/null
@@ -34,15 +36,10 @@ deploy build.lbry.io:
dependencies:
- build apk
before_script:
- apt-get -y update && apt-get -y install apt-transport-https
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install openjdk-8-jdk git git-secret
- apt-get -y update && apt-get -y install openjdk-8-jdk
- pip install awscli
- chmod u+x $CI_PROJECT_DIR/gradlew
- git secret reveal
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -p $CI_PROJECT_DIR -q printVersionName --console=plain | tail -1)
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1)
- export BUILD_APK_FILENAME__32=browser-$BUILD_VERSION-release__arm.apk
- export BUILD_APK_FILENAME__64=browser-$BUILD_VERSION-release__arm64.apk
script:
@@ -58,15 +55,10 @@ release apk:
dependencies:
- build apk
before_script:
- apt-get -y update && apt-get -y install apt-transport-https
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install openjdk-8-jdk git git-secret
- apt-get -y update && apt-get -y install openjdk-8-jdk
- pip install awscli githubrelease
- git secret reveal
- chmod u+x $CI_PROJECT_DIR/gradlew
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -p $CI_PROJECT_DIR -q printVersionName --console=plain | tail -1)
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1)
- export BUILD_APK_FILENAME__32=browser-$BUILD_VERSION-release__arm.apk
- export BUILD_APK_FILENAME__64=browser-$BUILD_VERSION-release__arm64.apk
script:
Binary file not shown.
Binary file not shown.
Binary file not shown.
-1
View File
@@ -1,3 +1,2 @@
lbry-android.keystore:0d958c531870694624cc877ea98ca1c583485f8ebbb3a5acca58b1930c190d65
app/google-services.json:896a0bee8294a36d061f10fa926129d8a780528b34d0a2f03113400c4246d67c
app/twitter.properties:01212d70712f2041efb5c814bf30ecbf6f72e1ca5179c7647c4f8cbd995dd033
+2 -2
View File
@@ -2,7 +2,7 @@
[![pipeline status](https://ci.lbry.tech/lbry/lbry-android/badges/master/pipeline.svg)](https://ci.lbry.tech/lbry/lbry-android/commits/master)
[![GitHub license](https://img.shields.io/github/license/lbryio/lbry-android)](https://github.com/lbryio/lbry-android/blob/master/LICENSE)
An Android browser and wallet for the [LBRY](https://lbry.com) network.
An Android browser and wallet for the [LBRY](https://lbry.com) network. This app bundles [LBRY SDK](https://github.com/lbryio/lbry) as a background service with a UI layer built with React Native.
<img src="https://spee.ch/@lbry:3f/android-08-homepage.gif" alt="LBRY Android GIF" width="384px" />
@@ -18,7 +18,7 @@ The minimum supported Android version is 5.0 Lollipop. There are two ways to ins
The app can be launched by opening **LBRY** from the device's app drawer or via the shortcut on the home screen if that was created upon installation.
## Running from Source
Clone the repository and open the project in Android Studio. Android Studio will automatically run the initial build process. Click the Run button to launch the app on your simulator or connected debugging device after the build process is complete.
Please refer to https://github.com/lbryio/lbry-react-native/blob/master/README.md
## Contributing
Contributions to this project are welcome, encouraged, and compensated. For more details, see https://lbry.io/faq/contributing
+9 -45
View File
@@ -1,5 +1,3 @@
import com.google.gms.googleservices.GoogleServicesPlugin
apply plugin: 'com.android.application'
android {
@@ -16,16 +14,12 @@ android {
applicationId "io.lbry.browser"
minSdkVersion 21
targetSdkVersion 29
versionCode 1600
versionName "0.16.0"
versionCode 1500
versionName "0.15.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
}
productFlavors {
__32bit {
versionCode android.defaultConfig.versionCode * 10 + 1
@@ -42,17 +36,7 @@ android {
}
buildTypes {
debug {
Properties twitterProps = new Properties()
twitterProps.load(project.file('twitter.properties').newDataInputStream())
resValue "string", "TWITTER_CONSUMER_KEY", "\"${twitterProps.getProperty("twitterConsumerKey")}\""
resValue "string", "TWITTER_CONSUMER_SECRET", "\"${twitterProps.getProperty("twitterConsumerSecret")}\""
}
release {
Properties twitterProps = new Properties()
twitterProps.load(project.file('twitter.properties').newDataInputStream())
resValue "string", "TWITTER_CONSUMER_KEY", "\"${twitterProps.getProperty("twitterConsumerKey")}\""
resValue "string", "TWITTER_CONSUMER_SECRET", "\"${twitterProps.getProperty("twitterConsumerSecret")}\""
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
@@ -65,19 +49,12 @@ task printVersionName {
}
}
configurations {
all {
exclude module: 'httpclient'
exclude module: 'commons-logging'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.3.0-alpha01'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.3.0-alpha01'
implementation 'com.google.android.material:material:1.1.0'
implementation "androidx.cardview:cardview:1.0.0"
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.navigation:navigation-fragment:2.2.2'
@@ -85,28 +62,17 @@ dependencies {
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
implementation 'androidx.preference:preference:1.1.1'
implementation 'androidx.webkit:webkit:1.3.0-alpha03'
implementation 'androidx.camera:camera-core:1.0.0-beta03'
implementation 'androidx.camera:camera-camera2:1.0.0-beta03'
implementation 'androidx.camera:camera-lifecycle:1.0.0-beta03'
implementation 'androidx.camera:camera-view:1.0.0-alpha10'
implementation 'androidx.browser:browser:1.2.0'
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.squareup.okhttp3:okhttp:4.4.1'
implementation 'com.google.firebase:firebase-analytics:17.4.2'
implementation 'com.google.firebase:firebase-analytics:17.4.0'
implementation 'com.google.android.gms:play-services-base:17.2.1'
implementation 'com.google.firebase:firebase-messaging:20.2.0'
implementation 'com.google.oauth-client:google-oauth-client:1.30.4'
implementation 'com.android.billingclient:billing:3.0.0'
implementation 'com.google.firebase:firebase-messaging:20.1.6'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.google.android.exoplayer:exoplayer-core:2.11.4'
implementation 'com.google.android.exoplayer:exoplayer-dash:2.11.4'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.11.4'
implementation 'com.google.android.exoplayer:extension-cast:2.11.4'
implementation 'com.google.android.exoplayer:extension-mediasession:2.11.4'
implementation 'com.google.android:flexbox:2.0.1'
@@ -115,8 +81,6 @@ dependencies {
implementation 'com.github.chrisbanes:PhotoView:2.3.0'
implementation 'com.atlassian.commonmark:commonmark:0.14.0'
implementation 'com.arthenica:mobile-ffmpeg-full-gpl:4.3.1.LTS'
compileOnly 'org.projectlombok:lombok:1.18.10'
annotationProcessor 'org.projectlombok:lombok:1.18.10'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
@@ -125,9 +89,9 @@ dependencies {
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
__32bitImplementation 'io.lbry:lbrysdk32:0.80.0'
__64bitImplementation 'io.lbry:lbrysdk64:0.80.0'
__32bitImplementation files('libs/lbrysdk-0.73.1-release__arm.aar')
__64bitImplementation files('libs/lbrysdk-0.73.1-release__arm64.aar')
}
apply plugin: 'com.google.gms.google-services'
GoogleServicesPlugin.config.disableVersionCheck = true
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true
Binary file not shown.
Binary file not shown.
Binary file not shown.
+12 -25
View File
@@ -3,29 +3,23 @@
package="io.lbry.browser"
android:installLocation="auto">
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.android.vending.BILLING" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true">
<meta-data android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
android:value="com.google.android.exoplayer2.ext.cast.DefaultCastOptionsProvider"/>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_lbry" />
@@ -44,46 +38,39 @@
android:label="@string/app_name"
android:supportsPictureInPicture="true"
android:theme="@style/AppTheme.NoActionBar"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
android:launchMode="singleInstance"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="video/*" />
<data android:mimeType="image/*" />
<data android:mimeType="text/*" />
</intent-filter>
<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:scheme="lbry" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https" android:host="open.lbry.com"/>
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".FirstRunActivity"
android:launchMode="singleTask"
android:launchMode="singleInstance"
android:parentActivityName=".MainActivity"
android:theme="@style/AppTheme.NoActionBarTranslucent" />
<activity
android:name=".VerificationActivity"
android:launchMode="singleTask"
android:launchMode="singleInstance"
android:parentActivityName=".MainActivity"
android:theme="@style/AppTheme.NoActionBarTranslucent"
android:windowSoftInputMode="adjustResize" />
<activity
android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize|screenLayout"
android:name=".FileViewActivity"
android:launchMode="singleInstance"
android:parentActivityName=".MainActivity"
android:supportsPictureInPicture="true"
android:theme="@style/AppTheme.NoActionBarBlack" />
<service
android:name="io.lbry.browser.LbrynetMessagingService"
Binary file not shown.
File diff suppressed because it is too large. Load diff
@@ -10,21 +10,20 @@ import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.text.HtmlCompat;
import androidx.preference.PreferenceManager;
import io.lbry.browser.exceptions.AuthTokenInvalidatedException;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.Lbryio;
import io.lbry.lbrysdk.LbrynetService;
public class FirstRunActivity extends AppCompatActivity {
private BroadcastReceiver sdkReceiver;
private BroadcastReceiver sdkReadyReceiver;
private BroadcastReceiver authReceiver;
@Override
@@ -46,26 +45,19 @@ public class FirstRunActivity extends AppCompatActivity {
registerAuthReceiver();
if (!Lbry.SDK_READY) {
findViewById(R.id.welcome_wait_container).setVisibility(View.VISIBLE);
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.ACTION_SDK_READY);
sdkReadyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// authenticate after we receive the sdk ready event
authenticate();
}
};
registerReceiver(sdkReadyReceiver, filter);
} else {
authenticate();
}
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.ACTION_SDK_READY);
filter.addAction(LbrynetService.ACTION_STOP_SERVICE);
sdkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (MainActivity.ACTION_SDK_READY.equals(action)) {
// authenticate after we receive the sdk ready event
authenticate();
} else if (LbrynetService.ACTION_STOP_SERVICE.equals(action)) {
finish();
}
}
};
registerReceiver(sdkReceiver, filter);
}
public void onResume() {
@@ -105,8 +97,7 @@ public class FirstRunActivity extends AppCompatActivity {
}
private void handleAuthenticationFailed() {
findViewById(R.id.welcome_progress_bar).setVisibility(View.GONE);
((TextView) findViewById(R.id.welcome_wait_text)).setText(R.string.startup_failed);
Toast.makeText(this, "Authentication failed.", Toast.LENGTH_LONG).show();
}
private void authenticate() {
@@ -130,7 +121,7 @@ public class FirstRunActivity extends AppCompatActivity {
@Override
protected void onDestroy() {
Helper.unregisterReceiver(authReceiver, this);
Helper.unregisterReceiver(sdkReceiver, this);
Helper.unregisterReceiver(sdkReadyReceiver, this);
super.onDestroy();
}
@@ -140,11 +131,7 @@ public class FirstRunActivity extends AppCompatActivity {
this.context = context;
}
protected Void doInBackground(Void... params) {
try {
Lbryio.authenticate(context);
} catch (AuthTokenInvalidatedException ex) {
// pass
}
Lbryio.authenticate(context);
return null;
}
}
@@ -6,7 +6,6 @@ import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
@@ -21,22 +20,19 @@ import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.lbrysdk.LbrynetService;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class LbrynetMessagingService extends FirebaseMessagingService {
public static final String ACTION_NOTIFICATION_RECEIVED = "io.lbry.browser.Broadcast.NotificationReceived";
private static final String TAG = "LbrynetMessagingService";
private static final String NOTIFICATION_CHANNEL_ID = "io.lbry.browser.LBRY_ENGAGEMENT_CHANNEL";
private static final String TYPE_COMMENT = "comment";
private static final String TYPE_SUBSCRIPTION = "subscription";
private static final String TYPE_REWARD = "reward";
private static final String TYPE_INTERESTS = "interests";
@@ -56,7 +52,10 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
String title = payload.get("title");
String body = payload.get("body");
String name = payload.get("name"); // notification name
String hash = payload.get("hash"); // comment hash
String contentTitle = payload.get("content_title");
String channelUrl = payload.get("channel_url");
//String publishTime = payload.get("publish_time");
String publishTime = null;
if (type != null && getEnabledTypes().indexOf(type) > -1 && body != null && body.trim().length() > 0) {
// only log the receive event for valid notifications received
@@ -66,34 +65,7 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
firebaseAnalytics.logEvent(LbryAnalytics.EVENT_LBRY_NOTIFICATION_RECEIVE, bundle);
}
if (!Helper.isNullOrEmpty(hash)) {
url = String.format("%s?comment_hash=%s", url, hash);
}
sendNotification(title, body, type, url, name);
}
// persist the notification data
try {
DatabaseHelper helper = DatabaseHelper.getInstance();
SQLiteDatabase db = helper.getWritableDatabase();
LbryNotification lnotification = new LbryNotification();
lnotification.setTitle(title);
lnotification.setDescription(body);
lnotification.setTargetUrl(url);
lnotification.setTimestamp(new Date());
DatabaseHelper.createOrUpdateNotification(lnotification, db);
// send a broadcast
Intent intent = new Intent(ACTION_NOTIFICATION_RECEIVED);
intent.putExtra("title", title);
intent.putExtra("body", body);
intent.putExtra("url", url);
intent.putExtra("timestamp", lnotification.getTimestamp().getTime());
sendBroadcast(intent);
} catch (Exception ex) {
// don't fail if any error occurs while saving a notification
Log.e(TAG, "could not save notification", ex);
sendNotification(title, body, type, url, name, contentTitle, channelUrl, publishTime);
}
}
}
@@ -125,7 +97,8 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
*
* @param messageBody FCM message body received.
*/
private void sendNotification(String title, String messageBody, String type, String url, String name) {
private void sendNotification(String title, String messageBody, String type, String url, String name,
String contentTitle, String channelUrl, String publishTime) {
//Intent intent = new Intent(this, MainActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (url == null) {
@@ -170,9 +143,6 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
List<String> enabledTypes = new ArrayList<String>();
if (sp.getBoolean(MainActivity.PREFERENCE_KEY_NOTIFICATION_COMMENTS, true)) {
enabledTypes.add(TYPE_COMMENT);
}
if (sp.getBoolean(MainActivity.PREFERENCE_KEY_NOTIFICATION_SUBSCRIPTIONS, true)) {
enabledTypes.add(TYPE_SUBSCRIPTION);
}
File diff suppressed because it is too large. Load diff
@@ -1,46 +1,25 @@
package io.lbry.browser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.widget.ViewPager2;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.lbry.browser.adapter.VerificationPagerAdapter;
import io.lbry.browser.listener.SignInListener;
import io.lbry.browser.listener.WalletSyncListener;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.model.lbryinc.User;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.tasks.lbryinc.FetchCurrentUserTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.Lbryio;
import io.lbry.lbrysdk.LbrynetService;
public class VerificationActivity extends FragmentActivity implements SignInListener, WalletSyncListener {
@@ -48,59 +27,10 @@ public class VerificationActivity extends FragmentActivity implements SignInList
public static final int VERIFICATION_FLOW_REWARDS = 2;
public static final int VERIFICATION_FLOW_WALLET = 3;
private BillingClient billingClient;
private BroadcastReceiver sdkReceiver;
private String email;
private boolean signedIn;
private int flow;
private PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> purchases) {
int responseCode = billingResult.getResponseCode();
if (responseCode == BillingClient.BillingResponseCode.OK && purchases != null)
{
for (Purchase purchase : purchases) {
if (MainActivity.SKU_SKIP.equalsIgnoreCase(purchase.getSku())) {
showLoading();
MainActivity.handleBillingPurchase(
purchase,
billingClient,
VerificationActivity.this, null, new RewardVerifiedHandler() {
@Override
public void onSuccess(RewardVerified rewardVerified) {
if (Lbryio.currentUser != null) {
Lbryio.currentUser.setRewardApproved(rewardVerified.isRewardApproved());
}
if (!rewardVerified.isRewardApproved()) {
// show pending purchase message (possible slow card tx)
Snackbar.make(findViewById(R.id.verification_pager), R.string.purchase_request_pending, Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(findViewById(R.id.verification_pager), R.string.reward_verification_successful, Snackbar.LENGTH_LONG).show();
}
setResult(RESULT_OK);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 3000);
}
@Override
public void onError(Exception error) {
showFetchUserError(getString(R.string.purchase_request_failed_error));
hideLoading();
}
});
}
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -124,25 +54,6 @@ public class VerificationActivity extends FragmentActivity implements SignInList
return;
}
IntentFilter filter = new IntentFilter();
filter.addAction(LbrynetService.ACTION_STOP_SERVICE);
sdkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (LbrynetService.ACTION_STOP_SERVICE.equals(action)) {
finish();
}
}
};
registerReceiver(sdkReceiver, filter);
billingClient = BillingClient.newBuilder(this)
.setListener(purchasesUpdatedListener)
.enablePendingPurchases()
.build();
establishBillingClientConnection();
setContentView(R.layout.activity_verification);
ViewPager2 viewPager = findViewById(R.id.verification_pager);
viewPager.setUserInputEnabled(false);
@@ -159,24 +70,6 @@ public class VerificationActivity extends FragmentActivity implements SignInList
});
}
private void establishBillingClientConnection() {
if (billingClient != null) {
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// no need to do anything here. purchases are always checked server-side
}
}
@Override
public void onBillingServiceDisconnected() {
establishBillingClientConnection();
}
});
}
}
public void onResume() {
super.onResume();
LbryAnalytics.setCurrentScreen(this, "Verification", "Verification");
@@ -192,13 +85,11 @@ public class VerificationActivity extends FragmentActivity implements SignInList
flowHandled = true;
} else if (flow == VERIFICATION_FLOW_REWARDS) {
User user = Lbryio.currentUser;
// disable phone verification for now
/*if (!user.isIdentityVerified()) {
if (!user.isIdentityVerified()) {
// phone number verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_PHONE, false);
flowHandled = true;
} else */
if (!user.isRewardApproved()) {
} else if (!user.isRewardApproved()) {
// manual verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_MANUAL, false);
flowHandled = true;
@@ -257,7 +148,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
// only sign in required, don't do anything else
showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(this, new FetchCurrentUserTask.FetchUserTaskHandler() {
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override
public void onSuccess(User user) {
Lbryio.currentUser = user;
@@ -267,7 +158,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
@Override
public void onError(Exception error) {
showFetchUserError(error != null ? error.getMessage() : getString(R.string.fetch_current_user_error));
showFetchUserError(error.getMessage());
hideLoading();
}
});
@@ -275,7 +166,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
} else {
// change pager view depending on flow
showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(this, new FetchCurrentUserTask.FetchUserTaskHandler() {
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override
public void onSuccess(User user) {
hideLoading();
@@ -285,14 +176,10 @@ public class VerificationActivity extends FragmentActivity implements SignInList
ViewPager2 viewPager = findViewById(R.id.verification_pager);
// for rewards, (show phone verification if not done, or manual verification if required)
if (flow == VERIFICATION_FLOW_REWARDS) {
// skipping phone verification
/*if (!user.isIdentityVerified()) {
if (!user.isIdentityVerified()) {
// phone number verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_PHONE, false);
} else
*/
if (!user.isRewardApproved()) {
} else if (!user.isRewardApproved()) {
// manual verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_MANUAL, false);
} else {
@@ -307,7 +194,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
}
@Override
public void onError(Exception error) {
showFetchUserError(error != null ? error.getMessage() : getString(R.string.fetch_current_user_error));
showFetchUserError(error.getMessage());
hideLoading();
}
});
@@ -323,7 +210,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
@Override
public void onPhoneVerified() {
showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(this, new FetchCurrentUserTask.FetchUserTaskHandler() {
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override
public void onSuccess(User user) {
Lbryio.currentUser = user;
@@ -344,7 +231,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
@Override
public void onError(Exception error) {
showFetchUserError(error != null ? error.getMessage() : getString(R.string.fetch_current_user_error));
showFetchUserError(error.getMessage());
hideLoading();
}
});
@@ -352,8 +239,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
}
private void showFetchUserError(String message) {
Snackbar.make(findViewById(R.id.verification_pager), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
Snackbar.make(findViewById(R.id.verification_pager), message, Snackbar.LENGTH_LONG).setBackgroundTint(Color.RED).show();
}
@Override
@@ -382,58 +268,4 @@ public class VerificationActivity extends FragmentActivity implements SignInList
public void onWalletSyncFailed(Exception error) {
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
}
@Override
public void onSkipQueueAction() {
if (billingClient != null) {
List<String> skuList = new ArrayList<>();
skuList.add(MainActivity.SKU_SKIP);
SkuDetailsParams detailsParams = SkuDetailsParams.newBuilder().
setType(BillingClient.SkuType.INAPP).
setSkusList(skuList).build();
billingClient.querySkuDetailsAsync(detailsParams, new SkuDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(@NonNull BillingResult billingResult, @Nullable List<SkuDetails> list) {
if (list != null && list.size() > 0) {
// we only queried one product, so it should be the first item in the list
SkuDetails skuDetails = list.get(0);
// launch the billing flow for skip queue
BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder().
setSkuDetails(skuDetails).build();
billingClient.launchBillingFlow(VerificationActivity.this, billingFlowParams);
}
}
});
}
}
@Override
public void onTwitterVerified() {
Snackbar.make(findViewById(R.id.verification_pager), R.string.reward_verification_successful, Snackbar.LENGTH_LONG).show();
setResult(RESULT_OK);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 3000);
}
@Override
public void onManualProgress(boolean progress) {
if (progress) {
findViewById(R.id.verification_close_button).setVisibility(View.GONE);
} else {
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
}
}
@Override
public void onDestroy() {
Helper.unregisterReceiver(sdkReceiver, this);
super.onDestroy();
}
}
@@ -101,7 +101,7 @@ public class ChannelFilterListAdapter extends RecyclerView.Adapter<ChannelFilter
}
vh.alphaContainer.setVisibility(claim.isPlaceholder() || Helper.isNullOrEmpty(thumbnailUrl) ? View.VISIBLE : View.GONE);
vh.thumbnailView.setVisibility(claim.isPlaceholder() || Helper.isNullOrEmpty(thumbnailUrl) ? View.GONE : View.VISIBLE);
vh.alphaView.setText(claim.isPlaceholder() ? null : claim.getName() != null ? claim.getName().substring(1, 2) : "");
vh.alphaView.setText(claim.isPlaceholder() ? null : claim.getName().substring(1, 2));
int bgColor = Helper.generateRandomColorForValue(claim.getClaimId());
Helper.setIconViewBackgroundColor(vh.alphaContainer, bgColor, claim.isPlaceholder(), context);
@@ -6,8 +6,8 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
@@ -17,18 +17,13 @@ import com.google.android.material.snackbar.Snackbar;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.listener.SelectionModeListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.LbryFile;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Lbryio;
import lombok.Getter;
import lombok.Setter;
@@ -37,13 +32,6 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
private static final int VIEW_TYPE_CHANNEL = 2;
private static final int VIEW_TYPE_FEATURED = 3; // featured search result
private Map<String, Claim> quickClaimIdMap;
private Map<String, Claim> quickClaimUrlMap;
private Map<String, Boolean> notFoundClaimIdMap;
private Map<String, Boolean> notFoundClaimUrlMap;
@Setter
private boolean hideFee;
@Setter
private boolean canEnterSelectionMode;
private Context context;
@@ -56,25 +44,11 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
private boolean inSelectionMode;
@Setter
private SelectionModeListener selectionModeListener;
private float scale;
public ClaimListAdapter(List<Claim> items, Context context) {
this.context = context;
this.items = new ArrayList<>();
for (Claim item : items) {
if (item != null) {
this.items.add(item);
}
}
this.items = new ArrayList<>(items);
this.selectedItems = new ArrayList<>();
quickClaimIdMap = new HashMap<>();
quickClaimUrlMap = new HashMap<>();
notFoundClaimIdMap = new HashMap<>();
notFoundClaimUrlMap = new HashMap<>();
if (context != null) {
scale = context.getResources().getDisplayMetrics().density;
}
}
public List<Claim> getSelectedItems() {
@@ -99,45 +73,12 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
return null;
}
public void removeFeaturedItem() {
int featuredIndex = -1;
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isFeatured()) {
featuredIndex = i;
break;
}
}
if (featuredIndex > -1) {
items.remove(featuredIndex);
}
}
public List<Claim> getItems() {
return new ArrayList<>(this.items);
}
public void updateSigningChannelForClaim(Claim resolvedClaim) {
for (Claim claim : items) {
if (claim.getClaimId().equalsIgnoreCase(resolvedClaim.getClaimId())) {
claim.setSigningChannel(resolvedClaim.getSigningChannel());
}
}
}
public void clearItems() {
clearSelectedItems();
this.items.clear();
quickClaimIdMap.clear();
quickClaimUrlMap.clear();
notFoundClaimIdMap.clear();
notFoundClaimUrlMap.clear();
notifyDataSetChanged();
}
public Claim getLastItem() {
return items.size() > 0 ? items.get(items.size() - 1) : null;
}
public void addFeaturedItem(Claim claim) {
items.add(0, claim);
notifyDataSetChanged();
@@ -145,27 +86,14 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
public void addItems(List<Claim> claims) {
for (Claim claim : claims) {
if (claim != null && !items.contains(claim)) {
if (!items.contains(claim)) {
items.add(claim);
}
}
notFoundClaimUrlMap.clear();
notFoundClaimIdMap.clear();
notifyDataSetChanged();
}
public void setItems(List<Claim> claims) {
items = new ArrayList<>();
for (Claim claim : claims) {
if (claim != null) {
items.add(claim);
}
}
notifyDataSetChanged();
}
public void removeItems(List<Claim> claims) {
items.removeAll(claims);
items = new ArrayList<>(claims);
notifyDataSetChanged();
}
@@ -190,13 +118,6 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
protected View repostInfoView;
protected TextView repostChannelView;
protected View selectedOverlayView;
protected TextView fileSizeView;
protected ProgressBar downloadProgressView;
protected TextView deviceView;
protected View loadingImagePlaceholder;
protected View loadingTextPlaceholder1;
protected View loadingTextPlaceholder2;
public ViewHolder(View v) {
super(v);
feeContainer = v.findViewById(R.id.claim_fee_container);
@@ -213,13 +134,6 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
repostInfoView = v.findViewById(R.id.claim_repost_info);
repostChannelView = v.findViewById(R.id.claim_repost_channel);
selectedOverlayView = v.findViewById(R.id.claim_selected_overlay);
fileSizeView = v.findViewById(R.id.claim_file_size);
downloadProgressView = v.findViewById(R.id.claim_download_progress);
deviceView = v.findViewById(R.id.claim_view_device);
loadingImagePlaceholder = v.findViewById(R.id.claim_thumbnail_placeholder);
loadingTextPlaceholder1 = v.findViewById(R.id.claim_text_loading_placeholder_1);
loadingTextPlaceholder2 = v.findViewById(R.id.claim_text_loading_placeholder_2);
}
}
@@ -241,68 +155,6 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
return Claim.TYPE_CHANNEL.equalsIgnoreCase(actualClaim.getValueType()) ? VIEW_TYPE_CHANNEL : VIEW_TYPE_STREAM;
}
public void updateFileForClaimByIdOrUrl(LbryFile file, String claimId, String url) {
updateFileForClaimByIdOrUrl(file, claimId, url, false);
}
public void updateFileForClaimByIdOrUrl(LbryFile file, String claimId, String url, boolean skipNotFound) {
if (!skipNotFound) {
if (notFoundClaimIdMap.containsKey(claimId) && notFoundClaimUrlMap.containsKey(url)) {
return;
}
}
if (quickClaimIdMap.containsKey(claimId)) {
quickClaimIdMap.get(claimId).setFile(file);
notifyDataSetChanged();
return;
}
if (quickClaimUrlMap.containsKey(claimId)) {
quickClaimUrlMap.get(claimId).setFile(file);
notifyDataSetChanged();
return;
}
boolean claimFound = false;
for (int i = 0; i < items.size(); i++) {
Claim claim = items.get(i);
if (claimId.equalsIgnoreCase(claim.getClaimId()) || url.equalsIgnoreCase(claim.getPermanentUrl())) {
quickClaimIdMap.put(claimId, claim);
quickClaimUrlMap.put(url, claim);
claim.setFile(file);
notifyDataSetChanged();
claimFound = true;
break;
}
}
if (!claimFound) {
notFoundClaimIdMap.put(claimId, true);
notFoundClaimUrlMap.put(url, true);
}
}
public void clearFileForClaimOrUrl(String outpoint, String url) {
clearFileForClaimOrUrl(outpoint, url, false);
notifyDataSetChanged();
}
public void clearFileForClaimOrUrl(String outpoint, String url, boolean remove) {
int claimIndex = -1;
for (int i = 0; i < items.size(); i++) {
Claim claim = items.get(i);
if (outpoint.equalsIgnoreCase(claim.getOutpoint()) || url.equalsIgnoreCase(claim.getPermanentUrl())) {
claimIndex = i;
claim.setFile(null);
break;
}
}
if (remove && claimIndex > -1) {
Claim removed = items.remove(claimIndex);
selectedItems.remove(removed);
}
notifyDataSetChanged();
}
@Override
public ClaimListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int viewResourceId = -1;
@@ -319,16 +171,10 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
@Override
public void onBindViewHolder(ClaimListAdapter.ViewHolder vh, int position) {
int type = getItemViewType(position);
int paddingTop = position == 0 ? 16 : 8;
int paddingBottom = position == getItemCount() - 1 ? 16 : 8;
int paddingTopScaled = Helper.getScaledValue(paddingTop, scale);
int paddingBottomScaled = Helper.getScaledValue(paddingBottom, scale);
vh.itemView.setPadding(vh.itemView.getPaddingLeft(), paddingTopScaled, vh.itemView.getPaddingRight(), paddingBottomScaled);
Claim original = items.get(position);
boolean isRepost = Claim.TYPE_REPOST.equalsIgnoreCase(original.getValueType());
final Claim item = Claim.TYPE_REPOST.equalsIgnoreCase(original.getValueType()) ?
(original.getRepostedClaim() != null ? original.getRepostedClaim() : original): original;
final Claim item = Claim.TYPE_REPOST.equalsIgnoreCase(original.getValueType()) ? original.getRepostedClaim() : original;
Claim.GenericMetadata metadata = item.getValue();
Claim signingChannel = item.getSigningChannel();
Claim.StreamMetadata streamMetadata = null;
@@ -343,22 +189,19 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
}
boolean isPending = item.getConfirmations() == 0;
boolean isSelected = isClaimSelected(original);
boolean isSelected = isClaimSelected(item);
vh.itemView.setSelected(isSelected);
vh.selectedOverlayView.setVisibility(isSelected ? View.VISIBLE : View.GONE);
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isPending) {
Snackbar snackbar = Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG);
TextView snackbarText = snackbar.getView().findViewById(com.google.android.material.R.id.snackbar_text);
snackbarText.setMaxLines(5);
snackbar.show();
Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG).show();
return;
}
if (inSelectionMode) {
toggleSelectedClaim(original);
toggleSelectedClaim(item);
} else {
if (listener != null) {
listener.onClaimClicked(item);
@@ -374,10 +217,7 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
}
if (isPending) {
Snackbar snackbar = Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG);
TextView snackbarText = snackbar.getView().findViewById(com.google.android.material.R.id.snackbar_text);
snackbarText.setMaxLines(5);
snackbar.show();
Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG).show();
return false;
}
@@ -387,7 +227,7 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
selectionModeListener.onEnterSelectionMode();
}
}
toggleSelectedClaim(original);
toggleSelectedClaim(item);
return true;
}
});
@@ -402,8 +242,8 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
});
vh.publishTimeView.setVisibility(!isPending ? View.VISIBLE : View.GONE);
vh.pendingTextView.setVisibility(isPending && !item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
vh.repostInfoView.setVisibility(isRepost && type != VIEW_TYPE_FEATURED ? View.VISIBLE : View.GONE);
vh.pendingTextView.setVisibility(isPending ? View.VISIBLE : View.GONE);
vh.repostInfoView.setVisibility(isRepost ? View.VISIBLE : View.GONE);
vh.repostChannelView.setText(isRepost ? original.getSigningChannel().getName() : null);
vh.repostChannelView.setOnClickListener(new View.OnClickListener() {
@Override
@@ -425,13 +265,6 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
vh.noThumbnailView.setVisibility(Helper.isNullOrEmpty(thumbnailUrl) ? View.VISIBLE : View.GONE);
Helper.setIconViewBackgroundColor(vh.noThumbnailView, bgColor, false, context);
Helper.setViewVisibility(vh.loadingImagePlaceholder, item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.loadingTextPlaceholder1, item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.loadingTextPlaceholder2, item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.titleView, !item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.publisherView, !item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.publishTimeView, !item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
if (type == VIEW_TYPE_FEATURED && item.isUnresolved()) {
vh.durationView.setVisibility(View.GONE);
vh.titleView.setText("Nothing here. Publish something!");
@@ -441,46 +274,21 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
long duration = item.getDuration();
if (!Helper.isNullOrEmpty(thumbnailUrl)) {
Glide.with(context.getApplicationContext()).
asBitmap().
load(thumbnailUrl).
centerCrop().
placeholder(R.drawable.bg_thumbnail_placeholder).
into(vh.thumbnailView);
vh.thumbnailView.setVisibility(View.VISIBLE);
} else {
vh.thumbnailView.setVisibility(View.GONE);
}
BigDecimal cost = item.getActualCost(Lbryio.LBCUSDRate);
vh.feeContainer.setVisibility(cost.doubleValue() > 0 && !hideFee ? View.VISIBLE : View.GONE);
vh.feeView.setText(cost.doubleValue() > 0 ? Helper.shortCurrencyFormat(cost.doubleValue()) : "Paid");
BigDecimal cost = streamMetadata != null && streamMetadata.getFee() != null ? new BigDecimal(streamMetadata.getFee().getAmount()) : new BigDecimal(0);
vh.feeContainer.setVisibility(cost.doubleValue() > 0 ? View.VISIBLE : View.GONE);
vh.feeView.setText(cost.doubleValue() > 0 ? Helper.shortCurrencyFormat(cost.divide(new BigDecimal(100000000)).doubleValue()) : null);
vh.alphaView.setText(item.getName().substring(0, Math.min(5, item.getName().length() - 1)));
vh.publisherView.setText(signingChannel != null ? signingChannel.getName() : context.getString(R.string.anonymous));
vh.publishTimeView.setText(DateUtils.getRelativeTimeSpanString(
publishTime, System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
vh.durationView.setVisibility(duration > 0 ? View.VISIBLE : View.GONE);
vh.durationView.setText(Helper.formatDuration(duration));
LbryFile claimFile = item.getFile();
boolean isDownloading = false;
int progress = 0;
String fileSizeString = claimFile == null ? null : Helper.formatBytes(claimFile.getTotalBytes(), false);
if (claimFile != null &&
!Helper.isNullOrEmpty(claimFile.getDownloadPath()) &&
!claimFile.isCompleted() &&
claimFile.getWrittenBytes() < claimFile.getTotalBytes()) {
isDownloading = true;
progress = claimFile.getTotalBytes() > 0 ?
Double.valueOf(((double) claimFile.getWrittenBytes() / (double) claimFile.getTotalBytes()) * 100.0).intValue() : 0;
fileSizeString = String.format("%s / %s",
Helper.formatBytes(claimFile.getWrittenBytes(), false),
Helper.formatBytes(claimFile.getTotalBytes(), false));
}
Helper.setViewText(vh.fileSizeView, claimFile != null && !Helper.isNullOrEmpty(claimFile.getDownloadPath()) ? fileSizeString : null);
Helper.setViewVisibility(vh.downloadProgressView, isDownloading ? View.VISIBLE : View.INVISIBLE);
Helper.setViewProgress(vh.downloadProgressView, progress);
Helper.setViewText(vh.deviceView, item.getDevice());
} else if (Claim.TYPE_CHANNEL.equalsIgnoreCase(item.getValueType())) {
if (!Helper.isNullOrEmpty(thumbnailUrl)) {
Glide.with(context.getApplicationContext()).
@@ -1,228 +0,0 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import io.lbry.browser.R;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.ClaimCacheKey;
import io.lbry.browser.model.Comment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryUri;
import lombok.Setter;
public class CommentListAdapter extends RecyclerView.Adapter<CommentListAdapter.ViewHolder> {
private List<Comment> items;
private Context context;
private boolean nested;
private float scale;
@Setter
private ClaimListAdapter.ClaimListItemListener listener;
@Setter
private ReplyClickListener replyListener;
public CommentListAdapter(List<Comment> items, Context context) {
this(items, context, false);
}
public CommentListAdapter(List<Comment> items, Context context, boolean nested) {
this.items = new ArrayList<>(items);
this.context = context;
this.nested = nested;
if (context != null) {
scale = context.getResources().getDisplayMetrics().density;
}
for (Comment item : this.items) {
ClaimCacheKey key = new ClaimCacheKey();
key.setClaimId(item.getChannelId());
if (Lbry.claimCache.containsKey(key)) {
item.setPoster(Lbry.claimCache.get(key));
}
}
}
public void clearItems() {
items.clear();
notifyDataSetChanged();
}
public int getPositionForComment(String commentHash) {
for (int i = 0; i < items.size(); i++) {
if (commentHash.equalsIgnoreCase(items.get(i).getId())) {
return i;
}
}
return -1;
}
@Override
public int getItemCount() {
return items != null ? items.size() : 0;
}
public List<String> getClaimUrlsToResolve() {
List<String> urls = new ArrayList<>();
for (int i = 0; i < items.size(); i++) {
Comment item = items.get(i);
if (item.getPoster() == null) {
LbryUri url = LbryUri.tryParse(String.format("%s#%s", item.getChannelName(), item.getChannelId()));
if (url != null && !urls.contains(url.toString())) {
urls.add(url.toString());
}
}
if (item.getReplies().size() > 0) {
for (int j = 0; j < item.getReplies().size(); j++) {
Comment reply = item.getReplies().get(j);
if (reply.getPoster() == null) {
LbryUri url = LbryUri.tryParse(String.format("%s#%s", reply.getChannelName(), reply.getChannelId()));
if (url != null && !urls.contains(url.toString())) {
urls.add(url.toString());
}
}
}
}
}
return urls;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected TextView channelName;
protected TextView commentText;
protected ImageView thumbnailView;
protected View noThumbnailView;
protected TextView alphaView;
protected TextView commentTimeView;
protected View replyLink;
protected RecyclerView repliesList;
public ViewHolder (View v) {
super(v);
channelName = v.findViewById(R.id.comment_channel_name);
commentTimeView = v.findViewById(R.id.comment_time);
commentText = v.findViewById(R.id.comment_text);
replyLink = v.findViewById(R.id.comment_reply_link);
thumbnailView = v.findViewById(R.id.comment_thumbnail);
noThumbnailView = v.findViewById(R.id.comment_no_thumbnail);
alphaView = v.findViewById(R.id.comment_thumbnail_alpha);
repliesList = v.findViewById(R.id.comment_replies);
}
}
public void insert(int index, Comment comment) {
if (!items.contains(comment)) {
items.add(index, comment);
notifyDataSetChanged();
}
}
public void addReply(Comment comment) {
for (int i = 0; i < items.size(); i++) {
Comment parent = items.get(i);
if (parent.getId().equalsIgnoreCase(comment.getParentId())) {
parent.addReply(comment);
notifyDataSetChanged();
break;
}
}
}
public void updatePosterForComment(String channelId, Claim channel) {
for (int i = 0 ; i < items.size(); i++) {
Comment item = items.get(i);
List<Comment> replies = item.getReplies();
if (replies != null && replies.size() > 0) {
for (int j = 0; j < replies.size(); j++) {
Comment reply = item.getReplies().get(j);
if (channelId.equalsIgnoreCase(reply.getChannelId())) {
reply.setPoster(channel);
break;
}
}
}
if (channelId.equalsIgnoreCase(item.getChannelId())) {
item.setPoster(channel);
break;
}
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_comment, parent, false);
return new CommentListAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Comment comment = items.get(position);
holder.itemView.setPadding(
nested ? Helper.getScaledValue(56, scale) : holder.itemView.getPaddingLeft(),
holder.itemView.getPaddingTop(),
nested ? 0 : holder.itemView.getPaddingRight(),
holder.itemView.getPaddingBottom());
holder.channelName.setText(comment.getChannelName());
holder.commentTimeView.setText(DateUtils.getRelativeTimeSpanString(
(comment.getTimestamp() * 1000), System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
holder.commentText.setText(comment.getText());
holder.replyLink.setVisibility(!nested ? View.VISIBLE : View.GONE);
boolean hasThumbnail = comment.getPoster() != null && !Helper.isNullOrEmpty(comment.getPoster().getThumbnailUrl());
holder.thumbnailView.setVisibility(hasThumbnail ? View.VISIBLE : View.INVISIBLE);
holder.noThumbnailView.setVisibility(!hasThumbnail ? View.VISIBLE : View.INVISIBLE);
int bgColor = Helper.generateRandomColorForValue(comment.getChannelId());
Helper.setIconViewBackgroundColor(holder.noThumbnailView, bgColor, false, context);
if (hasThumbnail) {
Glide.with(context.getApplicationContext()).asBitmap().load(comment.getPoster().getThumbnailUrl()).
apply(RequestOptions.circleCropTransform()).into(holder.thumbnailView);
}
holder.alphaView.setText(comment.getChannelName() != null ? comment.getChannelName().substring(1, 2).toUpperCase() : null);
List<Comment> replies = comment.getReplies();
boolean hasReplies = replies != null && replies.size() > 0;
if (hasReplies) {
holder.repliesList.setLayoutManager(new LinearLayoutManager(context));
holder.repliesList.setAdapter(new CommentListAdapter(replies, context, true));
} else {
holder.repliesList.setAdapter(null);
}
holder.channelName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null && comment.getPoster() != null) {
listener.onClaimClicked(comment.getPoster());
}
}
});
holder.replyLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (replyListener != null) {
replyListener.onReplyClicked(comment);
}
}
});
}
public interface ReplyClickListener {
void onReplyClicked(Comment comment);
}
}
@@ -95,7 +95,6 @@ public class EditorsChoiceItemAdapter extends RecyclerView.Adapter<EditorsChoice
vh.descriptionView.setText(item.getDescription());
if (!Helper.isNullOrEmpty(item.getThumbnailUrl())) {
Glide.with(context.getApplicationContext()).
asBitmap().
load(item.getThumbnailUrl()).
centerCrop().
placeholder(R.drawable.bg_thumbnail_placeholder).
@@ -1,119 +0,0 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.model.GalleryItem;
import io.lbry.browser.utils.Helper;
import lombok.Setter;
public class GalleryGridAdapter extends RecyclerView.Adapter<GalleryGridAdapter.ViewHolder> {
private Context context;
private List<GalleryItem> items;
@Setter
private GalleryItemClickListener listener;
public GalleryGridAdapter(List<GalleryItem> items, Context context) {
this.items = new ArrayList<>(items);
this.context = context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected ImageView thumbnailView;
protected TextView durationView;
public ViewHolder(View v) {
super(v);
thumbnailView = v.findViewById(R.id.gallery_item_thumbnail);
durationView = v.findViewById(R.id.gallery_item_duration);
}
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
public void addItem(GalleryItem item) {
if (!items.contains(item)) {
items.add(item);
notifyDataSetChanged();
}
}
public void addItems(List<GalleryItem> items) {
for (GalleryItem item : items) {
if (!this.items.contains(item)) {
this.items.add(item);
notifyDataSetChanged();
}
}
}
public void clearItems() {
items.clear();
notifyDataSetChanged();
}
@Override
public GalleryGridAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_gallery, root, false);
return new GalleryGridAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(GalleryGridAdapter.ViewHolder vh, int position) {
GalleryItem item = items.get(position);
String thumbnailUrl = item.getThumbnailPath();
Glide.with(context.getApplicationContext()).load(thumbnailUrl).centerCrop().into(vh.thumbnailView);
vh.durationView.setVisibility(item.getDuration() > 0 ? View.VISIBLE : View.INVISIBLE);
vh.durationView.setText(item.getDuration() > 0 ? Helper.formatDuration(Double.valueOf(item.getDuration() / 1000.0).longValue()) : null);
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null) {
listener.onGalleryItemClicked(item);
}
}
});
}
public interface GalleryItemClickListener {
void onGalleryItemClicked(GalleryItem item);
}
public static class GalleryGridItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
public GalleryGridItemDecoration(int spanCount, int spacing) {
this.spanCount = spanCount;
this.spacing = spacing;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
@@ -10,7 +10,6 @@ import android.widget.SpinnerAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import io.lbry.browser.R;
@@ -41,35 +40,6 @@ public class InlineChannelSpinnerAdapter extends ArrayAdapter<Claim> {
channels.add(1, anonymous);
}
}
public void addAnonymousPlaceholder() {
Claim anonymous = new Claim();
anonymous.setPlaceholderAnonymous(true);
insert(anonymous, 0);
channels.add(0, anonymous);
}
public void addAll(Collection<? extends Claim> collection) {
for (Claim claim : collection) {
if (!channels.contains(claim)) {
channels.add(claim);
}
}
super.addAll(collection);
}
public void clear() {
channels.clear();
super.clear();
}
public int getItemPosition(Claim item) {
for (int i = 0; i < channels.size(); i++) {
Claim channel = channels.get(i);
if (item.getClaimId() != null && item.getClaimId().equalsIgnoreCase(channel.getClaimId())) {
return i;
}
}
return -1;
}
@Override
public View getDropDownView(int position, View view, ViewGroup parent) {
@@ -1,53 +0,0 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import io.lbry.browser.R;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.Language;
import io.lbry.browser.utils.Predefined;
public class LanguageSpinnerAdapter extends ArrayAdapter<Language> {
private int layoutResourceId;
private LayoutInflater inflater;
public LanguageSpinnerAdapter(Context context, int resource) {
super(context, resource, 0, Predefined.PUBLISH_LANGUAGES);
inflater = LayoutInflater.from(context);
layoutResourceId = resource;
}
public int getItemPosition(String languageCode) {
for (int i = 0; i < Predefined.PUBLISH_LANGUAGES.size(); i++) {
Language lang = Predefined.PUBLISH_LANGUAGES.get(i);
if (lang.getCode().equalsIgnoreCase(languageCode)) {
return i;
}
}
return -1;
}
@Override
public View getDropDownView(int position, View view, @NonNull ViewGroup parent) {
return createView(position, view, parent);
}
@Override
public View getView(int position, View view, @NonNull ViewGroup parent) {
return createView(position, view, parent);
}
private View createView(int position, View convertView, ViewGroup parent) {
Language item = getItem(position);
View view = inflater.inflate(layoutResourceId, parent, false);
TextView label = view.findViewById(R.id.item_display_name);
label.setText(item != null ? item.getStringResourceId() : 0);
return view;
}
}
@@ -1,52 +0,0 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import io.lbry.browser.R;
import io.lbry.browser.model.Language;
import io.lbry.browser.model.License;
import io.lbry.browser.utils.Predefined;
public class LicenseSpinnerAdapter extends ArrayAdapter<License> {
private int layoutResourceId;
private LayoutInflater inflater;
public LicenseSpinnerAdapter(Context context, int resource) {
super(context, resource, 0, Predefined.LICENSES);
inflater = LayoutInflater.from(context);
layoutResourceId = resource;
}
public int getItemPosition(String name) {
for (int i = 0; i < Predefined.LICENSES.size(); i++) {
License lic = Predefined.LICENSES.get(i);
if (lic.getName().equalsIgnoreCase(name)) {
return i;
}
}
return -1;
}
@Override
public View getDropDownView(int position, View view, @NonNull ViewGroup parent) {
return createView(position, view, parent);
}
@Override
public View getView(int position, View view, @NonNull ViewGroup parent) {
return createView(position, view, parent);
}
private View createView(int position, View convertView, ViewGroup parent) {
License item = getItem(position);
View view = inflater.inflate(layoutResourceId, parent, false);
TextView label = view.findViewById(R.id.item_display_name);
label.setText(item != null ? item.getStringResourceId() : 0);
return view;
}
}
@@ -1,204 +0,0 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.graphics.Color;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;
import io.lbry.browser.R;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.ui.controls.SolidIconView;
import io.lbry.browser.utils.Helper;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Data
@EqualsAndHashCode(callSuper = false)
public class NotificationListAdapter extends RecyclerView.Adapter<NotificationListAdapter.ViewHolder> {
private static final String RULE_CREATOR_SUBSCRIBER = "creator_subscriber";
private static final String RULE_COMMENT = "comment";
private Context context;
private List<LbryNotification> items;
@Setter
private NotificationClickListener clickListener;
@Getter
@Setter
private int customizeMode;
public NotificationListAdapter(List<LbryNotification> notifications, Context context) {
this.context = context;
this.items = new ArrayList<>(notifications);
Collections.sort(items, Collections.reverseOrder(new LbryNotification()));
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected View layoutView;
protected TextView titleView;
protected TextView bodyView;
protected TextView timeView;
protected SolidIconView iconView;
protected ImageView thumbnailView;
public ViewHolder(View v) {
super(v);
layoutView = v.findViewById(R.id.notification_layout);
titleView = v.findViewById(R.id.notification_title);
bodyView = v.findViewById(R.id.notification_body);
timeView = v.findViewById(R.id.notification_time);
iconView = v.findViewById(R.id.notification_icon);
thumbnailView = v.findViewById(R.id.notification_author_thumbnail);
}
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
public void insertNotification(LbryNotification notification, int index) {
if (!items.contains(notification)) {
items.add(index, notification);
}
notifyDataSetChanged();
}
public void addNotification(LbryNotification notification) {
if (!items.contains(notification)) {
items.add(notification);
}
notifyDataSetChanged();
}
public List<String> getAuthorUrls() {
List<String> urls = new ArrayList<>();
for (LbryNotification item : items) {
if (!Helper.isNullOrEmpty(item.getAuthorUrl())) {
urls.add(item.getAuthorUrl());
}
}
return urls;
}
public void updateAuthorClaims(List<Claim> claims) {
for (Claim claim : claims) {
if (claim != null && claim.getThumbnailUrl() != null) {
updateClaimForAuthorUrl(claim);
}
}
notifyDataSetChanged();
}
private void updateClaimForAuthorUrl(Claim claim) {
for (LbryNotification item : items) {
if (claim.getPermanentUrl().equalsIgnoreCase(item.getAuthorUrl())) {
item.setCommentAuthor(claim);
}
}
}
public void addNotifications(List<LbryNotification> notifications) {
for (LbryNotification notification : notifications) {
if (!items.contains(notification)) {
items.add(notification);
}
}
Collections.sort(items, Collections.reverseOrder(new LbryNotification()));
notifyDataSetChanged();
}
@Override
public NotificationListAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_notification, root, false);
return new NotificationListAdapter.ViewHolder(v);
}
private int getStringIdForRule(String rule) {
if (RULE_CREATOR_SUBSCRIBER.equalsIgnoreCase(rule)) {
return R.string.fa_heart;
}
if (RULE_COMMENT.equalsIgnoreCase(rule)) {
return R.string.fa_comment_alt;
}
return R.string.fa_asterisk;
}
private int getColorForRule(String rule) {
if (RULE_CREATOR_SUBSCRIBER.equalsIgnoreCase(rule)) {
return Color.RED;
}
if (RULE_COMMENT.equalsIgnoreCase(rule)) {
return ContextCompat.getColor(context, R.color.nextLbryGreen);
}
return ContextCompat.getColor(context, R.color.lbryGreen);
}
@Override
public void onBindViewHolder(NotificationListAdapter.ViewHolder vh, int position) {
LbryNotification notification = items.get(position);
vh.layoutView.setBackgroundColor(ContextCompat.getColor(context, notification.isSeen() ? R.color.white : R.color.nextLbryGreenSemiTransparent));
vh.titleView.setVisibility(!Helper.isNullOrEmpty(notification.getTitle()) ? View.VISIBLE : View.GONE);
vh.titleView.setText(notification.getTitle());
vh.bodyView.setText(notification.getDescription());
vh.timeView.setText(DateUtils.getRelativeTimeSpanString(
getLocalNotificationTime(notification), System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
vh.thumbnailView.setVisibility(notification.getCommentAuthor() == null ? View.INVISIBLE : View.VISIBLE);
if (notification.getCommentAuthor() != null) {
Glide.with(context.getApplicationContext()).load(
notification.getCommentAuthor().getThumbnailUrl()).apply(RequestOptions.circleCropTransform()).into(vh.thumbnailView);
}
vh.iconView.setVisibility(notification.getCommentAuthor() != null ? View.INVISIBLE : View.VISIBLE);
vh.iconView.setText(getStringIdForRule(notification.getRule()));
vh.iconView.setTextColor(getColorForRule(notification.getRule()));
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onNotificationClicked(notification);
}
}
});
}
private long getLocalNotificationTime(LbryNotification notification) {
TimeZone utcTZ = TimeZone.getTimeZone("UTC");
TimeZone targetTZ = TimeZone.getDefault();
Calendar cal = new GregorianCalendar(utcTZ);
cal.setTimeInMillis(notification.getTimestamp().getTime());
cal.add(Calendar.MILLISECOND, utcTZ.getRawOffset() * -1);
cal.add(Calendar.MILLISECOND, targetTZ.getRawOffset());
return cal.getTimeInMillis();
}
public interface NotificationClickListener {
void onNotificationClicked(LbryNotification notification);
}
}
@@ -159,7 +159,7 @@ public class RewardListAdapter extends RecyclerView.Adapter<RewardListAdapter.Vi
});
vh.textUsdValue.setText(reward.isCustom() || Lbryio.LBCUSDRate == 0 ? null :
String.format("≈$%s", Helper.SIMPLE_CURRENCY_FORMAT.format(rewardAmount * Lbryio.LBCUSDRate)));
String.format("≈$%s", Helper.USD_CURRENCY_FORMAT.format(rewardAmount * Lbryio.LBCUSDRate)));
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
@@ -168,10 +168,6 @@ public class RewardListAdapter extends RecyclerView.Adapter<RewardListAdapter.Vi
return;
}
if (vh.inputCustomCode != null && !vh.inputCustomCode.hasFocus()) {
vh.inputCustomCode.requestFocus();
}
if (clickListener != null) {
clickListener.onRewardClicked(reward, vh.loading);
}
@@ -201,8 +197,7 @@ public class RewardListAdapter extends RecyclerView.Adapter<RewardListAdapter.Vi
public void onClick(View view) {
String claimCode = Helper.getValue(vh.inputCustomCode.getText());
if (Helper.isNullOrEmpty(claimCode)) {
Snackbar.make(view, R.string.please_enter_claim_code, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
Snackbar.make(view, R.string.please_enter_claim_code, Snackbar.LENGTH_LONG).setBackgroundTint(Color.RED).show();
return;
}
@@ -56,11 +56,6 @@ public class SuggestedChannelGridAdapter extends RecyclerView.Adapter<SuggestedC
public int getSelectedCount() { return selectedItems.size(); }
public void clearItems() {
items.clear();
notifyDataSetChanged();
}
public List<Claim> getSelectedItems() {
return this.selectedItems;
}
@@ -72,9 +72,7 @@ public class TransactionListAdapter extends RecyclerView.Adapter<TransactionList
vh.claimView.setText(item.getClaim());
vh.feeView.setText(context.getString(R.string.tx_list_fee, TX_LIST_AMOUNT_FORMAT.format(item.getFee().doubleValue())));
vh.txidLinkView.setText(item.getTxid().substring(0, 7));
vh.dateView.setVisibility(item.getConfirmations() > 0 ? View.VISIBLE : View.GONE);
vh.dateView.setText(item.getConfirmations() > 0 ? TX_LIST_DATE_FORMAT.format(item.getTxDate()) : null);
vh.pendingView.setVisibility(item.getConfirmations() == 0 ? View.VISIBLE : View.GONE);
vh.dateView.setText(TX_LIST_DATE_FORMAT.format(item.getTxDate()));
vh.infoFeeContainer.setVisibility(!Helper.isNullOrEmpty(item.getClaim()) || Math.abs(item.getFee().doubleValue()) > 0 ?
View.VISIBLE : View.GONE);
@@ -113,7 +111,6 @@ public class TransactionListAdapter extends RecyclerView.Adapter<TransactionList
protected TextView feeView;
protected TextView txidLinkView;
protected TextView dateView;
protected TextView pendingView;
protected View infoFeeContainer;
public ViewHolder(View v) {
@@ -124,7 +121,6 @@ public class TransactionListAdapter extends RecyclerView.Adapter<TransactionList
feeView = v.findViewById(R.id.transaction_fee);
txidLinkView = v.findViewById(R.id.transaction_id_link);
dateView = v.findViewById(R.id.transaction_date);
pendingView = v.findViewById(R.id.transaction_pending_text);
infoFeeContainer = v.findViewById(R.id.transaction_info_fee_container);
}
}
@@ -16,7 +16,6 @@ import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.ui.controls.SolidIconView;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import lombok.Setter;
@@ -97,7 +96,7 @@ public class UrlSuggestionListAdapter extends RecyclerView.Adapter<UrlSuggestion
iconStringId = R.string.fa_at;
fullTitle = item.getTitle();
desc = item.getClaim() != null ? item.getClaim().getTitle() :
((item.isUseTextAsDescription() && !Helper.isNullOrEmpty(item.getText())) ? item.getText() : String.format(context.getString(R.string.view_channel_url_desc), item.getText()));
(item.isUseTextAsDescription() ? item.getText() : String.format(context.getString(R.string.view_channel_url_desc), item.getText()));
break;
case UrlSuggestion.TYPE_TAG:
iconStringId = R.string.fa_hashtag;
@@ -114,7 +113,7 @@ public class UrlSuggestionListAdapter extends RecyclerView.Adapter<UrlSuggestion
iconStringId = R.string.fa_file;
fullTitle = item.getTitle();
desc = item.getClaim() != null ? item.getClaim().getTitle() :
((item.isUseTextAsDescription() && !Helper.isNullOrEmpty(item.getText())) ? item.getText() : String.format(context.getString(R.string.view_file_url_desc), item.getText()));
(item.isUseTextAsDescription() ? item.getText() : String.format(context.getString(R.string.view_file_url_desc), item.getText()));
break;
}
@@ -5,25 +5,22 @@ import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.model.Tag;
import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.model.ViewHistory;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.model.lbryinc.Subscription;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 6;
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "LbryApp.db";
private static DatabaseHelper instance;
private static final String[] SQL_CREATE_TABLES = {
// local subscription store
@@ -39,7 +36,6 @@ public class DatabaseHelper extends SQLiteOpenHelper {
", claim_id TEXT" +
", claim_name TEXT" +
", cost REAL " +
", currency TEXT " +
", title TEXT " +
", publisher_claim_id TEXT" +
", publisher_name TEXT" +
@@ -47,19 +43,7 @@ public class DatabaseHelper extends SQLiteOpenHelper {
", thumbnail_url TEXT" +
", release_time INTEGER " +
", device TEXT" +
", timestamp TEXT NOT NULL)",
"CREATE TABLE notifications (" +
" id INTEGER PRIMARY KEY NOT NULL" +
", remote_id INTEGER NOT NULL" +
", author_url TEXT" +
", title TEXT" +
", description TEXT" +
", thumbnail_url TEXT" +
", target_url TEXT" +
", rule TEXT" +
", is_read INTEGER DEFAULT 0 NOT NULL" +
", is_seen INTEGER DEFAULT 0 NOT NULL " +
", timestamp TEXT NOT NULL)",
", timestamp TEXT NOT NULL)"
};
private static final String[] SQL_CREATE_INDEXES = {
"CREATE UNIQUE INDEX idx_subscription_url ON subscriptions (url)",
@@ -67,60 +51,20 @@ public class DatabaseHelper extends SQLiteOpenHelper {
"CREATE UNIQUE INDEX idx_url_history_url ON url_history (url)",
"CREATE UNIQUE INDEX idx_tag_name ON tags (name)",
"CREATE UNIQUE INDEX idx_view_history_url_device ON view_history (url, device)",
"CREATE INDEX idx_view_history_device ON view_history (device)",
"CREATE UNIQUE INDEX idx_notification_remote_id ON notifications (remote_id)",
"CREATE INDEX idx_notification_timestamp ON notifications (timestamp)"
};
private static final String[] SQL_V1_V2_UPGRADE = {
"ALTER TABLE view_history ADD COLUMN currency TEXT"
};
private static final String[] SQL_V2_V3_UPGRADE = {
"CREATE TABLE notifications (" +
" id INTEGER PRIMARY KEY NOT NULL" +
", title TEXT" +
", description TEXT" +
", thumbnail_url TEXT" +
", target_url TEXT" +
", is_read INTEGER DEFAULT 0 NOT NULL" +
", timestamp TEXT NOT NULL)",
"CREATE INDEX idx_notification_timestamp ON notifications (timestamp)"
};
private static final String[] SQL_V3_V4_UPGRADE = {
"ALTER TABLE notifications ADD COLUMN remote_id INTEGER",
"CREATE UNIQUE INDEX idx_notification_remote_id ON notifications (remote_id)"
};
private static final String[] SQL_V4_V5_UPGRADE = {
"ALTER TABLE notifications ADD COLUMN rule TEXT",
"ALTER TABLE notifications ADD COLUMN is_seen TEXT"
};
private static final String[] SQL_V5_V6_UPGRADE = {
"ALTER TABLE notifications ADD COLUMN author_url TEXT"
"CREATE INDEX idx_view_history_device ON view_history (device)"
};
private static final String SQL_INSERT_SUBSCRIPTION = "REPLACE INTO subscriptions (channel_name, url) VALUES (?, ?)";
private static final String SQL_CLEAR_SUBSCRIPTIONS = "DELETE FROM subscriptions";
private static final String SQL_DELETE_SUBSCRIPTION = "DELETE FROM subscriptions WHERE url = ?";
private static final String SQL_GET_SUBSCRIPTIONS = "SELECT channel_name, url FROM subscriptions";
private static final String SQL_INSERT_URL_HISTORY = "REPLACE INTO url_history (value, url, type, timestamp) VALUES (?, ?, ?, ?)";
private static final String SQL_INSERT_URL_HISTORY = "REPLACE INTO url_history (value, url, type, timestamp) VALUES (?, ?, ?)";
private static final String SQL_CLEAR_URL_HISTORY = "DELETE FROM url_history";
private static final String SQL_CLEAR_URL_HISTORY_BEFORE_TIME = "DELETE FROM url_history WHERE timestamp < ?";
private static final String SQL_GET_RECENT_URL_HISTORY = "SELECT value, url, type FROM url_history ORDER BY timestamp DESC LIMIT 10";
private static final String SQL_INSERT_NOTIFICATION = "REPLACE INTO notifications (remote_id, author_url, title, description, rule, target_url, is_read, is_seen, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String SQL_GET_NOTIFICATIONS = "SELECT id, remote_id, author_url, title, description, rule, target_url, is_read, is_seen, timestamp FROM notifications ORDER BY timestamp DESC LIMIT 500";
private static final String SQL_GET_UNREAD_NOTIFICATIONS_COUNT = "SELECT COUNT(id) FROM notifications WHERE is_read <> 1";
private static final String SQL_MARK_NOTIFICATIONS_READ = "UPDATE notifications SET is_read = 1 WHERE is_read = 0";
private static final String SQL_MARK_NOTIFICATION_READ_AND_SEEN = "UPDATE notifications SET is_read = 1, is_seen = 1 WHERE id = ?";
private static final String SQL_INSERT_VIEW_HISTORY =
"REPLACE INTO view_history (url, claim_id, claim_name, cost, currency, title, publisher_claim_id, publisher_name, publisher_title, thumbnail_url, device, release_time, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String SQL_GET_VIEW_HISTORY =
"SELECT url, claim_id, claim_name, cost, currency, title, publisher_claim_id, publisher_name, publisher_title, thumbnail_url, device, release_time, timestamp " +
"FROM view_history WHERE '' = ? OR timestamp < ? ORDER BY timestamp DESC LIMIT %d";
"REPLACE INTO view_history (url, claim_id, claim_name, cost, title, publisher_claim_id, publisher_name, publisher_title, thumbnail_url, device, release_time, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String SQL_CLEAR_VIEW_HISTORY = "DELETE FROM view_history";
private static final String SQL_CLEAR_VIEW_HISTORY_BY_DEVICE = "DELETE FROM view_history WHERE device = ?";
private static final String SQL_CLEAR_VIEW_HISTORY_BEFORE_TIME = "DELETE FROM view_history WHERE timestamp < ?";
@@ -131,14 +75,8 @@ public class DatabaseHelper extends SQLiteOpenHelper {
private static final String SQL_UNFOLLOW_TAGS = "UPDATE tags SET is_followed = 0";
private static final String SQL_GET_FOLLOWED_TAGS = "SELECT name FROM tags WHERE is_followed = 1";
public DatabaseHelper(Context context) {
super(context, String.format("%s/%s", context.getFilesDir().getAbsolutePath(), DATABASE_NAME), null, DATABASE_VERSION);
instance = this;
}
public static DatabaseHelper getInstance() {
return instance;
}
public void onCreate(SQLiteDatabase db) {
for (String sql : SQL_CREATE_TABLES) {
@@ -149,31 +87,7 @@ public class DatabaseHelper extends SQLiteOpenHelper {
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
for (String sql : SQL_V1_V2_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 3) {
for (String sql : SQL_V2_V3_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 4) {
for (String sql : SQL_V3_V4_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 5) {
for (String sql : SQL_V4_V5_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 6) {
for (String sql : SQL_V5_V6_UPGRADE) {
db.execSQL(sql);
}
}
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
@@ -199,9 +113,13 @@ public class DatabaseHelper extends SQLiteOpenHelper {
while (cursor.moveToNext()) {
UrlSuggestion suggestion = new UrlSuggestion();
suggestion.setText(cursor.getString(0));
suggestion.setUri(cursor.isNull(1) ? null : LbryUri.tryParse(cursor.getString(1)));
suggestion.setType(cursor.getInt(2));
suggestion.setTitleUrlOnly(true);
try {
suggestion.setUri(cursor.isNull(1) ? null : LbryUri.parse(cursor.getString(1)));
} catch (LbryUriException ex) {
// don't fail if the LbryUri is invalid
}
suggestions.add(suggestion);
}
} finally {
@@ -217,7 +135,6 @@ public class DatabaseHelper extends SQLiteOpenHelper {
viewHistory.getClaimId(),
viewHistory.getClaimName(),
viewHistory.getCost() != null ? viewHistory.getCost().doubleValue() : 0,
viewHistory.getCurrency(),
viewHistory.getTitle(),
viewHistory.getPublisherClaimId(),
viewHistory.getPublisherName(),
@@ -229,42 +146,6 @@ public class DatabaseHelper extends SQLiteOpenHelper {
});
}
public static List<ViewHistory> getViewHistory(String lastTimestamp, int pageLimit, SQLiteDatabase db) {
List<ViewHistory> history = new ArrayList<>();
Cursor cursor = null;
try {
String arg = lastTimestamp == null ? "" : lastTimestamp;
cursor = db.rawQuery(String.format(SQL_GET_VIEW_HISTORY, pageLimit), new String[] { arg, arg });
while (cursor.moveToNext()) {
ViewHistory item = new ViewHistory();
int cursorIndex = 0;
item.setUri(LbryUri.tryParse(cursor.getString(cursorIndex++)));
item.setClaimId(cursor.getString(cursorIndex++));
item.setClaimName(cursor.getString(cursorIndex++));
item.setCost(new BigDecimal(cursor.getDouble(cursorIndex++)));
item.setCurrency(cursor.getString(cursorIndex++));
item.setTitle(cursor.getString(cursorIndex++));
item.setPublisherClaimId(cursor.getString(cursorIndex++));
item.setPublisherName(cursor.getString(cursorIndex++));
item.setPublisherTitle(cursor.getString(cursorIndex++));
item.setThumbnailUrl(cursor.getString(cursorIndex++));
item.setDevice(cursor.getString(cursorIndex++));
item.setReleaseTime(cursor.getLong(cursorIndex++));
try {
item.setTimestamp(new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).parse(cursor.getString(cursorIndex)));
} catch (ParseException ex) {
// invalid timestamp (which shouldn't happen). Skip this item
continue;
}
history.add(item);
}
} finally {
Helper.closeCursor(cursor);
}
return history;
}
public static void createOrUpdateTag(Tag tag, SQLiteDatabase db) {
db.execSQL(SQL_INSERT_TAG, new Object[] { tag.getLowercaseName(), tag.isFollowed() ? 1 : 0 });
}
@@ -294,9 +175,6 @@ public class DatabaseHelper extends SQLiteOpenHelper {
public static void deleteSubscription(Subscription subscription, SQLiteDatabase db) {
db.execSQL(SQL_DELETE_SUBSCRIPTION, new Object[] { subscription.getUrl() });
}
public static void clearSubscriptions(SQLiteDatabase db) {
db.execSQL(SQL_CLEAR_SUBSCRIPTIONS);
}
public static List<Subscription> getSubscriptions(SQLiteDatabase db) {
List<Subscription> subscriptions = new ArrayList<>();
Cursor cursor = null;
@@ -314,66 +192,4 @@ public class DatabaseHelper extends SQLiteOpenHelper {
return subscriptions;
}
public static void createOrUpdateNotification(LbryNotification notification, SQLiteDatabase db) {
db.execSQL(SQL_INSERT_NOTIFICATION, new Object[] {
notification.getRemoteId(),
notification.getAuthorUrl(),
notification.getTitle(),
notification.getDescription(),
notification.getRule(),
notification.getTargetUrl(),
notification.isRead() ? 1 : 0,
notification.isSeen() ? 1 : 0,
new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).format(notification.getTimestamp() != null ? notification.getTimestamp() : new Date())
});
}
public static List<LbryNotification> getNotifications(SQLiteDatabase db) {
List<LbryNotification> notifications = new ArrayList<>();
Cursor cursor = null;
try {
cursor = db.rawQuery(SQL_GET_NOTIFICATIONS, null);
while (cursor.moveToNext()) {
LbryNotification notification = new LbryNotification();
int columnIndex = 0;
notification.setId(cursor.getLong(columnIndex++));
notification.setRemoteId(cursor.getLong(columnIndex++));
notification.setAuthorUrl(cursor.getString(columnIndex++));
notification.setTitle(cursor.getString(columnIndex++));
notification.setDescription(cursor.getString(columnIndex++));
notification.setRule(cursor.getString(columnIndex++));
notification.setTargetUrl(cursor.getString(columnIndex++));
notification.setRead(cursor.getInt(columnIndex++) == 1);
notification.setSeen(cursor.getInt(columnIndex++) == 1);
try {
notification.setTimestamp(new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).parse(cursor.getString(columnIndex++)));
} catch (ParseException ex) {
// invalid timestamp (which shouldn't happen). Skip this item
continue;
}
notifications.add(notification);
}
} finally {
Helper.closeCursor(cursor);
}
return notifications;
}
public static int getUnreadNotificationsCount(SQLiteDatabase db) {
int count = 0;
Cursor cursor = null;
try {
cursor = db.rawQuery(SQL_GET_UNREAD_NOTIFICATIONS_COUNT, null);
if (cursor.moveToNext()) {
count = cursor.getInt(0);
}
} finally {
Helper.closeCursor(cursor);
}
return count;
}
public static void markNotificationsRead(SQLiteDatabase db) {
db.execSQL(SQL_MARK_NOTIFICATIONS_READ);
}
public static void markNotificationReadAndSeen(long notificationId, SQLiteDatabase db) {
db.execSQL(SQL_MARK_NOTIFICATION_READ_AND_SEEN, new Object[] { notificationId });
}
}
@@ -1,346 +0,0 @@
package io.lbry.browser.dialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.text.HtmlCompat;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.android.material.textfield.TextInputEditText;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.InlineChannelSpinnerAdapter;
import io.lbry.browser.listener.WalletBalanceListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimListTask;
import io.lbry.browser.tasks.wallet.SupportCreateTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import lombok.Setter;
public class CreateSupportDialogFragment extends BottomSheetDialogFragment implements WalletBalanceListener {
public static final String TAG = "CreateSupportDialog";
private MaterialButton sendButton;
private View cancelLink;
private TextInputEditText inputAmount;
private View inlineBalanceContainer;
private TextView inlineBalanceValue;
private ProgressBar sendProgress;
private InlineChannelSpinnerAdapter channelSpinnerAdapter;
private AppCompatSpinner channelSpinner;
private SwitchMaterial switchTip;
private boolean fetchingChannels;
private ProgressBar progressLoadingChannels;
@Setter
private CreateSupportListener listener;
@Setter
private Claim claim;
public static CreateSupportDialogFragment newInstance() {
return new CreateSupportDialogFragment();
}
private void disableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(false);
}
channelSpinner.setEnabled(false);
switchTip.setEnabled(false);
sendButton.setEnabled(false);
cancelLink.setEnabled(false);
}
private void enableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(true);
}
channelSpinner.setEnabled(true);
switchTip.setEnabled(true);
sendButton.setEnabled(true);
cancelLink.setEnabled(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_create_support, container, false);
inputAmount = view.findViewById(R.id.create_support_input_amount);
inlineBalanceContainer = view.findViewById(R.id.create_support_inline_balance_container);
inlineBalanceValue = view.findViewById(R.id.create_support_inline_balance_value);
sendProgress = view.findViewById(R.id.create_support_progress);
cancelLink = view.findViewById(R.id.create_support_cancel_link);
sendButton = view.findViewById(R.id.create_support_send);
channelSpinner = view.findViewById(R.id.create_support_channel_spinner);
switchTip = view.findViewById(R.id.create_support_make_tip_switch);
progressLoadingChannels = view.findViewById(R.id.create_support_channel_progress);
inputAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
inputAmount.setHint(hasFocus ? getString(R.string.zero) : "");
inlineBalanceContainer.setVisibility(hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
inputAmount.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
updateSendButtonText();
}
@Override
public void afterTextChanged(Editable editable) {
}
});
updateInfoText();
updateSendButtonText();
String channel = null;
if (Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType())) {
channel = claim.getTitleOrName();
} else if (claim.getSigningChannel() != null) {
channel = claim.getPublisherTitle();
}
TextView titleView = view.findViewById(R.id.create_support_title);
String tipTitleText = Helper.isNullOrEmpty(channel) ? getString(R.string.send_a_tip) : getString(R.string.send_a_tip_to, channel);
titleView.setText(tipTitleText);
switchTip.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
// show tip info
titleView.setText(tipTitleText);
updateSendButtonText();
} else {
// show support info
titleView.setText(R.string.support_this_content);
sendButton.setText(R.string.send_revocable_support);
}
updateInfoText();
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String amountString = Helper.getValue(inputAmount.getText());
if (Helper.isNullOrEmpty(amountString)) {
showError(getString(R.string.invalid_amount));
return;
}
BigDecimal amount = new BigDecimal(amountString);
if (amount.doubleValue() > Lbry.walletBalance.getAvailable().doubleValue()) {
showError(getString(R.string.insufficient_balance));
return;
}
if (amount.doubleValue() < Helper.MIN_SPEND) {
showError(getString(R.string.min_spend_required));
return;
}
Claim selectedChannel = (Claim) channelSpinner.getSelectedItem();
String channelId = !fetchingChannels && selectedChannel != null ? selectedChannel.getClaimId() : null;
boolean isTip = switchTip.isChecked();
SupportCreateTask task = new SupportCreateTask(
claim.getClaimId(), channelId, amount, isTip, sendProgress, new GenericTaskHandler() {
@Override
public void beforeStart() {
disableControls();
}
@Override
public void onSuccess() {
enableControls();
if (listener != null) {
listener.onSupportCreated(amount, isTip);
}
dismiss();
}
@Override
public void onError(Exception error) {
showError(error.getMessage());
enableControls();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
cancelLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
onWalletBalanceUpdated(Lbry.walletBalance);
updateInfoText();
return view;
}
private void updateSendButtonText() {
boolean isTip = switchTip.isChecked();
if (!isTip) {
sendButton.setText(R.string.send_revocable_support);
} else {
String amountString = Helper.getValue(inputAmount.getText());
double parsedAmount = Helper.parseDouble(amountString, 0);
sendButton.setText(parsedAmount == 0 ? getString(R.string.send_a_tip) : getString(R.string.send_lbc_tip, amountString));
}
}
private void updateInfoText() {
View view = getView();
if (view != null && switchTip != null) {
TextView infoText = view.findViewById(R.id.create_support_info);
boolean isTip = switchTip.isChecked();
infoText.setMovementMethod(LinkMovementMethod.getInstance());
if (!isTip) {
infoText.setText(HtmlCompat.fromHtml(getString(R.string.support_info), HtmlCompat.FROM_HTML_MODE_LEGACY));
} else if (claim != null) {
infoText.setText(HtmlCompat.fromHtml(
Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType()) ?
getString(R.string.send_tip_info_channel, claim.getTitleOrName()) :
getString(R.string.send_tip_info_content, claim.getTitleOrName()),
HtmlCompat.FROM_HTML_MODE_LEGACY));
}
}
}
private void fetchChannels() {
if (Lbry.ownChannels != null && Lbry.ownChannels.size() > 0) {
updateChannelList(Lbry.ownChannels);
return;
}
fetchingChannels = true;
disableChannelSpinner();
ClaimListTask task = new ClaimListTask(Claim.TYPE_CHANNEL, progressLoadingChannels, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownChannels = new ArrayList<>(claims);
updateChannelList(Lbry.ownChannels);
enableChannelSpinner();
fetchingChannels = false;
}
@Override
public void onError(Exception error) {
enableChannelSpinner();
fetchingChannels = false;
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void disableChannelSpinner() {
Helper.setViewEnabled(channelSpinner, false);
}
private void enableChannelSpinner() {
Helper.setViewEnabled(channelSpinner, true);
}
private void updateChannelList(List<Claim> channels) {
if (channelSpinnerAdapter == null) {
Context context = getContext();
if (context != null) {
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, new ArrayList<>(channels));
channelSpinnerAdapter.addAnonymousPlaceholder();
channelSpinnerAdapter.notifyDataSetChanged();
}
} else {
channelSpinnerAdapter.clear();
channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.addAnonymousPlaceholder();
channelSpinnerAdapter.notifyDataSetChanged();
}
if (channelSpinner != null) {
channelSpinner.setAdapter(channelSpinnerAdapter);
}
if (channelSpinnerAdapter != null && channelSpinner != null) {
if (channelSpinnerAdapter.getCount() > 1) {
channelSpinner.setSelection(1);
}
}
}
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).addWalletBalanceListener(this);
}
updateInfoText();
fetchChannels();
}
public void onPause() {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).removeWalletBalanceListener(this);
}
super.onPause();
}
@Override
public void onWalletBalanceUpdated(WalletBalance walletBalance) {
if (walletBalance != null && inlineBalanceValue != null) {
inlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
}
private void showError(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
public interface CreateSupportListener {
void onSupportCreated(BigDecimal amount, boolean isTip);
}
}
@@ -159,13 +159,7 @@ public class CustomizeTagsDialogFragment extends BottomSheetDialogFragment {
}
private void updateKnownTags(String filter, int limit, boolean clearPrevious) {
UpdateSuggestedTagsTask task = new UpdateSuggestedTagsTask(
filter,
SUGGESTED_LIMIT,
followedTagsAdapter,
suggestedTagsAdapter,
clearPrevious,
false, new UpdateSuggestedTagsTask.KnownTagsHandler() {
UpdateSuggestedTagsTask task = new UpdateSuggestedTagsTask(filter, SUGGESTED_LIMIT, followedTagsAdapter, suggestedTagsAdapter, clearPrevious, new UpdateSuggestedTagsTask.KnownTagsHandler() {
@Override
public void onSuccess(List<Tag> tags) {
if (suggestedTagsAdapter == null) {
@@ -84,16 +84,10 @@ public class DiscoverDialogFragment extends BottomSheetDialogFragment {
dialogActionsListener.onResume();
}
}
@Override
public void onCancel(DialogInterface dialog) {
super.onDismiss(dialog);
if (dialogActionsListener != null) {
dialogActionsListener.onCancel();
}
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
super.onCancel(dialog);
if (dialogActionsListener != null) {
dialogActionsListener.onCancel();
}
@@ -24,6 +24,7 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.FileViewActivity;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.InlineChannelSpinnerAdapter;
@@ -86,7 +87,7 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
textTitle.setText(getString(R.string.repost_title, claim.getTitle()));
inputName.setText(claim.getName());
inputDeposit.setText(R.string.min_deposit);
inputDeposit.setText(R.string.min_repost_deposit);
channelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
@@ -146,16 +147,16 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).addWalletBalanceListener(this);
if (context instanceof FileViewActivity) {
((FileViewActivity) context).addWalletBalanceListener(this);
}
fetchChannels();
}
public void onPause() {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).removeWalletBalanceListener(this);
if (context instanceof FileViewActivity) {
((FileViewActivity) context).removeWalletBalanceListener(this);
}
inputDeposit.clearFocus();
super.onPause();
@@ -177,8 +178,8 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
public void onError(Exception error) {
// could not fetch channels
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).showError(error.getMessage());
if (context instanceof FileViewActivity) {
((FileViewActivity) context).showError(error.getMessage());
}
dismiss();
}
@@ -192,16 +193,14 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
private void loadChannels(List<Claim> channels) {
if (channelSpinnerAdapter == null) {
Context context = getContext();
if (context != null) {
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, channels);
channelSpinnerAdapter.notifyDataSetChanged();
}
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, channels);
channelSpinnerAdapter.notifyDataSetChanged();
} else {
channelSpinnerAdapter.clear();
channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.notifyDataSetChanged();
}
if (channelSpinner != null && channelSpinnerAdapter != null) {
if (channelSpinner != null) {
channelSpinner.setAdapter(channelSpinnerAdapter);
}
}
@@ -231,18 +230,8 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
showError(getString(R.string.insufficient_balance));
return;
}
if (bid.doubleValue() < Helper.MIN_DEPOSIT) {
String message = getResources().getQuantityString(R.plurals.min_deposit_required, 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(message);
return;
}
Claim channel = (Claim) channelSpinner.getSelectedItem();
if (channel == null) {
showError(getString(R.string.please_select_repost_channel));
return;
}
StreamRepostTask task = new StreamRepostTask(name, bid, claim.getClaimId(), channel.getClaimId(), repostProgress, new ClaimResultHandler() {
@Override
public void beforeStart() {
@@ -268,13 +257,10 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
}
private void showError(String message) {
View view = getView();
if (view != null && !Helper.isNullOrEmpty(message)) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
private void startLoading() {
@@ -0,0 +1,197 @@
package io.lbry.browser.dialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.core.text.HtmlCompat;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import io.lbry.browser.FileViewActivity;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.listener.WalletBalanceListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.tasks.wallet.SupportCreateTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import lombok.Setter;
public class SendTipDialogFragment extends BottomSheetDialogFragment implements WalletBalanceListener {
public static final String TAG = "SendTipDialog";
private MaterialButton sendButton;
private View cancelLink;
private TextInputEditText inputAmount;
private View inlineBalanceContainer;
private TextView inlineBalanceValue;
private ProgressBar sendProgress;
@Setter
private SendTipListener listener;
@Setter
private Claim claim;
public static SendTipDialogFragment newInstance() {
return new SendTipDialogFragment();
}
private void disableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(false);
}
sendButton.setEnabled(false);
cancelLink.setEnabled(false);
}
private void enableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(true);
}
sendButton.setEnabled(true);
cancelLink.setEnabled(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_send_tip, container, false);
inputAmount = view.findViewById(R.id.tip_input_amount);
inlineBalanceContainer = view.findViewById(R.id.tip_inline_balance_container);
inlineBalanceValue = view.findViewById(R.id.tip_inline_balance_value);
sendProgress = view.findViewById(R.id.tip_send_progress);
cancelLink = view.findViewById(R.id.tip_cancel_link);
sendButton = view.findViewById(R.id.tip_send);
inputAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
inputAmount.setHint(hasFocus ? getString(R.string.zero) : "");
inlineBalanceContainer.setVisibility(hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
TextView infoText = view.findViewById(R.id.tip_info);
infoText.setMovementMethod(LinkMovementMethod.getInstance());
infoText.setText(HtmlCompat.fromHtml(
Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType()) ?
getString(R.string.send_tip_info_channel, claim.getTitleOrName()) :
getString(R.string.send_tip_info_content, claim.getTitleOrName()),
HtmlCompat.FROM_HTML_MODE_LEGACY));
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String amountString = Helper.getValue(inputAmount.getText());
if (Helper.isNullOrEmpty(amountString)) {
showError(getString(R.string.invalid_amount));
return;
}
BigDecimal amount = new BigDecimal(amountString);
if (amount.doubleValue() > Lbry.walletBalance.getAvailable().doubleValue()) {
showError(getString(R.string.insufficient_balance));
return;
}
SupportCreateTask task = new SupportCreateTask(claim.getClaimId(), amount, true, sendProgress, new GenericTaskHandler() {
@Override
public void beforeStart() {
disableControls();
}
@Override
public void onSuccess() {
enableControls();
if (listener != null) {
listener.onTipSent(amount);
}
dismiss();
}
@Override
public void onError(Exception error) {
showError(error.getMessage());
enableControls();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
cancelLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
String channel = null;
if (Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType())) {
channel = claim.getTitleOrName();
} else if (claim.getSigningChannel() != null) {
channel = claim.getPublisherTitle();
}
((TextView) view.findViewById(R.id.tip_send_title)).setText(
Helper.isNullOrEmpty(channel) ? getString(R.string.send_a_tip) : getString(R.string.send_a_tip_to, channel)
);
onWalletBalanceUpdated(Lbry.walletBalance);
return view;
}
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof FileViewActivity) {
((FileViewActivity) context).addWalletBalanceListener(this);
}
}
public void onPause() {
Context context = getContext();
if (context instanceof FileViewActivity) {
((FileViewActivity) context).removeWalletBalanceListener(this);
}
super.onPause();
}
@Override
public void onWalletBalanceUpdated(WalletBalance walletBalance) {
if (walletBalance != null && inlineBalanceValue != null) {
inlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
}
private void showError(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
public interface SendTipListener {
void onTipSent(BigDecimal amount);
}
}
@@ -1,4 +0,0 @@
package io.lbry.browser.exceptions;
public class AuthTokenInvalidatedException extends Exception {
}
@@ -1,8 +0,0 @@
package io.lbry.browser.listener;
public interface CameraPermissionListener {
void onCameraPermissionGranted();
void onCameraPermissionRefused();
void onRecordAudioPermissionGranted();
void onRecordAudioPermissionRefused();
}
@@ -1,5 +0,0 @@
package io.lbry.browser.listener;
public interface DownloadActionListener {
void onDownloadAction(String downloadAction, String uri, String outpoint, String fileInfoJson, double progress);
}
@@ -1,9 +0,0 @@
package io.lbry.browser.listener;
import java.util.List;
import io.lbry.browser.model.Claim;
public interface FetchClaimsListener {
void onClaimsFetched(List<Claim> claims);
}
@@ -1,6 +0,0 @@
package io.lbry.browser.listener;
public interface FilePickerListener {
void onFilePicked(String filePath);
void onFilePickerCancelled();
}
@@ -1,6 +0,0 @@
package io.lbry.browser.listener;
public interface PIPModeListener {
void onEnterPIPMode();
void onExitPIPMode();
}
@@ -1,6 +0,0 @@
package io.lbry.browser.listener;
public interface ScreenOrientationListener {
void onPortraitOrientationEntered();
void onLandscapeOrientationEntered();
}
@@ -7,7 +7,4 @@ public interface SignInListener {
void onPhoneAdded(String countryCode, String phoneNumber);
void onPhoneVerified();
void onManualVerifyContinue();
void onSkipQueueAction();
void onTwitterVerified();
void onManualProgress(boolean progress);
}
@@ -1,6 +0,0 @@
package io.lbry.browser.listener;
public interface StoragePermissionListener {
void onStoragePermissionGranted();
void onStoragePermissionRefused();
}
@@ -9,7 +9,6 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@@ -19,7 +18,6 @@ import java.util.stream.Stream;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Predefined;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -54,7 +52,6 @@ public class Claim {
@EqualsAndHashCode.Include
private boolean placeholder;
private boolean placeholderAnonymous;
private boolean loadingPlaceholder;
private boolean featured;
private boolean unresolved; // used for featured
private String address;
@@ -84,9 +81,6 @@ public class Claim {
private GenericMetadata value;
private LbryFile file; // associated file if it exists
// device it was viewed on (for view history)
private String device;
public static Claim claimFromOutput(JSONObject item) {
// we only need name, permanent_url, txid and nout
Claim claim = new Claim();
@@ -98,10 +92,6 @@ public class Claim {
return claim;
}
public String getOutpoint() {
return String.format("%s:%d", txid, nout);
}
public boolean isFree() {
if (!(value instanceof StreamMetadata)) {
return true;
@@ -111,24 +101,6 @@ public class Claim {
return fee == null || Helper.parseDouble(fee.getAmount(), 0) == 0;
}
public BigDecimal getActualCost(double usdRate) {
if (!(value instanceof StreamMetadata)) {
return new BigDecimal(0);
}
Fee fee = ((StreamMetadata) value).getFee();
if (fee != null) {
double amount = Helper.parseDouble(fee.getAmount(), 0);
if ("usd".equalsIgnoreCase(fee.getCurrency())) {
return new BigDecimal(String.valueOf(amount / usdRate));
}
return new BigDecimal(String.valueOf(amount)); // deweys
}
return new BigDecimal(0);
}
public String getMediaType() {
if (value instanceof StreamMetadata) {
StreamMetadata metadata = (StreamMetadata) value;
@@ -158,17 +130,6 @@ public class Claim {
}
return false;
}
public boolean isMature() {
List<String> tags = getTags();
if (tags != null && tags.size() > 0) {
for (String tag : tags) {
if (Predefined.MATURE_TAGS.contains(tag.toLowerCase())) {
return true;
}
}
}
return false;
}
public String getThumbnailUrl() {
if (value != null && value.getThumbnail() != null) {
@@ -266,8 +227,6 @@ public class Claim {
claim.setName(viewHistory.getClaimName());
claim.setValueType(TYPE_STREAM);
claim.setPermanentUrl(viewHistory.getUri().toString());
claim.setDevice(viewHistory.getDevice());
claim.setConfirmations(1);
StreamMetadata value = new StreamMetadata();
value.setTitle(viewHistory.getTitle());
@@ -280,8 +239,7 @@ public class Claim {
if (viewHistory.getCost() != null && viewHistory.getCost().doubleValue() > 0) {
Fee fee = new Fee();
fee.setAmount(String.valueOf(viewHistory.getCost().doubleValue()));
fee.setCurrency(viewHistory.getCurrency());
value.setFee(fee);
fee.setCurrency("LBC"); // always LBC
}
claim.setValue(value);
@@ -290,9 +248,6 @@ public class Claim {
Claim signingChannel = new Claim();
signingChannel.setClaimId(viewHistory.getPublisherClaimId());
signingChannel.setName(viewHistory.getPublisherName());
LbryUri channelUrl = LbryUri.tryParse(String.format("%s#%s", signingChannel.getName(), signingChannel.getClaimId()));
signingChannel.setPermanentUrl(channelUrl != null ? channelUrl.toString() : null);
if (!Helper.isNullOrEmpty(viewHistory.getPublisherTitle())) {
GenericMetadata channelValue = new GenericMetadata();
channelValue.setTitle(viewHistory.getPublisherTitle());
@@ -379,8 +334,7 @@ public class Claim {
Fee fee = null;
if (feeAmount > 0) {
fee = new Fee();
fee.setAmount(String.valueOf(new BigDecimal(String.valueOf(feeAmount)).divide(new BigDecimal(100000000))));
fee.setCurrency("LBC");
fee.setAmount(String.valueOf(feeAmount));
}
((StreamMetadata) metadata).setFee(fee);
@@ -399,10 +353,9 @@ public class Claim {
Claim signingChannel = new Claim();
signingChannel.setClaimId(searchResultObject.getString("channel_claim_id"));
signingChannel.setName(searchResultObject.getString("channel"));
LbryUri channelUri = new LbryUri();
channelUri.setChannelClaimId(signingChannel.getClaimId());
channelUri.setChannelName(signingChannel.getName());
signingChannel.setPermanentUrl(channelUri.toString());
claimUri.setChannelClaimId(signingChannel.getClaimId());
claimUri.setChannelName(signingChannel.getName());
claim.setSigningChannel(signingChannel);
}
@@ -5,36 +5,34 @@ import androidx.annotation.Nullable;
import io.lbry.browser.utils.Helper;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* Class to represent a key to check equality with another object
*/
@ToString
public class ClaimCacheKey {
@Getter
@Setter
private String claimId;
@Getter
@Setter
private String url;
public static ClaimCacheKey fromClaimShortUrl(Claim claim) {
ClaimCacheKey key = new ClaimCacheKey();
key.setUrl(claim.getShortUrl());
return key;
}
public static ClaimCacheKey fromClaimPermanentUrl(Claim claim) {
ClaimCacheKey key = new ClaimCacheKey();
key.setUrl(claim.getPermanentUrl());
return key;
}
private String canonicalUrl;
@Getter
@Setter
private String permanentUrl;
@Getter
@Setter
private String shortUrl;
@Getter
@Setter
private String vanityUrl;
public static ClaimCacheKey fromClaim(Claim claim) {
ClaimCacheKey key = new ClaimCacheKey();
key.setClaimId(claim.getClaimId());
key.setUrl(!Helper.isNullOrEmpty(claim.getShortUrl()) ? claim.getShortUrl() : claim.getPermanentUrl());
key.setCanonicalUrl(claim.getCanonicalUrl());
key.setPermanentUrl(claim.getPermanentUrl());
key.setShortUrl(claim.getShortUrl());
return key;
}
@@ -43,24 +41,44 @@ public class ClaimCacheKey {
if (obj == null || !(obj instanceof ClaimCacheKey)) {
return false;
}
ClaimCacheKey key = (ClaimCacheKey) obj;
if (!Helper.isNullOrEmpty(claimId) && !Helper.isNullOrEmpty(key.getClaimId())) {
return claimId.equalsIgnoreCase(key.getClaimId());
}
if (!Helper.isNullOrEmpty(url) && !Helper.isNullOrEmpty(key.getUrl())) {
return url.equalsIgnoreCase(key.getUrl());
if (!Helper.isNullOrEmpty(permanentUrl) && !Helper.isNullOrEmpty(key.getPermanentUrl())) {
return permanentUrl.equalsIgnoreCase(key.getPermanentUrl());
}
if (!Helper.isNullOrEmpty(canonicalUrl) && !Helper.isNullOrEmpty(key.getCanonicalUrl())) {
return canonicalUrl.equalsIgnoreCase(key.getCanonicalUrl());
}
if (!Helper.isNullOrEmpty(shortUrl) && !Helper.isNullOrEmpty(key.getShortUrl())) {
return shortUrl.equalsIgnoreCase(key.getShortUrl());
}
if (!Helper.isNullOrEmpty(vanityUrl) && !Helper.isNullOrEmpty(key.getVanityUrl())) {
return vanityUrl.equalsIgnoreCase(key.getVanityUrl());
}
return false;
}
@Override
public int hashCode() {
if (!Helper.isNullOrEmpty(url)) {
return url.hashCode();
}
if (!Helper.isNullOrEmpty(claimId)) {
return claimId.hashCode();
}
if (!Helper.isNullOrEmpty(permanentUrl)) {
return permanentUrl.hashCode();
}
if (!Helper.isNullOrEmpty(canonicalUrl)) {
return canonicalUrl.hashCode();
}
if (!Helper.isNullOrEmpty(shortUrl)) {
return shortUrl.hashCode();
}
if (!Helper.isNullOrEmpty(vanityUrl)) {
return vanityUrl.hashCode();
}
return super.hashCode();
}
@@ -1,69 +0,0 @@
package io.lbry.browser.model;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.utils.Helper;
import lombok.Data;
@Data
public class Comment {
public static final double LBC_COST = 1;
public static final int MAX_LENGTH = 2000;
private Claim poster;
private String claimId;
private List<Comment> replies;
private long timestamp;
private String channelId;
private String channelName, text, id, parentId;
public Comment(String channelId, String channelName, String text, String id, String parentId) {
this.channelId = channelId;
this.channelName = channelName;
this.text = text;
this.id = id;
this.parentId = parentId;
this.replies = new ArrayList<>();
}
public Comment() {
replies = new ArrayList<>();
}
public void addReply(Comment reply) {
if (replies == null) {
replies = new ArrayList<>();
}
if (!replies.contains(reply)) {
replies.add(reply);
}
}
public static Comment fromJSONObject(JSONObject jsonObject) {
try {
String parentId = null;
if (jsonObject.has("parent_id")) {
parentId = jsonObject.getString("parent_id");
}
Comment comment = new Comment(
Helper.getJSONString("channel_id", null, jsonObject),
jsonObject.getString("channel_name"),
jsonObject.getString("comment"),
jsonObject.getString("comment_id"),
parentId
);
comment.setClaimId(Helper.getJSONString("claim_id", null, jsonObject));
comment.setTimestamp(Helper.getJSONLong("timestamp", 0, jsonObject));
return comment;
} catch (JSONException ex) {
return null;
}
}
}
@@ -1,13 +0,0 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class GalleryItem {
private String id;
private String name;
private String filePath;
private String type;
private String thumbnailPath;
private long duration;
}
@@ -1,16 +0,0 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class Language {
private String code;
private String name;
private int stringResourceId;
public Language(String code, String name, int stringResourceId) {
this.code = code;
this.name = name;
this.stringResourceId = stringResourceId;
}
}
@@ -9,12 +9,9 @@ import org.json.JSONObject;
import java.lang.reflect.Type;
import io.lbry.browser.utils.LbryUri;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class LbryFile {
private Claim.StreamMetadata metadata;
private long addedOn;
@@ -23,7 +20,6 @@ public class LbryFile {
private int blobsRemaining;
private String channelClaimId;
private String channelName;
@EqualsAndHashCode.Include
private String claimId;
private String claimName;
private boolean completed;
@@ -43,50 +39,16 @@ public class LbryFile {
private String streamName;
private String streamingUrl;
private String suggestedFileName;
private long timestamp;
private long totalBytes;
private long totalBytesLowerBound;
private String txid;
private long writtenBytes;
private Claim generatedClaim;
public Claim getClaim() {
if (generatedClaim != null) {
return generatedClaim;
}
generatedClaim = new Claim();
generatedClaim.setValueType(Claim.TYPE_STREAM);
generatedClaim.setPermanentUrl(LbryUri.tryParse(String.format("%s#%s", claimName, claimId)).toString());
generatedClaim.setClaimId(claimId);
generatedClaim.setName(claimName);
generatedClaim.setValue(metadata);
generatedClaim.setConfirmations(1);
generatedClaim.setTxid(txid);
generatedClaim.setNout(nout);
generatedClaim.setFile(this);
if (channelClaimId != null) {
Claim signingChannel = new Claim();
signingChannel.setClaimId(channelClaimId);
signingChannel.setName(channelName);
signingChannel.setPermanentUrl(LbryUri.tryParse(String.format("%s#%s", claimName, claimId)).toString());
generatedClaim.setSigningChannel(signingChannel);
}
return generatedClaim;
}
public static LbryFile fromJSONObject(JSONObject fileObject) {
String fileJson = fileObject.toString();
Type type = new TypeToken<LbryFile>(){}.getType();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
LbryFile file = gson.fromJson(fileJson, type);
if (file.getMetadata() != null && file.getMetadata().getReleaseTime() == 0) {
file.getMetadata().setReleaseTime(file.getTimestamp());
}
return file;
}
}
@@ -1,20 +0,0 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class License {
private String name;
private String url;
private int stringResourceId;
public License(String name, int stringResourceId) {
this.name = name;
this.stringResourceId = stringResourceId;
}
public License(String name, String url, int stringResourceId) {
this.name = name;
this.url = url;
this.stringResourceId = stringResourceId;
}
}
@@ -5,9 +5,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.exceptions.LbryUriException;
@@ -55,22 +53,13 @@ public class Transaction {
int descStringId = -1;
TransactionInfo info = null;
List<TransactionInfo> infos = new ArrayList<>();
try {
if (jsonObject.has("abandon_info")) {
JSONArray array = jsonObject.getJSONArray("abandon_info");
if (array.length() > 0) {
if (array.length() == 1) {
info = TransactionInfo.fromJSONObject(array.getJSONObject(0));
descStringId = info.getBalanceDelta().doubleValue() == info.getAmount().doubleValue() ? R.string.unlock : R.string.abandon;
transaction.setAbandonInfo(info);
} else {
// multiple abandon infos (txo_spend unlock tip)
descStringId = R.string.unlock;
for (int i = 0; i < array.length(); i++) {
infos.add(TransactionInfo.fromJSONObject(array.getJSONObject(i)));
}
}
info = TransactionInfo.fromJSONObject(array.getJSONObject(0));
descStringId = R.string.abandon;
transaction.setAbandonInfo(info);
}
}
if (info == null && jsonObject.has("claim_info")) {
@@ -105,18 +94,8 @@ public class Transaction {
// pass
}
if (transaction.getValue().doubleValue() == 0) {
if (info != null && info.getBalanceDelta().doubleValue() != 0) {
transaction.setValue(info.getBalanceDelta());
} else if (infos.size() > 0) {
BigDecimal total = new BigDecimal(0);
for (TransactionInfo txInfo : infos) {
total = total.add(txInfo.getAmount());
}
transaction.setValue(total);
}
if (transaction.getValue().doubleValue() == 0 && info != null && info.getBalanceDelta().doubleValue() != 0) {
transaction.setValue(info.getBalanceDelta());
}
if (descStringId == -1) {
@@ -1,9 +0,0 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class TwitterOauth {
private String oauthToken;
private String oauthTokenSecret;
}
@@ -15,7 +15,6 @@ public class UrlSuggestion {
private LbryUri uri;
private Claim claim; // associated claim if resolved
private boolean titleTextOnly;
private boolean titleUrlOnly;
private boolean useTextAsDescription;
public UrlSuggestion() {
@@ -35,10 +34,6 @@ public class UrlSuggestion {
}
public String getTitle() {
if (titleUrlOnly && (type == TYPE_CHANNEL || type == TYPE_FILE)) {
return uri.toString();
}
if (!titleTextOnly) {
switch (type) {
case TYPE_CHANNEL:
@@ -5,7 +5,6 @@ import java.util.Date;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Lbryio;
import lombok.Data;
@Data
@@ -14,7 +13,6 @@ public class ViewHistory {
private String claimId;
private String claimName;
private BigDecimal cost;
private String currency;
private String title;
private String publisherClaimId;
private String publisherName;
@@ -41,14 +39,9 @@ public class ViewHistory {
Claim.StreamMetadata value = (Claim.StreamMetadata) metadata;
history.setReleaseTime(value.getReleaseTime());
if (value.getFee() != null) {
Fee fee = value.getFee();
history.setCost(new BigDecimal(fee.getAmount()));
history.setCurrency(fee.getCurrency());
history.setCost(new BigDecimal(value.getFee().getAmount()));
}
}
if (history.getReleaseTime() == 0) {
history.setReleaseTime(claim.getTimestamp());
}
Claim signingChannel = claim.getSigningChannel();
if (signingChannel != null) {
@@ -1,10 +1,7 @@
package io.lbry.browser.model;
import org.json.JSONObject;
import java.math.BigDecimal;
import io.lbry.browser.utils.Helper;
import lombok.Data;
@Data
@@ -24,18 +21,4 @@ public class WalletBalance {
tips = new BigDecimal(0);
total = new BigDecimal(0);
}
public static WalletBalance fromJSONObject(JSONObject json) {
WalletBalance balance = new WalletBalance();
JSONObject reservedSubtotals = Helper.getJSONObject("reserved_subtotals", json);
balance.setAvailable(new BigDecimal(Helper.getJSONString("available", "0", json)));
balance.setReserved(new BigDecimal(Helper.getJSONString("reserved", "0", json)));
balance.setTotal(new BigDecimal(Helper.getJSONString("total", "0", json)));
if (reservedSubtotals != null) {
balance.setClaims(new BigDecimal(Helper.getJSONString("claims", "0", reservedSubtotals)));
balance.setSupports(new BigDecimal(Helper.getJSONString("supports", "0", reservedSubtotals)));
balance.setTips(new BigDecimal(Helper.getJSONString("tips", "0", reservedSubtotals)));
}
return balance;
}
}
@@ -8,13 +8,9 @@ public class WalletSync {
private String data;
private boolean changed;
public WalletSync(String hash, String data) {
public WalletSync(String hash, String data, boolean changed) {
this.hash = hash;
this.data = data;
}
public WalletSync(String hash, String data, boolean changed) {
this(hash, data);
this.changed = changed;
}
}
@@ -1,40 +0,0 @@
package io.lbry.browser.model.lbryinc;
import java.util.Comparator;
import java.util.Date;
import io.lbry.browser.model.Claim;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true)
public class LbryNotification implements Comparator<LbryNotification> {
private long id;
@EqualsAndHashCode.Include
private long remoteId;
private String title;
private String description;
private String thumbnailUrl;
private String rule;
private String targetUrl;
private boolean read;
private boolean seen;
private Date timestamp;
// only for comment notifications
private String authorUrl;
private Claim commentAuthor;
public int compare(LbryNotification a, LbryNotification b) {
long t1 = a.getTimestamp() != null ? a.getTimestamp().getTime() : 0;
long t2 = b.getTimestamp() != null ? b.getTimestamp().getTime() : 0;
if (t1 < t2) {
return -1;
}
if (t1 > t2) {
return 1;
}
return 0;
}
}
@@ -1,9 +0,0 @@
package io.lbry.browser.model.lbryinc;
import lombok.Data;
@Data
public class RewardVerified {
private long userId;
private boolean isRewardApproved;
}
@@ -24,19 +24,6 @@ public class User {
private String primaryEmail;
private String rewardStatusChangeTrigger;
private String updatedAt;
private List<YoutubeChannel> youtubeChannels;
private List<String> youtubeChannels;
private List<String> deviceTypes;
@Data
public static class YoutubeChannel {
String ytChannelName;
String lbryChannelName;
String channelClaimId;
String syncStatus;
String statusToken;
boolean transferable;
String transferState;
List<String> publishToAddress;
String publicKey;
}
}
@@ -1,65 +0,0 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.util.concurrent.TimeUnit;
import io.lbry.browser.utils.Helper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class BufferEventTask extends AsyncTask<Void, Void, Void> {
private static final String TAG = "LbryBufferEvent";
private static final String ENDPOINT = "https://collector-service.api.lbry.tv/api/v1/events/video";
private String streamUrl;
private String userIdHash;
private long streamDuration;
private long streamPosition;
private long bufferDuration;
public BufferEventTask(String streamUrl, long streamDuration, long streamPosition, long bufferDuration, String userIdHash) {
this.streamUrl = streamUrl;
this.bufferDuration = bufferDuration;
this.streamDuration = streamDuration;
this.streamPosition = streamPosition;
this.userIdHash = userIdHash;
}
protected Void doInBackground(Void... params) {
JSONObject requestBody = new JSONObject();
JSONObject data = new JSONObject();
try {
data.put("url", streamUrl);
data.put("position", streamPosition);
data.put("stream_duration", streamDuration);
//data.put("duration", bufferDuration);
requestBody.put("device", "android");
requestBody.put("type", "buffering");
requestBody.put("client", userIdHash);
requestBody.put("data", data);
RequestBody body = RequestBody.create(requestBody.toString(), Helper.JSON_MEDIA_TYPE);
Request request = new Request.Builder().url(ENDPOINT).post(body).build();
OkHttpClient client = new OkHttpClient.Builder().
writeTimeout(60, TimeUnit.SECONDS).
readTimeout(60, TimeUnit.SECONDS).
build();
Response response = client.newCall(request).execute();
String responseString = response.body().string();
Log.d(TAG, String.format("buffer event sent: %s", responseString));
} catch (Exception ex) {
// we don't want to fail if a buffer event fails to register
Log.d(TAG, String.format("buffer event log failed: %s", ex.getMessage()), ex);
}
return null;
}
}
@@ -1,4 +1,4 @@
package io.lbry.browser.tasks.claim;
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.view.View;
@@ -9,9 +9,7 @@ import org.json.JSONObject;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
@@ -49,28 +47,14 @@ public class ChannelCreateUpdateTask extends AsyncTask<Void, Void, Claim> {
} else {
options.put("claim_id", claim.getClaimId());
}
options.put("bid", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)).format(deposit.doubleValue()));
if (!Helper.isNullOrEmpty(claim.getTitle())) {
options.put("title", claim.getTitle());
}
if (!Helper.isNullOrEmpty(claim.getCoverUrl())) {
options.put("cover_url", claim.getCoverUrl());
}
if (!Helper.isNullOrEmpty(claim.getThumbnailUrl())) {
options.put("thumbnail_url", claim.getThumbnailUrl());
}
if (!Helper.isNullOrEmpty(claim.getDescription())) {
options.put("description", claim.getDescription());
}
if (!Helper.isNullOrEmpty(claim.getWebsiteUrl())) {
options.put("website_url", claim.getWebsiteUrl());
}
if (!Helper.isNullOrEmpty(claim.getEmail())) {
options.put("email", claim.getEmail());
}
if (claim.getTags() != null && claim.getTags().size() > 0) {
options.put("tags", claim.getTags());
}
options.put("bid", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT).format(deposit.doubleValue()));
options.put("title", claim.getTitle());
options.put("cover_url", claim.getCoverUrl());
options.put("thumbnail_url", claim.getThumbnailUrl());
options.put("description", claim.getDescription());
options.put("website_url", claim.getWebsiteUrl());
options.put("email", claim.getEmail());
options.put("tags", claim.getTags());
options.put("blocking", true);
Claim claimResult = null;
@@ -1,103 +0,0 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.model.Comment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.Lbryio;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class CommentCreateWithTipTask extends AsyncTask<Void, Void, Comment> {
private static final String STATUS_ENDPOINT = "https://comments.lbry.com";
private Comment comment;
private BigDecimal amount;
private View progressView;
private CommentCreateWithTipHandler handler;
private Exception error;
public CommentCreateWithTipTask(Comment comment, BigDecimal amount, View progressView, CommentCreateWithTipHandler handler) {
this.comment = comment;
this.amount = amount;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
public Comment doInBackground(Void... params) {
Comment createdComment = null;
try {
// check comments status endpoint
Request request = new Request.Builder().url(STATUS_ENDPOINT).build();
OkHttpClient client = new OkHttpClient.Builder().
writeTimeout(30, TimeUnit.SECONDS).
readTimeout(30, TimeUnit.SECONDS).
build();
Response response = client.newCall(request).execute();
JSONObject status = new JSONObject(response.body().string());
String statusText = Helper.getJSONString("text", null, status);
boolean isRunning = Helper.getJSONBoolean("is_running", false, status);
if (!"ok".equalsIgnoreCase(statusText) || !isRunning) {
throw new ApiCallException("The comment server is not available at this time. Please try again later.");
}
Map<String, Object> options = new HashMap<>();
options.put("blocking", true);
options.put("claim_id", comment.getClaimId());
options.put("amount", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)).format(amount.doubleValue()));
options.put("tip", true);
Lbry.genericApiCall(Lbry.METHOD_SUPPORT_CREATE, options);
options = new HashMap<>();
options.put("comment", comment.getText());
options.put("claim_id", comment.getClaimId());
options.put("channel_id", comment.getChannelId());
options.put("channel_name", comment.getChannelName());
if (!Helper.isNullOrEmpty(comment.getParentId())) {
options.put("parent_id", comment.getParentId());
}
JSONObject jsonObject = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_COMMENT_CREATE, options);
createdComment = Comment.fromJSONObject(jsonObject);
} catch (ApiCallException | ClassCastException | IOException | JSONException ex) {
error = ex;
}
return createdComment;
}
protected void onPostExecute(Comment createdComment) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (createdComment != null) {
handler.onSuccess(createdComment);
} else {
handler.onError(error);
}
}
}
public interface CommentCreateWithTipHandler {
void onSuccess(Comment createdComment);
void onError(Exception error);
}
}
@@ -1,10 +0,0 @@
package io.lbry.browser.tasks;
import java.util.List;
import io.lbry.browser.model.Comment;
public interface CommentListHandler {
void onSuccess(List<Comment> comments, boolean hasReachedEnd);
void onError(Exception error);
}
@@ -1,95 +0,0 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.model.Comment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class CommentListTask extends AsyncTask<Void, Void, List<Comment>> {
private final int page;
private final int pageSize;
private final String claim;
private ProgressBar progressBar;
private CommentListHandler handler;
private Exception error;
public CommentListTask(int page, int pageSize, String claim, ProgressBar progressBar, CommentListHandler handler) {
this.page = page;
this.pageSize = pageSize;
this.claim = claim;
this.progressBar = progressBar;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressBar, View.VISIBLE);
}
protected List<Comment> doInBackground(Void... voids) {
List<Comment> comments = null;
try {
Map<String, Object> options = new HashMap<>();
options.put("claim_id", claim);
options.put("page", page);
options.put("page_size", pageSize);
options.put("hidden", false);
options.put("include_replies", false);
options.put("is_channel_signature_valid", true);
options.put("skip_validation", true);
options.put("visible", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_COMMENT_LIST, options);
JSONArray items = result.getJSONArray("items");
List<Comment> children = new ArrayList<>();
comments = new ArrayList<>();
for (int i = 0; i < items.length(); i++) {
Comment comment = Comment.fromJSONObject(items.getJSONObject(i));
if (comment != null) {
if (!Helper.isNullOrEmpty(comment.getParentId())) {
children.add(comment);
} else {
comments.add(comment);
}
}
}
for (Comment child : children) {
for (Comment parent : comments) {
if (parent.getId().equalsIgnoreCase(child.getParentId())) {
parent.addReply(child);
break;
}
}
}
} catch (Exception ex) {
error = ex;
}
return comments;
}
protected void onPostExecute(List<Comment> comments) {
Helper.setViewVisibility(progressBar, View.GONE);
if (handler != null) {
if (comments != null) {
handler.onSuccess(comments, comments.size() < pageSize);
} else {
handler.onError(error);
}
}
}
}
@@ -9,7 +9,7 @@ import java.util.List;
import io.lbry.browser.exceptions.LbryRequestException;
import io.lbry.browser.exceptions.LbryResponseException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.tasks.claim.ClaimSearchResultHandler;
import io.lbry.browser.tasks.claim.ClaimSearchTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lighthouse;
@@ -19,11 +19,11 @@ public class LighthouseSearchTask extends AsyncTask<Void, Void, List<Claim>> {
private int from;
private boolean nsfw;
private String relatedTo;
private ClaimSearchResultHandler handler;
private ClaimSearchTask.ClaimSearchResultHandler handler;
private ProgressBar progressBar;
private Exception error;
public LighthouseSearchTask(String rawQuery, int size, int from, boolean nsfw, String relatedTo, ProgressBar progressBar, ClaimSearchResultHandler handler) {
public LighthouseSearchTask(String rawQuery, int size, int from, boolean nsfw, String relatedTo, ProgressBar progressBar, ClaimSearchTask.ClaimSearchResultHandler handler) {
this.rawQuery = rawQuery;
this.size = size;
this.from = from;
@@ -24,7 +24,6 @@ import io.lbry.browser.model.lbryinc.Subscription;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Lbryio;
import okhttp3.Response;
// background task to create a diff of local and remote subscriptions and try to merge
public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscription>> {
@@ -34,11 +33,9 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
private List<Subscription> diff;
private MergeSubscriptionsHandler handler;
private Exception error;
private boolean replaceLocal;
public MergeSubscriptionsTask(List<Subscription> base, boolean replaceLocal, Context context, MergeSubscriptionsHandler handler) {
public MergeSubscriptionsTask(List<Subscription> base, Context context, MergeSubscriptionsHandler handler) {
this.base = base;
this.replaceLocal = replaceLocal;
this.context = context;
this.handler = handler;
}
@@ -55,17 +52,10 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
db = ((MainActivity) context).getDbHelper().getWritableDatabase();
}
if (db != null) {
if (replaceLocal) {
DatabaseHelper.clearSubscriptions(db);
for (Subscription sub : base) {
DatabaseHelper.createOrUpdateSubscription(sub, db);
}
} else {
localSubs = DatabaseHelper.getSubscriptions(db);
for (Subscription sub : localSubs) {
if (!combined.contains(sub)) {
combined.add(sub);
}
localSubs = DatabaseHelper.getSubscriptions(db);
for (Subscription sub : localSubs) {
if (!combined.contains(sub)) {
combined.add(sub);
}
}
}
@@ -73,7 +63,6 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
// fetch remote subscriptions
JSONArray array = (JSONArray) Lbryio.parseResponse(Lbryio.call("subscription", "list", context));
if (array != null) {
// check for any remote subs that may have been removed, and unsubscribe from them
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
String claimId = item.getString("claim_id");
@@ -87,45 +76,43 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
}
}
List<Subscription> remoteUnsubs = new ArrayList<>();
List<Subscription> finalRemoteSubs = new ArrayList<>();
if (remoteSubs.size() > 0) {
for (int i = 0; i < remoteSubs.size(); i++) {
Subscription sub = remoteSubs.get(i);
if (!combined.contains(sub)) {
for (int i = 0; i < combined.size(); i++) {
Subscription local = combined.get(i);
if (!remoteSubs.contains(local)) {
// add to remote subscriptions
try {
LbryUri uri = LbryUri.parse(local.getUrl());
Map<String, String> options = new HashMap<>();
LbryUri uri = LbryUri.tryParse(sub.getUrl());
if (uri != null) {
options.put("claim_id", uri.getChannelClaimId());
Lbryio.parseResponse(Lbryio.call("subscription", "delete", options, context));
remoteUnsubs.add(sub);
} else {
finalRemoteSubs.add(sub);
}
options.put("claim_id", uri.getChannelClaimId());
options.put("channel_name", local.getChannelName());
Lbryio.call("subscription", "new", options, context);
} catch (LbryUriException | LbryioRequestException | LbryioResponseException ex) {
// pass
Log.e(TAG, String.format("subscription/new failed: %s", ex.getMessage()), ex);
}
}
}
if (!replaceLocal) {
for (int i = 0; i < localSubs.size(); i++) {
Subscription local = localSubs.get(i);
if (!base.contains(local) && !diff.contains(local)) {
diff.add(local);
}
for (int i = 0; i < localSubs.size(); i++) {
Subscription local = localSubs.get(i);
if (!base.contains(local) && !diff.contains(local)) {
diff.add(local);
}
for (int i = 0; i < finalRemoteSubs.size(); i++) {
Subscription remote = finalRemoteSubs.get(i);
if (!combined.contains(remote)) {
combined.add(remote);
if (!diff.contains(remote)) {
diff.add(remote);
}
}
for (int i = 0; i < remoteSubs.size(); i++) {
Subscription remote = remoteSubs.get(i);
if (!combined.contains(remote)) {
combined.add(remote);
if (!diff.contains(remote)) {
diff.add(remote);
}
}
}
} catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException | IllegalStateException | SQLiteException ex) {
} catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException | SQLiteException ex) {
error = ex;
return null;
} finally {
Helper.closeDatabase(db);
}
return combined;
@@ -1,8 +0,0 @@
package io.lbry.browser.tasks;
import io.lbry.browser.model.lbryinc.RewardVerified;
public interface RewardVerifiedHandler {
void onSuccess(RewardVerified rewardVerified);
void onError(Exception error);
}
@@ -1,45 +0,0 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import java.util.HashMap;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.utils.Lbry;
public class SetSdkSettingTask extends AsyncTask<Void, Void, Boolean> {
private String key;
private String value;
private GenericTaskHandler handler;
private Exception error;
public SetSdkSettingTask(String key, String value, GenericTaskHandler handler) {
this.key = key;
this.value = value;
this.handler = handler;
}
@Override
protected Boolean doInBackground(Void... params) {
try {
Map<String, Object> options = new HashMap<>();
options.put("key", key);
options.put("value", value);
Lbry.genericApiCall("setting_set", options);
return true;
} catch (ApiCallException ex) {
error = ex;
return false;
}
}
protected void onPostExecute(Boolean result) {
if (handler != null) {
if (result) {
handler.onSuccess();
} else {
handler.onError(error);
}
}
}
}
@@ -1,8 +0,0 @@
package io.lbry.browser.tasks;
import io.lbry.browser.model.TwitterOauth;
public interface TwitterOauthHandler {
void onSuccess(TwitterOauth twitterOauth);
void onError(Exception error);
}
@@ -14,27 +14,18 @@ import io.lbry.browser.utils.Lbry;
public class UpdateSuggestedTagsTask extends AsyncTask<Void, Void, List<Tag>> {
private boolean clearPrevious;
private boolean excludeMature;
private int limit;
private String filter;
private TagListAdapter addedTagsAdapter;
private TagListAdapter suggestedTagsAdapter;
private KnownTagsHandler handler;
public UpdateSuggestedTagsTask(
String filter,
int limit,
TagListAdapter addedTagsAdapter,
TagListAdapter suggestedTagsAdapter,
boolean clearPrevious,
boolean excludeMature,
KnownTagsHandler handler) {
public UpdateSuggestedTagsTask(String filter, int limit, TagListAdapter addedTagsAdapter, TagListAdapter suggestedTagsAdapter, boolean clearPrevious, KnownTagsHandler handler) {
this.filter = filter;
this.limit = limit;
this.addedTagsAdapter = addedTagsAdapter;
this.suggestedTagsAdapter = suggestedTagsAdapter;
this.clearPrevious = clearPrevious;
this.excludeMature = excludeMature;
this.handler = handler;
}
@@ -45,15 +36,10 @@ public class UpdateSuggestedTagsTask extends AsyncTask<Void, Void, List<Tag>> {
if (suggestedTagsAdapter != null && !clearPrevious) {
tags = new ArrayList<>(suggestedTagsAdapter.getTags());
}
if (Lbry.knownTags.size() > 0) {
while (tags.size() < limit) {
Tag randomTag = Lbry.knownTags.get(random.nextInt(Lbry.knownTags.size()));
if (excludeMature && randomTag.isMature()) {
continue;
}
if (!Lbry.followedTags.contains(randomTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(randomTag))) {
tags.add(randomTag);
}
while (tags.size() < limit) {
Tag randomTag = Lbry.knownTags.get(random.nextInt(Lbry.knownTags.size()));
if (!Lbry.followedTags.contains(randomTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(randomTag))) {
tags.add(randomTag);
}
}
} else {
@@ -63,18 +49,10 @@ public class UpdateSuggestedTagsTask extends AsyncTask<Void, Void, List<Tag>> {
}
for (int i = 0; i < Lbry.knownTags.size() && tags.size() < limit - 1; i++) {
Tag knownTag = Lbry.knownTags.get(i);
if (excludeMature && knownTag.isMature()) {
continue;
}
try {
if ((knownTag.getLowercaseName().startsWith(filter) ||
knownTag.getLowercaseName().matches(filter)) &&
(!tags.contains(knownTag) && !Lbry.followedTags.contains(knownTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(knownTag)))
) {
tags.add(knownTag);
}
} catch (Exception ex) {
// continue
if ((knownTag.getLowercaseName().startsWith(filter) || knownTag.getLowercaseName().matches(filter)) &&
(!tags.contains(knownTag) &&
!Lbry.followedTags.contains(knownTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(knownTag)))) {
tags.add(knownTag);
}
}
}
@@ -7,9 +7,9 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Random;
import java.io.File;
import java.util.concurrent.TimeUnit;
import io.lbry.browser.exceptions.LbryResponseException;
import io.lbry.browser.utils.Helper;
@@ -47,17 +47,14 @@ public class UploadImageTask extends AsyncTask<Void, Void, String> {
}
String fileType = String.format("image/%s", extension);
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).
addFormDataPart("name", Helper.makeid(24)).
addFormDataPart("name", makeid()).
addFormDataPart("file", fileName, RequestBody.create(file, MediaType.parse(fileType))).
build();
Request request = new Request.Builder().url("https://spee.ch/api/claim/publish").post(body).build();
OkHttpClient client = new OkHttpClient.Builder().
writeTimeout(300, TimeUnit.SECONDS).
readTimeout(300, TimeUnit.SECONDS).
build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
JSONObject json = new JSONObject(response.body().string());
if (json.has("success") && Helper.getJSONBoolean("success", false, json)) {
if (json.has("success")) {
JSONObject data = json.getJSONObject("data");
String url = Helper.getJSONString("url", null, data);
if (Helper.isNullOrEmpty(url)) {
@@ -65,15 +62,9 @@ public class UploadImageTask extends AsyncTask<Void, Void, String> {
}
thumbnailUrl = String.format("%s.%s", url, extension);
} else if (json.has("error") || json.has("message")) {
JSONObject error = Helper.getJSONObject("error", json);
String message = null;
if (error != null) {
message = Helper.getJSONString("message", null, error);
}
if (Helper.isNullOrEmpty(message)) {
message = Helper.getJSONString("message", null, json);
}
} else if (json.has("error")) {
JSONObject error = json.getJSONObject("error");
String message = Helper.getJSONString("message", null, error);
throw new LbryResponseException(Helper.isNullOrEmpty(message) ? "The image failed to upload." : message);
}
} catch (IOException | JSONException | LbryResponseException ex) {
@@ -93,6 +84,16 @@ public class UploadImageTask extends AsyncTask<Void, Void, String> {
}
}
private static String makeid() {
Random random = new Random();
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder id = new StringBuilder();
for (int i = 0; i < 24; i++) {
id.append(chars.charAt(random.nextInt(chars.length())));
}
return id.toString();
}
public interface UploadThumbnailHandler {
void onSuccess(String url);
void onError(Exception error);
@@ -1,63 +0,0 @@
package io.lbry.browser.tasks.claim;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class AbandonChannelTask extends AsyncTask<Void, Void, Boolean> {
private List<String> claimIds;
private List<String> successfulClaimIds;
private List<String> failedClaimIds;
private List<Exception> failedExceptions;
private View progressView;
private AbandonHandler handler;
public AbandonChannelTask(List<String> claimIds, View progressView, AbandonHandler handler) {
this.claimIds = claimIds;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
public Boolean doInBackground(Void... params) {
successfulClaimIds = new ArrayList<>();
failedClaimIds = new ArrayList<>();
failedExceptions = new ArrayList<>();
for (String claimId : claimIds) {
try {
Map<String, Object> options = new HashMap<>();
options.put("claim_id", claimId);
options.put("blocking", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_CHANNEL_ABANDON, options);
successfulClaimIds.add(claimId);
} catch (ApiCallException ex) {
failedClaimIds.add(claimId);
failedExceptions.add(ex);
}
}
return true;
}
protected void onPostExecute(Boolean result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
handler.onComplete(successfulClaimIds, failedClaimIds, failedExceptions);
}
}
}
@@ -1,7 +0,0 @@
package io.lbry.browser.tasks.claim;
import java.util.List;
public interface AbandonHandler {
void onComplete(List<String> successfulClaimIds, List<String> failedClaimIds, List<Exception> errors);
}
@@ -1,63 +0,0 @@
package io.lbry.browser.tasks.claim;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class AbandonStreamTask extends AsyncTask<Void, Void, Boolean> {
private List<String> claimIds;
private List<String> successfulClaimIds;
private List<String> failedClaimIds;
private List<Exception> failedExceptions;
private View progressView;
private AbandonHandler handler;
public AbandonStreamTask(List<String> claimIds, View progressView, AbandonHandler handler) {
this.claimIds = claimIds;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
public Boolean doInBackground(Void... params) {
successfulClaimIds = new ArrayList<>();
failedClaimIds = new ArrayList<>();
failedExceptions = new ArrayList<>();
for (String claimId : claimIds) {
try {
Map<String, Object> options = new HashMap<>();
options.put("claim_id", claimId);
options.put("blocking", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_STREAM_ABANDON, options);
successfulClaimIds.add(claimId);
} catch (ApiCallException ex) {
failedClaimIds.add(claimId);
failedExceptions.add(ex);
}
}
return true;
}
protected void onPostExecute(Boolean result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
handler.onComplete(successfulClaimIds, failedClaimIds, failedExceptions);
}
}
}
@@ -8,7 +8,6 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -19,16 +18,13 @@ import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class ClaimListTask extends AsyncTask<Void, Void, List<Claim>> {
private List<String> types;
private String type;
private View progressView;
private ClaimListResultHandler handler;
private Exception error;
public ClaimListTask(String type, View progressView, ClaimListResultHandler handler) {
this(Arrays.asList(type), progressView, handler);
}
public ClaimListTask(List<String> types, View progressView, ClaimListResultHandler handler) {
this.types = types;
this.type = type;
this.progressView = progressView;
this.handler = handler;
}
@@ -40,8 +36,8 @@ public class ClaimListTask extends AsyncTask<Void, Void, List<Claim>> {
try {
Map<String, Object> options = new HashMap<>();
if (types != null && types.size() > 0) {
options.put("claim_type", types);
if (!Helper.isNullOrEmpty(type)) {
options.put("claim_type", type);
}
options.put("page", 1);
options.put("page_size", 999);
@@ -62,8 +58,7 @@ public class ClaimListTask extends AsyncTask<Void, Void, List<Claim>> {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (claims != null) {
// TODO: Add fix for handling invalid reposts in ClaimListAdapter
handler.onSuccess(Helper.filterInvalidReposts(claims));
handler.onSuccess(claims);
} else {
handler.onError(error);
}
@@ -1,10 +0,0 @@
package io.lbry.browser.tasks.claim;
import java.util.List;
import io.lbry.browser.model.Claim;
public interface ClaimSearchResultHandler {
void onSuccess(List<Claim> claims, boolean hasReachedEnd);
void onError(Exception error);
}
@@ -2,6 +2,7 @@ package io.lbry.browser.tasks.claim;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import java.util.List;
import java.util.Map;
@@ -39,11 +40,15 @@ public class ClaimSearchTask extends AsyncTask<Void, Void, List<Claim>> {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (claims != null) {
handler.onSuccess(Helper.filterInvalidReposts(claims), claims.size() < Helper.parseInt(options.get("page_size"), 0));
handler.onSuccess(claims, claims.size() < Helper.parseInt(options.get("page_size"), 0));
} else {
handler.onError(error);
}
}
}
public interface ClaimSearchResultHandler {
void onSuccess(List<Claim> claims, boolean hasReachedEnd);
void onError(Exception error);
}
}
@@ -1,114 +0,0 @@
package io.lbry.browser.tasks.claim;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class PublishClaimTask extends AsyncTask<Void, Void, Claim> {
private Claim claim;
private String filePath;
private View progressView;
private ClaimResultHandler handler;
private Exception error;
public PublishClaimTask(Claim claim, String filePath, View progressView, ClaimResultHandler handler) {
this.claim = claim;
this.filePath = filePath;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
if (handler != null) {
handler.beforeStart();
}
}
protected Claim doInBackground(Void... params) {
Claim.StreamMetadata metadata = (Claim.StreamMetadata) claim.getValue();
DecimalFormat amountFormat = new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US));
Map<String, Object> options = new HashMap<>();
options.put("blocking", true);
options.put("name", claim.getName());
options.put("bid", amountFormat.format(new BigDecimal(claim.getAmount()).doubleValue()));
options.put("title", Helper.isNullOrEmpty(claim.getTitle()) ? "" : claim.getTitle());
options.put("description", Helper.isNullOrEmpty(claim.getDescription()) ? "" : claim.getDescription());
options.put("thumbnail_url", Helper.isNullOrEmpty(claim.getThumbnailUrl()) ? "" : claim.getThumbnailUrl());
if (!Helper.isNullOrEmpty(filePath)) {
options.put("file_path", filePath);
}
if (claim.getTags() != null && claim.getTags().size() > 0) {
options.put("tags", new ArrayList<>(claim.getTags()));
}
if (metadata.getFee() != null) {
options.put("fee_currency", metadata.getFee().getCurrency());
options.put("fee_amount", amountFormat.format(new BigDecimal(metadata.getFee().getAmount()).doubleValue()));
}
if (claim.getSigningChannel() != null) {
options.put("channel_id", claim.getSigningChannel().getClaimId());
}
if (metadata.getLanguages() != null && metadata.getLanguages().size() > 0) {
options.put("languages", metadata.getLanguages());
}
if (!Helper.isNullOrEmpty(metadata.getLicense())) {
options.put("license", metadata.getLicense());
}
if (!Helper.isNullOrEmpty(metadata.getLicenseUrl())) {
options.put("license_url", metadata.getLicenseUrl());
}
if (metadata.getReleaseTime() > 0) {
options.put("release_time", metadata.getReleaseTime());
} else if (claim.getTimestamp() > 0) {
options.put("release_time", claim.getTimestamp());
} else {
options.put("release_time", Double.valueOf(Math.floor(System.currentTimeMillis() / 1000.0)).intValue());
}
Claim claimResult = null;
try {
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_PUBLISH, options);
if (result.has("outputs")) {
JSONArray outputs = result.getJSONArray("outputs");
for (int i = 0; i < outputs.length(); i++) {
JSONObject output = outputs.getJSONObject(i);
if (output.has("claim_id") && output.has("claim_op")) {
claimResult = Claim.claimFromOutput(output);
break;
}
}
}
} catch (ApiCallException | ClassCastException | JSONException ex) {
error = ex;
}
return claimResult;
}
protected void onPostExecute(Claim result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (result != null) {
handler.onSuccess(result);
} else {
handler.onError(error);
}
}
}
}
@@ -1,85 +0,0 @@
package io.lbry.browser.tasks.claim;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class PurchaseListTask extends AsyncTask<Void, Void, List<Claim>> {
private String claimId;
private int page;
private int pageSize;
private ClaimSearchResultHandler handler;
private View progressView;
private Exception error;
public PurchaseListTask(String claimId, View progressView, ClaimSearchResultHandler handler) {
this.claimId = claimId;
this.progressView = progressView;
this.handler = handler;
}
public PurchaseListTask(int page, int pageSize, View progressView, ClaimSearchResultHandler handler) {
this.page = page;
this.pageSize = pageSize;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected List<Claim> doInBackground(Void... params) {
List<Claim> claims = null;
try {
Map<String, Object> options = new HashMap<>();
if (!Helper.isNullOrEmpty(claimId)) {
options.put("claim_id", claimId);
}
if (page > 0) {
options.put("page", page);
}
if (pageSize > 0) {
options.put("page_size", pageSize);
}
options.put("resolve", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_PURCHASE_LIST, options);
JSONArray items = result.getJSONArray("items");
claims = new ArrayList<>();
for (int i = 0; i < items.length(); i++) {
Claim claim = Claim.fromJSONObject(items.getJSONObject(i).getJSONObject("claim"));
if (!Helper.isNullOrEmpty(claim.getClaimId())) {
claims.add(claim);
Lbry.addClaimToCache(claim);
}
}
} catch (ApiCallException | JSONException | ClassCastException ex) {
error = ex;
}
return claims;
}
protected void onPostExecute(List<Claim> claims) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (claims != null) {
handler.onSuccess(claims, claims.size() < pageSize);
} else {
handler.onError(error);
}
}
}
}
@@ -34,7 +34,7 @@ public class ResolveTask extends AsyncTask<Void, Void, List<Claim>> {
}
protected List<Claim> doInBackground(Void... params) {
try {
return Helper.filterInvalidReposts(Lbry.resolve(urls, connectionString));
return Lbry.resolve(urls, connectionString);
} catch (ApiCallException ex) {
error = ex;
return null;
@@ -9,9 +9,7 @@ import org.json.JSONObject;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
@@ -42,7 +40,7 @@ public class StreamRepostTask extends AsyncTask<Void, Void, Claim> {
try {
Map<String, Object> options = new HashMap<>();
options.put("name", name);
options.put("bid", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)).format(bid.doubleValue()));
options.put("bid", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT).format(bid.doubleValue()));
options.put("claim_id", claimId);
options.put("channel_id", channelId);
@@ -1,32 +0,0 @@
package io.lbry.browser.tasks.file;
import android.os.AsyncTask;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.utils.Lbry;
// Just run delete on the specified claim IDs (no need for a handler)
public class BulkDeleteFilesTask extends AsyncTask<Void, Void, Boolean> {
private List<String> claimIds;
public BulkDeleteFilesTask(List<String> claimIds) {
this.claimIds = claimIds;
}
protected Boolean doInBackground(Void... params) {
for (String claimId : claimIds) {
try {
Map<String, Object> options = new HashMap<>();
options.put("claim_id", claimId);
options.put("delete_from_download_dir", true);
Lbry.genericApiCall(Lbry.METHOD_FILE_DELETE, options);
} catch (ApiCallException ex) {
// pass
}
}
return true;
}
}
@@ -26,7 +26,6 @@ public class DeleteFileTask extends AsyncTask<Void, Void, Boolean> {
options.put("delete_from_download_dir", true);
return (boolean) Lbry.genericApiCall(Lbry.METHOD_FILE_DELETE, options);
} catch (ApiCallException ex) {
error = ex;
return false;
}
}
@@ -12,18 +12,12 @@ import io.lbry.browser.utils.Lbry;
public class FileListTask extends AsyncTask<Void, Void, List<LbryFile>> {
private String claimId;
private boolean downloads;
private int page;
private int pageSize;
private FileListResultHandler handler;
private View progressView;
private ApiCallException error;
public FileListTask(int page, int pageSize, boolean downloads, View progressView, FileListResultHandler handler) {
public FileListTask(View progressView, FileListResultHandler handler) {
this(null, progressView, handler);
this.page = page;
this.pageSize = pageSize;
this.downloads = downloads;
}
public FileListTask(String claimId, View progressView, FileListResultHandler handler) {
@@ -36,7 +30,7 @@ public class FileListTask extends AsyncTask<Void, Void, List<LbryFile>> {
}
protected List<LbryFile> doInBackground(Void... params) {
try {
return Lbry.fileList(claimId, downloads, page, pageSize);
return Lbry.fileList(claimId);
} catch (ApiCallException ex) {
error = ex;
return null;
@@ -46,7 +40,7 @@ public class FileListTask extends AsyncTask<Void, Void, List<LbryFile>> {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (files != null) {
handler.onSuccess(files, files.size() < pageSize);
handler.onSuccess(files);
} else {
handler.onError(error);
}
@@ -54,7 +48,7 @@ public class FileListTask extends AsyncTask<Void, Void, List<LbryFile>> {
}
public interface FileListResultHandler {
void onSuccess(List<LbryFile> files, boolean hasReachedEnd);
void onSuccess(List<LbryFile> files);
void onError(Exception error);
}
}
@@ -1,68 +0,0 @@
package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import io.lbry.browser.MainActivity;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
import okhttp3.Response;
public class AndroidPurchaseTask extends AsyncTask<Void, Void, RewardVerified> {
private Context context;
private View progressView;
private String purchaseToken;
private RewardVerifiedHandler handler;
private Exception error;
public AndroidPurchaseTask(String purchaseToken, View progressView, Context context, RewardVerifiedHandler handler) {
this.purchaseToken = purchaseToken;
this.progressView = progressView;
this.context = context;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected RewardVerified doInBackground(Void... params) {
try {
Map<String, String> options = new HashMap<>();
options.put("purchase_token", purchaseToken);
JSONObject object = (JSONObject) Lbryio.parseResponse(Lbryio.call("verification", "android_purchase", options, context));
Type type = new TypeToken<RewardVerified>(){}.getType();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
return gson.fromJson(object.toString(), type);
} catch (Exception ex) {
error = ex;
return null;
}
}
protected void onPostExecute(RewardVerified result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (result != null) {
handler.onSuccess(result);
} else {
handler.onError(error);
}
}
}
}
@@ -64,6 +64,8 @@ public class ChannelSubscribeTask extends AsyncTask<Void, Void, Boolean> {
} catch (LbryioRequestException | LbryioResponseException | SQLiteException ex) {
error = ex;
return false;
} finally {
Helper.closeDatabase(db);
}
return true;
@@ -4,12 +4,9 @@ import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
@@ -17,8 +14,6 @@ import io.lbry.browser.R;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.lbryinc.Reward;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.Lbryio;
@@ -27,15 +22,15 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
private Context context;
private String type;
private String rewardCode;
private String claimCode;
private View progressView;
private double amountClaimed;
private ClaimRewardHandler handler;
private Exception error;
public ClaimRewardTask(String type, String rewardCode, View progressView, Context context, ClaimRewardHandler handler) {
public ClaimRewardTask(String type, String claimCode, View progressView, Context context, ClaimRewardHandler handler) {
this.type = type;
this.rewardCode = rewardCode;
this.claimCode = claimCode;
this.progressView = progressView;
this.context = context;
this.handler = handler;
@@ -48,27 +43,15 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
public String doInBackground(Void... params) {
String message = null;
try {
String txid = null;
if (Reward.TYPE_FIRST_CHANNEL.equalsIgnoreCase(type)) {
// fetch a channel
txid = fetchSingleClaimTxid(Claim.TYPE_CHANNEL);
} else if (Reward.TYPE_FIRST_PUBLISH.equalsIgnoreCase(type)) {
// fetch a publish
txid = fetchSingleClaimTxid(Claim.TYPE_STREAM);
}
// Get a new wallet address for the reward
String address = (String) Lbry.genericApiCall(Lbry.METHOD_ADDRESS_UNUSED);
Map<String, String> options = new HashMap<>();
options.put("reward_type", type);
options.put("wallet_address", address);
if (!Helper.isNullOrEmpty(rewardCode)) {
options.put("code", rewardCode);
}
if (!Helper.isNullOrEmpty(txid)) {
options.put("transaction_id", txid);
}
if (!Helper.isNullOrEmpty(claimCode)) {
options.put("claim_code", claimCode);
}
JSONObject reward = (JSONObject) Lbryio.parseResponse(
Lbryio.call("reward", "claim", options, Helper.METHOD_POST, null));
amountClaimed = Helper.getJSONDouble("reward_amount", 0, reward);
@@ -78,7 +61,7 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
amountClaimed == 1 ? 1 : 2,
new DecimalFormat(Helper.LBC_CURRENCY_FORMAT_PATTERN).format(amountClaimed)) : "";
message = Helper.getJSONString("reward_notification", defaultMessage, reward);
} catch (ApiCallException | JSONException | LbryioRequestException | LbryioResponseException ex) {
} catch (ApiCallException | LbryioRequestException | LbryioResponseException ex) {
error = ex;
}
@@ -96,23 +79,6 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
}
}
private String fetchSingleClaimTxid(String claimType) throws ApiCallException, JSONException {
Map<String, Object> options = new HashMap<>();
options.put("claim_type", claimType);
options.put("page", 1);
options.put("page_size", 1);
options.put("resolve", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_CLAIM_LIST, options);
JSONArray items = result.getJSONArray("items");
if (items.length() > 0) {
Claim claim = Claim.fromJSONObject(items.getJSONObject(0));
return claim.getTxid();
}
return null;
}
public interface ClaimRewardHandler {
void onSuccess(double amountClaimed, String message);
void onError(Exception error);
@@ -1,23 +1,20 @@
package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.os.AsyncTask;
import io.lbry.browser.model.lbryinc.User;
import io.lbry.browser.utils.Lbryio;
public class FetchCurrentUserTask extends AsyncTask<Void, Void, User> {
private Context context;
private Exception error;
private FetchUserTaskHandler handler;
public FetchCurrentUserTask(Context context, FetchUserTaskHandler handler) {
this.context = context;
public FetchCurrentUserTask(FetchUserTaskHandler handler) {
this.handler = handler;
}
protected User doInBackground(Void... params) {
try {
return Lbryio.fetchCurrentUser(context);
return Lbryio.fetchCurrentUser(null);
} catch (Exception ex) {
error = ex;
return null;
@@ -64,6 +64,8 @@ public class FetchSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
} catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException | IllegalStateException ex) {
error = ex;
return null;
} finally {
Helper.closeDatabase(db);
}
return subscriptions;
@@ -1,128 +0,0 @@
package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import io.lbry.browser.MainActivity;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
public class NotificationListTask extends AsyncTask<Void, Void, List<LbryNotification>> {
private static final String TAG = "Notifications";
private Context context;
private ListNotificationsHandler handler;
private ProgressBar progressBar;
private Exception error;
public NotificationListTask(Context context, ProgressBar progressBar, ListNotificationsHandler handler) {
this.context = context;
this.progressBar = progressBar;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressBar, View.VISIBLE);
}
protected List<LbryNotification> doInBackground(Void... params) {
List<LbryNotification> notifications = new ArrayList<>();
SQLiteDatabase db = null;
try {
JSONArray array = (JSONArray) Lbryio.parseResponse(Lbryio.call("notification", "list", context));
if (array != null) {
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
if (item.has("notification_parameters")) {
LbryNotification notification = new LbryNotification();
JSONObject notificationParams = item.getJSONObject("notification_parameters");
if (notificationParams.has("device")) {
JSONObject device = notificationParams.getJSONObject("device");
notification.setTitle(Helper.getJSONString("title", null, device));
notification.setDescription(Helper.getJSONString("text", null, device));
notification.setTargetUrl(Helper.getJSONString("target", null, device));
}
if (notificationParams.has("dynamic") && !notificationParams.isNull("dynamic")) {
JSONObject dynamic = notificationParams.getJSONObject("dynamic");
if (dynamic.has("comment_author")) {
notification.setAuthorUrl(Helper.getJSONString("comment_author", null, dynamic));
}
if (dynamic.has("channelURI")) {
String channelUrl = Helper.getJSONString("channelURI", null, dynamic);
if (!Helper.isNullOrEmpty(channelUrl)) {
notification.setTargetUrl(channelUrl);
}
}
if (dynamic.has("hash") && "comment".equalsIgnoreCase(Helper.getJSONString("notification_rule", null, item))) {
notification.setTargetUrl(String.format("%s?comment_hash=%s", notification.getTargetUrl(), dynamic.getString("hash")));
}
}
notification.setRule(Helper.getJSONString("notification_rule", null, item));
notification.setRemoteId(Helper.getJSONLong("id", 0, item));
notification.setRead(Helper.getJSONBoolean("is_read", false, item));
notification.setSeen(Helper.getJSONBoolean("is_seen", false, item));
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(Helper.ISO_DATE_FORMAT_JSON, Locale.US);
notification.setTimestamp(dateFormat.parse(Helper.getJSONString("created_at", dateFormat.format(new Date()), item)));
} catch (ParseException ex) {
notification.setTimestamp(new Date());
}
if (notification.getRemoteId() > 0 && !Helper.isNullOrEmpty(notification.getDescription())) {
notifications.add(notification);
}
}
}
if (context instanceof MainActivity) {
db = ((MainActivity) context).getDbHelper().getWritableDatabase();
for (LbryNotification notification : notifications) {
DatabaseHelper.createOrUpdateNotification(notification, db);
}
}
}
} catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException | SQLiteException | IllegalStateException ex) {
Log.e(TAG, ex.getMessage(), ex);
error = ex;
return null;
}
return notifications;
}
protected void onPostExecute(List<LbryNotification> notifications) {
Helper.setViewVisibility(progressBar, View.GONE);
if (handler != null) {
if (notifications != null) {
handler.onSuccess(notifications);
} else {
handler.onError(error);
}
}
}
public interface ListNotificationsHandler {
void onSuccess(List<LbryNotification> notifications);
void onError(Exception exception);
}
}
@@ -1,47 +0,0 @@
package io.lbry.browser.tasks.lbryinc;
import android.os.AsyncTask;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
public class NotificationUpdateTask extends AsyncTask<Void, Void, Boolean> {
private List<Long> ids;
private boolean seen;
private boolean read;
private boolean updateSeen;
public NotificationUpdateTask(List<Long> ids, boolean read) {
this(ids, read, false, false);
}
public NotificationUpdateTask(List<Long> ids, boolean read, boolean seen, boolean updateSeen) {
this.ids = ids;
this.read = read;
this.seen = seen;
this.updateSeen = updateSeen;
}
protected Boolean doInBackground(Void... params) {
Map<String, String> options = new HashMap<>();
options.put("notification_ids", Helper.joinL(ids, ","));
options.put("is_read", String.valueOf(read));
if (updateSeen) {
options.put("is_seen", String.valueOf(seen));
}
try {
Object result = Lbryio.parseResponse(Lbryio.call("notification", "edit", options, null));
return "ok".equalsIgnoreCase(result.toString());
} catch (LbryioResponseException | LbryioRequestException ex) {
}
return false;
}
}
@@ -1,68 +0,0 @@
package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import io.lbry.browser.model.TwitterOauth;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
public class TwitterVerifyTask extends AsyncTask<Void, Void, RewardVerified> {
private Context context;
private View progressView;
private TwitterOauth twitterOauth;
private RewardVerifiedHandler handler;
private Exception error;
public TwitterVerifyTask(TwitterOauth twitterOauth, View progressView, Context context, RewardVerifiedHandler handler) {
this.twitterOauth = twitterOauth;
this.progressView = progressView;
this.context = context;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected RewardVerified doInBackground(Void... params) {
try {
Map<String, String> options = new HashMap<>();
options.put("oauth_token", twitterOauth.getOauthToken());
options.put("oauth_token_secret", twitterOauth.getOauthTokenSecret());
JSONObject object = (JSONObject) Lbryio.parseResponse(Lbryio.call("verification", "twitter_verify", options, context));
Type type = new TypeToken<RewardVerified>(){}.getType();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
return gson.fromJson(object.toString(), type);
} catch (Exception ex) {
error = ex;
return null;
}
}
protected void onPostExecute(RewardVerified result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (result != null) {
handler.onSuccess(result);
} else {
handler.onError(error);
}
}
}
}
@@ -9,21 +9,21 @@ import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.tasks.GenericTaskHandler;
public class SaveUrlHistoryTask extends AsyncTask<Void, Void, Boolean> {
private DatabaseHelper dbHelper;
public class CreateUrlHistoryTask extends AsyncTask<Void, Void, Boolean> {
private Context context;
private UrlSuggestion suggestion;
private SaveUrlHistoryHandler handler;
private GenericTaskHandler handler;
private Exception error;
public SaveUrlHistoryTask(UrlSuggestion suggestion, DatabaseHelper dbHelper, SaveUrlHistoryHandler handler) {
public CreateUrlHistoryTask(UrlSuggestion suggestion, Context context, GenericTaskHandler handler) {
this.suggestion = suggestion;
this.dbHelper = dbHelper;
this.context = context;
this.handler = handler;
}
protected Boolean doInBackground(Void... params) {
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
SQLiteDatabase db = ((MainActivity) context).getDbHelper().getWritableDatabase();
DatabaseHelper.createOrUpdateUrlHistoryItem(suggestion.getText(), suggestion.getUri().toString(), suggestion.getType(), db);
} catch (Exception ex) {
error = ex;
@@ -35,15 +35,10 @@ public class SaveUrlHistoryTask extends AsyncTask<Void, Void, Boolean> {
protected void onPostExecute(Boolean result) {
if (handler != null) {
if (result) {
handler.onSuccess(suggestion);
handler.onSuccess();
} else {
handler.onError(error);
}
}
}
public interface SaveUrlHistoryHandler {
void onSuccess(UrlSuggestion item);
void onError(Exception error);
}
}
@@ -1,37 +0,0 @@
package io.lbry.browser.tasks.localdata;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.model.UrlSuggestion;
public class FetchRecentUrlHistoryTask extends AsyncTask<Void, Void, List<UrlSuggestion>> {
private DatabaseHelper dbHelper;
private FetchRecentUrlHistoryHandler handler;
public FetchRecentUrlHistoryTask(DatabaseHelper dbHelper, FetchRecentUrlHistoryHandler handler) {
this.dbHelper = dbHelper;
this.handler = handler;
}
protected List<UrlSuggestion> doInBackground(Void... params) {
try {
SQLiteDatabase db = dbHelper.getReadableDatabase();
return DatabaseHelper.getRecentHistory(db);
} catch (SQLiteException ex) {
return new ArrayList<>();
}
}
protected void onPostExecute(List<UrlSuggestion> recentHistory) {
if (handler != null) {
handler.onSuccess(recentHistory);
}
}
public interface FetchRecentUrlHistoryHandler {
void onSuccess(List<UrlSuggestion> recentHistory);
}
}
@@ -1,46 +0,0 @@
package io.lbry.browser.tasks.localdata;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.model.ViewHistory;
import io.lbry.browser.utils.Helper;
public class FetchViewHistoryTask extends AsyncTask<Void, Void, List<ViewHistory>> {
private DatabaseHelper dbHelper;
private FetchViewHistoryHandler handler;
private int pageSize;
private Date lastDate;
public FetchViewHistoryTask(Date lastDate, int pageSize, DatabaseHelper dbHelper, FetchViewHistoryHandler handler) {
this.lastDate = lastDate;
this.pageSize = pageSize;
this.dbHelper = dbHelper;
this.handler = handler;
}
protected List<ViewHistory> doInBackground(Void... params) {
try {
SQLiteDatabase db = dbHelper.getReadableDatabase();
return DatabaseHelper.getViewHistory(
lastDate == null ? null : new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).format(lastDate), pageSize, db);
} catch (SQLiteException ex) {
return new ArrayList<>();
}
}
protected void onPostExecute(List<ViewHistory> history) {
if (handler != null) {
handler.onSuccess(history, history.size() < pageSize);
}
}
public interface FetchViewHistoryHandler {
void onSuccess(List<ViewHistory> history, boolean hasReachedEnd);
}
}
@@ -1,137 +0,0 @@
package io.lbry.browser.tasks.localdata;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.model.GalleryItem;
import io.lbry.browser.utils.Helper;
public class LoadGalleryItemsTask extends AsyncTask<Void, GalleryItem, List<GalleryItem>> {
private static final String TAG = "LoadGalleryItemsTask";
private LoadGalleryHandler handler;
private View progressView;
private Context context;
public LoadGalleryItemsTask(View progressView, Context context, LoadGalleryHandler handler) {
this.progressView = progressView;
this.context = context;
this.handler = handler;
}
protected void onPreExecute(Void... params) {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected List<GalleryItem> doInBackground(Void... params) {
List<GalleryItem> items = new ArrayList<>();
List<GalleryItem> itemsWithThumbnails = new ArrayList<>();
Cursor cursor = null;
if (context != null) {
ContentResolver resolver = context.getContentResolver();
try {
String[] projection = {
MediaStore.MediaColumns._ID,
MediaStore.MediaColumns.DATA,
MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.MIME_TYPE,
MediaStore.Video.Media.DURATION
};
cursor = resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, null, null,
String.format("%s DESC LIMIT 150", MediaStore.MediaColumns.DATE_MODIFIED));
if (cursor != null) {
while (cursor.moveToNext()) {
int idColumn = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
int nameColumn = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
int typeColumn = cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE);
int pathColumn = cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
int durationColumn = cursor.getColumnIndex(MediaStore.Video.Media.DURATION);
GalleryItem item = new GalleryItem();
item.setId(cursor.getString(idColumn));
item.setName(cursor.getString(nameColumn));
item.setType(cursor.getString(typeColumn));
item.setFilePath(cursor.getString(pathColumn));
item.setDuration(cursor.getLong(durationColumn));
items.add(item);
}
}
} catch (SQLiteException ex) {
// failed to load videos. log and pass
Log.e(TAG, ex.getMessage(), ex);
} finally {
Helper.closeCursor(cursor);
}
// load (or generate) thumbnail for each item
for (GalleryItem item : items) {
String id = item.getId();
File cacheDir = context.getExternalCacheDir();
File thumbnailsDir = new File(String.format("%s/thumbnails", cacheDir.getAbsolutePath()));
if (!thumbnailsDir.isDirectory()) {
thumbnailsDir.mkdirs();
}
String thumbnailPath = String.format("%s/%s.png", thumbnailsDir.getAbsolutePath(), id);
File file = new File(thumbnailPath);
if (!file.exists()) {
// save the thumbnail to the path
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap thumbnail = MediaStore.Video.Thumbnails.getThumbnail(
resolver, Long.parseLong(id), MediaStore.Video.Thumbnails.MINI_KIND, options);
if (thumbnail != null) {
try (FileOutputStream os = new FileOutputStream(thumbnailPath)) {
thumbnail.compress(Bitmap.CompressFormat.PNG, 80, os);
} catch (IOException ex) {
// skip
}
}
}
if (file.exists() && file.length() > 0) {
item.setThumbnailPath(file.getAbsolutePath());
itemsWithThumbnails.add(item);
publishProgress(item);
}
}
}
return itemsWithThumbnails;
}
protected void onProgressUpdate(GalleryItem... items) {
if (handler != null) {
for (GalleryItem item : items) {
handler.onItemLoaded(item);
}
}
}
protected void onPostExecute(List<GalleryItem> items) {
if (handler != null) {
handler.onAllItemsLoaded(items);
}
}
public interface LoadGalleryHandler {
void onItemLoaded(GalleryItem item);
void onAllItemsLoaded(List<GalleryItem> items);
}
}
Loaded 100 of 278 files, more files were not shown because too many files have changed in this diff. Show more