├── lib
├── .gitignore
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ ├── res
│ │ │ └── values
│ │ │ │ └── strings.xml
│ │ └── kotlin
│ │ │ └── net
│ │ │ └── dean
│ │ │ └── jraw
│ │ │ └── android
│ │ │ ├── AppInfoProvider.kt
│ │ │ ├── AppInfo.kt
│ │ │ ├── SimpleAndroidLogAdapter.kt
│ │ │ ├── AndroidHelper.kt
│ │ │ ├── SharedPreferencesTokenStore.kt
│ │ │ └── ManifestAppInfoProvider.kt
│ └── test
│ │ └── kotlin
│ │ └── net
│ │ └── dean
│ │ └── jraw
│ │ └── android
│ │ ├── util.kt
│ │ ├── AndroidHelperTest.kt
│ │ ├── SimpleAndroidLogAdapterTest.kt
│ │ ├── SharedPreferencesTokenStoreTest.kt
│ │ └── ManifestAppInfoProviderTest.kt
├── proguard-rules.pro
└── build.gradle
├── example-app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── dimens.xml
│ │ │ ├── colors.xml
│ │ │ ├── styles.xml
│ │ │ └── strings.xml
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── drawable
│ │ │ ├── ic_plus.xml
│ │ │ ├── ic_user.xml
│ │ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ │ ├── activity_new_user.xml
│ │ │ ├── view_tokenstore_row.xml
│ │ │ ├── activity_main.xml
│ │ │ └── activity_user_overview.xml
│ │ └── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── net
│ │ └── dean
│ │ └── jraw
│ │ └── android
│ │ └── example
│ │ ├── TokenStoreUserView.java
│ │ ├── App.java
│ │ ├── UserOverviewActivity.java
│ │ ├── NewUserActivity.java
│ │ └── MainActivity.java
├── proguard-rules.pro
├── build.gradle
└── README.md
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── .travis.yml
├── gradle.properties
├── gradlew.bat
├── gradlew
└── README.md
/lib/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/example-app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':example-app', ':lib'
2 |
--------------------------------------------------------------------------------
/example-app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mattbdean/JRAW-Android/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | .idea/
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 |
--------------------------------------------------------------------------------
/lib/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/lib/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | net.dean.jraw.android.prefs_file
3 |
4 |
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mattbdean/JRAW-Android/HEAD/example-app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mattbdean/JRAW-Android/HEAD/example-app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mattbdean/JRAW-Android/HEAD/example-app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mattbdean/JRAW-Android/HEAD/example-app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mattbdean/JRAW-Android/HEAD/example-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/lib/src/main/kotlin/net/dean/jraw/android/AppInfoProvider.kt:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android
2 |
3 | interface AppInfoProvider {
4 | fun provide(): AppInfo
5 | }
6 |
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mattbdean/JRAW-Android/HEAD/example-app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mattbdean/JRAW-Android/HEAD/example-app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mattbdean/JRAW-Android/HEAD/example-app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mattbdean/JRAW-Android/HEAD/example-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mattbdean/JRAW-Android/HEAD/example-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.7-all.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/example-app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/example-app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/example-app/src/main/res/drawable/ic_plus.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
--------------------------------------------------------------------------------
/lib/src/main/kotlin/net/dean/jraw/android/AppInfo.kt:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android
2 |
3 | import net.dean.jraw.http.UserAgent
4 |
5 | /**
6 | * This class contains all the information required to authenticate an Android app using reddit's
7 | * OAuth2 authentication process.
8 | */
9 | data class AppInfo(val clientId: String, val redirectUrl: String, val userAgent: UserAgent)
10 |
--------------------------------------------------------------------------------
/example-app/src/main/res/drawable/ic_user.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 | language: android
3 | before_install:
4 | # https://stackoverflow.com/a/47719835/1275092
5 | - yes | sdkmanager "platforms;android-27"
6 | android:
7 | components:
8 | - tools
9 | - platform-tools
10 | - tools
11 |
12 | - build-tools-27.0.3
13 | - android-27
14 | script:
15 | - "./gradlew check jacocoTestReportDebug"
16 | after_success:
17 | - bash <(curl -s https://codecov.io/bash) -f lib/build/reports/jacoco/debug/jacoco.xml
--------------------------------------------------------------------------------
/example-app/src/main/res/layout/activity_new_user.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
--------------------------------------------------------------------------------
/lib/src/main/kotlin/net/dean/jraw/android/SimpleAndroidLogAdapter.kt:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android
2 |
3 | import android.util.Log
4 | import net.dean.jraw.http.LogAdapter
5 |
6 | /**
7 | * Uses android.util.Log to log messages.
8 | */
9 | class SimpleAndroidLogAdapter @JvmOverloads constructor(
10 | /** The priority of each message to log. Must be one of the android.util.Log constants. */
11 | var level: Int = Log.VERBOSE,
12 |
13 | /** The tag to use when logging. Default is "JRAW" */
14 | var tag: String = "JRAW"
15 | ) : LogAdapter {
16 | override fun writeln(data: String) {
17 | if (Log.isLoggable(tag, level))
18 | Log.println(level, tag, data)
19 | }
20 | }
--------------------------------------------------------------------------------
/lib/src/test/kotlin/net/dean/jraw/android/util.kt:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android
2 |
3 | inline fun expectException(doWork: () -> Unit): T {
4 | val message = "Should have thrown ${T::class.java.name}"
5 | try {
6 | doWork()
7 | throw IllegalStateException(message)
8 | } catch (e: Exception) {
9 | // Make sure rethrow the Exception we created here
10 | if (e.message == message) throw e
11 | // Make sure we got the right kind of Exception
12 | if (e::class.java != T::class.java)
13 | throw IllegalStateException("Expecting function to throw ${T::class.java.name}, instead threw ${e::class.java.name}", e)
14 | return e as T
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/example-app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/lib/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/example-app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/example-app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | JRAW-Android Example
3 | Choose an account
4 |
5 | %s comment karma
6 | %s link karma
7 | Access token expires in %d minutes
8 | Expires in %d minutes
9 | Refresh token on hand
10 | No refresh token on hand
11 | Logout
12 |
13 | There\'s nothing here ¯\\_(ツ)_/¯
14 | New user
15 | Access token expired
16 |
17 |
--------------------------------------------------------------------------------
/lib/src/test/kotlin/net/dean/jraw/android/AndroidHelperTest.kt:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android
2 |
3 | import net.dean.jraw.http.UserAgent
4 | import net.dean.jraw.oauth.NoopTokenStore
5 | import okhttp3.OkHttpClient
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 | import org.robolectric.RobolectricTestRunner
9 | import java.util.*
10 |
11 | @RunWith(RobolectricTestRunner::class)
12 | class AndroidHelperTest {
13 | private val clientId = ""
14 | private val redirectUrl = ""
15 | private val userAgent = UserAgent("")
16 | private val deviceUUID = UUID.randomUUID()!!
17 | private val tokenStore = NoopTokenStore()
18 | private val http = OkHttpClient()
19 |
20 | @Test
21 | fun shouldUseManuallyProvidedDataToCreateAnAccountHelper() {
22 | AndroidHelper.accountHelper(clientId, redirectUrl, userAgent, deviceUUID, tokenStore, http)
23 | }
24 |
25 | @Test
26 | fun shouldUseAnAppInfoProviderWhenGiven() {
27 | AndroidHelper.accountHelper(object: AppInfoProvider {
28 | override fun provide(): AppInfo = AppInfo(clientId, redirectUrl, userAgent)
29 | }, deviceUUID, tokenStore, http)
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/example-app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'com.getkeepsafe.dexcount'
3 |
4 | android {
5 | compileSdkVersion 27
6 | buildToolsVersion '27.0.3'
7 | defaultConfig {
8 | applicationId 'net.dean.jraw.android.example'
9 | minSdkVersion 15
10 | targetSdkVersion 27
11 | versionCode 1
12 | versionName '1.0.0'
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 |
15 | vectorDrawables.useSupportLibrary = true
16 | }
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | compileOptions {
24 | targetCompatibility 1.8
25 | sourceCompatibility 1.8
26 | }
27 | }
28 |
29 | dependencies {
30 | implementation 'com.android.support:appcompat-v7:27.1.1'
31 | implementation project(':lib')
32 | implementation 'com.android.support.constraint:constraint-layout:1.1.1'
33 | implementation 'com.android.support:design:27.1.1'
34 | testImplementation 'junit:junit:4.12'
35 | }
36 |
37 | dexcount {
38 | maxTreeDepth = 3
39 | includeTotalMethodCount = true
40 | }
41 |
--------------------------------------------------------------------------------
/lib/src/test/kotlin/net/dean/jraw/android/SimpleAndroidLogAdapterTest.kt:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android
2 |
3 | import android.util.Log
4 | import com.winterbe.expekt.should
5 | import org.junit.After
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 | import org.robolectric.RobolectricTestRunner
9 | import org.robolectric.shadows.ShadowLog
10 |
11 | @RunWith(RobolectricTestRunner::class)
12 | class SimpleAndroidLogAdapterTest {
13 | val tag = "TESTING-TAG"
14 |
15 | @After
16 | fun tearDown() {
17 | ShadowLog.reset()
18 | }
19 |
20 | @Test
21 | fun shouldLogAtRequestedLevel() {
22 | val level = Log.INFO
23 | val msg = "foo"
24 |
25 | val adapter = SimpleAndroidLogAdapter(level, tag)
26 | adapter.writeln(msg)
27 | ShadowLog.getLogs().should.equal(listOf(ShadowLog.LogItem(level, tag, msg, null)))
28 | }
29 |
30 | @Test
31 | fun shouldNotLogWhenLevelNotLoggable() {
32 | val level = Log.VERBOSE
33 | val msg = "foo"
34 | val adapter = SimpleAndroidLogAdapter(level, tag)
35 |
36 | // By default, only INFO and above are loggable
37 | adapter.writeln(msg)
38 | ShadowLog.getLogs().should.be.empty
39 |
40 | // Use ShadowLog to explicitly allow this tag at this level to be logged
41 | ShadowLog.setLoggable(tag, level)
42 | adapter.writeln(msg)
43 | ShadowLog.getLogs().should.equal(listOf(ShadowLog.LogItem(level, tag, msg, null)))
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/example-app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
15 |
18 |
21 |
24 |
25 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/example-app/README.md:
--------------------------------------------------------------------------------
1 | # Example App
2 |
3 | The first thing you'll see is the MainActivity. This screen shows you what the TokenStore knows, and since right now it knows nothing, it shows you nothing.
4 |
5 |
6 |
7 | Click the FAB in the bottom right to authenticate a new user. It'll launch the NewUserActivity, which will show you a WebView. This WebView will automatically be loaded with the correct authorization URL for the example OAuth2 app credentials.
8 |
9 |
10 |
11 | Once you enter your username and password, you'll be prompted by reddit to allow the example app to allow the app to fetch information about your account.
12 |
13 |
14 |
15 | If you press "deny" you'll be taken back to the previous screen. If you press "allow," you'll be taken to the UserOverviewActivity.
16 |
17 |
18 |
19 | From here, if you press the back or logout button, you'll be taken back to the MainActivity. This time, you'll notice that there is an entry present for the account you just logged in to. Clicking on the entry will take you back to the user overview.
20 |
21 |
22 |
23 | Once the access token expires, the text in the bottom left-hand corner of the entry will read "Access token expired." If you now click on the entry, JRAW will automatically request a new access token for that user and you will be shown the UserOverviewActivity.
24 |
25 |
26 |
--------------------------------------------------------------------------------
/example-app/src/main/res/layout/view_tokenstore_row.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
16 |
17 |
27 |
28 |
37 |
--------------------------------------------------------------------------------
/example-app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
15 |
16 |
20 |
21 |
27 |
28 |
29 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/lib/src/main/kotlin/net/dean/jraw/android/AndroidHelper.kt:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android
2 |
3 | import net.dean.jraw.http.OkHttpNetworkAdapter
4 | import net.dean.jraw.http.UserAgent
5 | import net.dean.jraw.oauth.AccountHelper
6 | import net.dean.jraw.oauth.Credentials
7 | import net.dean.jraw.oauth.NoopTokenStore
8 | import net.dean.jraw.oauth.TokenStore
9 | import okhttp3.OkHttpClient
10 | import java.util.*
11 |
12 | /**
13 | * A few JRAW utility methods specific to the Android platform. See
14 | * [here](https://mattbdean.gitbooks.io/jraw/content/oauth2.html#accounthelper) for more information.
15 | */
16 | object AndroidHelper {
17 | /** Creates an AccountHelper */
18 | @JvmOverloads
19 | @JvmStatic
20 | fun accountHelper(clientId: String,
21 | redirectUrl: String,
22 | userAgent: UserAgent,
23 | deviceUUID: UUID,
24 | tokenStore: TokenStore = NoopTokenStore(),
25 | http: OkHttpClient = OkHttpClient()): AccountHelper {
26 |
27 | val networkAdapter = OkHttpNetworkAdapter(userAgent, http)
28 | val creds = Credentials.installedApp(clientId, redirectUrl)
29 |
30 | return AccountHelper(networkAdapter, creds, tokenStore, deviceUUID)
31 | }
32 |
33 | /**
34 | * Creates an AccountHelper using an [AppInfoProvider] to specify OAuth2 app details.
35 | *
36 | * @see ManifestAppInfoProvider
37 | */
38 | @JvmOverloads
39 | @JvmStatic
40 | fun accountHelper(provider: AppInfoProvider,
41 | deviceUUID: UUID,
42 | tokenStore: TokenStore = NoopTokenStore(),
43 | http: OkHttpClient = OkHttpClient()): AccountHelper {
44 |
45 | val meta = provider.provide()
46 | return accountHelper(meta.clientId, meta.redirectUrl, meta.userAgent, deviceUUID,
47 | tokenStore, http)
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/example-app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/lib/src/main/kotlin/net/dean/jraw/android/SharedPreferencesTokenStore.kt:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android
2 |
3 | import android.content.Context
4 | import android.content.SharedPreferences
5 | import com.squareup.moshi.JsonAdapter
6 | import net.dean.jraw.JrawUtils
7 | import net.dean.jraw.models.PersistedAuthData
8 | import net.dean.jraw.oauth.DeferredPersistentTokenStore
9 |
10 | /**
11 | * This TokenStore implementation persists OAuthData and refresh tokens to a private
12 | * SharedPreferences.
13 | *
14 | * SharedPreferences are persisted using `apply()` rather than `commit()`, so it might be a good
15 | * idea to enable [autoPersist].
16 | *
17 | * It should be noted that this is probably not the most efficient or secure means of storing this
18 | * kind of data. For apps that have several hundred users, it might be better to store this
19 | * information in a database.
20 | */
21 | class SharedPreferencesTokenStore(context: Context) : DeferredPersistentTokenStore() {
22 | val sharedPreferences: SharedPreferences = context.getSharedPreferences(
23 | context.getString(R.string.prefs_file), Context.MODE_PRIVATE)
24 |
25 | override fun doLoad(): Map {
26 | return sharedPreferences
27 | .all
28 | // Only operate on key-value pairs whose value is a string (since we store all data
29 | // as strings)
30 | .filterValues { it is String }
31 | // Parse the JSON value to a PersistedAuthData
32 | .map { (username, data) -> username to adapter.fromJson(data as String)!! }
33 | .toMap()
34 | }
35 |
36 | override fun doPersist(data: Map) {
37 | val editor = sharedPreferences.edit().clear()
38 |
39 | for ((username, persistedData) in data) {
40 | editor.putString(username, adapter.toJson(persistedData))
41 | }
42 |
43 | editor.apply()
44 | }
45 |
46 | companion object {
47 | private val adapter: JsonAdapter = JrawUtils.adapter()
48 | }
49 | }
50 |
51 |
--------------------------------------------------------------------------------
/lib/src/test/kotlin/net/dean/jraw/android/SharedPreferencesTokenStoreTest.kt:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android
2 |
3 | import com.winterbe.expekt.should
4 | import net.dean.jraw.JrawUtils
5 | import net.dean.jraw.models.OAuthData
6 | import net.dean.jraw.models.PersistedAuthData
7 | import org.junit.Before
8 | import org.junit.Test
9 | import org.junit.runner.RunWith
10 | import org.robolectric.RobolectricTestRunner
11 | import org.robolectric.RuntimeEnvironment
12 | import java.util.*
13 | import java.util.concurrent.TimeUnit
14 |
15 | @RunWith(RobolectricTestRunner::class)
16 | class SharedPreferencesTokenStoreTest {
17 | private lateinit var store: SharedPreferencesTokenStore
18 | private val adapter = JrawUtils.adapter()
19 | private val username = "foo"
20 |
21 | @Before
22 | fun setUp() {
23 | store = SharedPreferencesTokenStore(RuntimeEnvironment.application)
24 | store.sharedPreferences.edit().clear().apply()
25 | }
26 |
27 | @Test
28 | fun shouldLoadDataFromPrefs() {
29 | val username = "foo"
30 | val authData = mockAuthData()
31 | store.sharedPreferences.edit().putString(username, adapter.toJson(authData)).apply()
32 |
33 | store.load()
34 | store.usernames.should.equal(listOf(username))
35 | store.fetchLatest(username).should.equal(authData.latest)
36 | store.fetchRefreshToken(username).should.equal(authData.refreshToken)
37 | }
38 |
39 | @Test
40 | fun shouldNotTryToParseNonStrings() {
41 | store.sharedPreferences.edit().putInt("foo", 4).apply()
42 | store.load()
43 |
44 | store.size().should.equal(0)
45 | }
46 |
47 | @Test
48 | fun shouldSaveToPrefs() {
49 | val authData = mockAuthData()
50 | store.sharedPreferences.getString(username, null).should.be.`null`
51 |
52 | store.storeLatest(username, authData.latest!!)
53 | store.storeRefreshToken(username, authData.refreshToken!!)
54 |
55 | store.persist()
56 |
57 | adapter.fromJson(store.sharedPreferences.getString(username, "")).should.equal(authData)
58 | }
59 |
60 | private fun mockAuthData(): PersistedAuthData {
61 | val expiration = Date(Date().time + TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS))
62 | return PersistedAuthData.create(OAuthData.create("access_token", listOf("*"), "", expiration), "refresh_token")
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/example-app/src/main/java/net/dean/jraw/android/example/TokenStoreUserView.java:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android.example;
2 |
3 | import android.content.Context;
4 | import android.support.annotation.IdRes;
5 | import android.support.annotation.Nullable;
6 | import android.support.constraint.ConstraintLayout;
7 | import android.util.AttributeSet;
8 | import android.widget.TextView;
9 |
10 | import net.dean.jraw.models.OAuthData;
11 | import net.dean.jraw.models.PersistedAuthData;
12 |
13 | import org.jetbrains.annotations.NotNull;
14 |
15 | import java.util.Date;
16 | import java.util.concurrent.TimeUnit;
17 |
18 | /**
19 | * A very simple view group that displays some information about a user and its associated
20 | * PersistedAuthData instance. Used by MainActivity's RecyclerView.
21 | */
22 | public class TokenStoreUserView extends ConstraintLayout {
23 | public TokenStoreUserView(Context context) {
24 | super(context);
25 | init();
26 | }
27 |
28 | public TokenStoreUserView(Context context, @Nullable AttributeSet attrs) {
29 | super(context, attrs);
30 | init();
31 | }
32 |
33 | public TokenStoreUserView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
34 | super(context, attrs, defStyleAttr);
35 | init();
36 | }
37 |
38 | public void display(String username, @NotNull PersistedAuthData data) {
39 | textView(R.id.username).setText(username);
40 |
41 | OAuthData latest = data.getLatest();
42 | if (latest != null) {
43 | // Calculate the amount of minutes in which the OAuthData will expire
44 | long diffMillis = data.getLatest().getExpiration().getTime() - new Date().getTime();
45 | long diffMinutes = TimeUnit.MINUTES.convert(diffMillis, TimeUnit.MILLISECONDS);
46 |
47 | // Update the TextView
48 | textView(R.id.expiresIn).setText(getContext().getString(R.string.access_token_status_short, diffMinutes));
49 | } else {
50 | // No OAuthData, it's expired
51 | textView(R.id.expiresIn).setText(R.string.access_token_expired);
52 | }
53 |
54 | // Simply set this guy to say if there's a refresh token or not
55 | textView(R.id.refreshTokenStatus).setText(data.getRefreshToken() == null ? R.string.no_refresh_token : R.string.refresh_token);
56 | }
57 |
58 | private TextView textView(@IdRes int id) {
59 | return (TextView) findViewById(id);
60 | }
61 |
62 | private void init() {
63 | inflate(getContext(), R.layout.view_tokenstore_row, this);
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/lib/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'com.github.dcendents.android-maven'
4 | apply plugin: 'org.jetbrains.dokka-android'
5 |
6 | ext.projectName = 'JRAW-Android'
7 |
8 | // https://github.com/dcendents/android-maven-gradle-plugin/issues/9#issuecomment-73550293
9 | project.archivesBaseName = projectName
10 | // https://jitpack.io/docs/ANDROID/
11 | group = System.getenv("JITPACK") ? 'com.github.mattbdean' : 'net.dean.jraw'
12 | version = projectVersion
13 |
14 | android {
15 | compileSdkVersion 27
16 | buildToolsVersion "27.0.3"
17 |
18 |
19 | defaultConfig {
20 | minSdkVersion 15
21 | targetSdkVersion 27
22 | versionCode 1
23 | versionName projectVersion
24 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
25 |
26 | }
27 |
28 | buildTypes {
29 | release {
30 | minifyEnabled false
31 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
32 | }
33 | }
34 |
35 | sourceSets {
36 | main.java.srcDirs += 'src/main/kotlin'
37 | test.java.srcDirs += 'src/test/kotlin'
38 | }
39 |
40 | testOptions {
41 | unitTests {
42 | // For robolectric
43 | includeAndroidResources = true
44 | }
45 | }
46 | }
47 |
48 | dependencies {
49 | api jraw
50 | testImplementation 'junit:junit:4.12'
51 | testImplementation 'org.robolectric:robolectric:3.5.1'
52 | testImplementation 'com.winterbe:expekt:0.5.0'
53 | testImplementation 'com.nhaarman:mockito-kotlin-kt1.1:1.5.0'
54 | }
55 |
56 | dokka {
57 | moduleName = 'jraw-android'
58 | jdkVersion = 7
59 | impliedPlatforms = ['JVM']
60 | reportUndocumented = true
61 | outputFormat = 'javadoc'
62 |
63 | linkMapping {
64 | dir = file('src/main/kotlin')
65 | url = 'https://github.com/mattbdean/JRAW-Android/tree/master/lib/src/main/kotlin'
66 | suffix = '#L'
67 | }
68 | }
69 |
70 | task javadocJar(type: Jar, dependsOn: dokka) {
71 | classifier = 'javadoc'
72 | from dokka.outputDirectory
73 | baseName = projectName
74 | }
75 |
76 | task sourcesJar(type: Jar) {
77 | classifier = 'sources'
78 | from android.sourceSets.main.java.srcDirs
79 | baseName = projectName
80 | }
81 |
82 | // When JitPack builds, it runs the install task (from the maven plugin) to install all artifacts listed here to the
83 | // local repository. List the sources and Javadoc jar here to make it available to JitPack users.
84 | artifacts {
85 | archives sourcesJar
86 | archives javadocJar
87 | }
88 |
--------------------------------------------------------------------------------
/example-app/src/main/java/net/dean/jraw/android/example/App.java:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android.example;
2 |
3 | import android.app.Application;
4 | import android.util.Log;
5 |
6 | import net.dean.jraw.RedditClient;
7 | import net.dean.jraw.android.AndroidHelper;
8 | import net.dean.jraw.android.AppInfoProvider;
9 | import net.dean.jraw.android.ManifestAppInfoProvider;
10 | import net.dean.jraw.android.SharedPreferencesTokenStore;
11 | import net.dean.jraw.android.SimpleAndroidLogAdapter;
12 | import net.dean.jraw.http.LogAdapter;
13 | import net.dean.jraw.http.SimpleHttpLogger;
14 | import net.dean.jraw.oauth.AccountHelper;
15 |
16 | import java.util.UUID;
17 |
18 | import kotlin.Unit;
19 | import kotlin.jvm.functions.Function1;
20 |
21 | public final class App extends Application {
22 | private static AccountHelper accountHelper;
23 | private static SharedPreferencesTokenStore tokenStore;
24 |
25 | @Override
26 | public void onCreate() {
27 | super.onCreate();
28 |
29 | // Get UserAgent and OAuth2 data from AndroidManifest.xml
30 | AppInfoProvider provider = new ManifestAppInfoProvider(getApplicationContext());
31 |
32 | // Ideally, this should be unique to every device
33 | UUID deviceUuid = UUID.randomUUID();
34 |
35 | // Store our access tokens and refresh tokens in shared preferences
36 | tokenStore = new SharedPreferencesTokenStore(getApplicationContext());
37 | // Load stored tokens into memory
38 | tokenStore.load();
39 | // Automatically save new tokens as they arrive
40 | tokenStore.setAutoPersist(true);
41 |
42 | // An AccountHelper manages switching between accounts and into/out of userless mode.
43 | accountHelper = AndroidHelper.accountHelper(provider, deviceUuid, tokenStore);
44 |
45 | // Every time we use the AccountHelper to switch between accounts (from one account to
46 | // another, or into/out of userless mode), call this function
47 | accountHelper.onSwitch(redditClient -> {
48 | // By default, JRAW logs HTTP activity to System.out. We're going to use Log.i()
49 | // instead.
50 | LogAdapter logAdapter = new SimpleAndroidLogAdapter(Log.INFO);
51 |
52 | // We're going to use the LogAdapter to write down the summaries produced by
53 | // SimpleHttpLogger
54 | redditClient.setLogger(
55 | new SimpleHttpLogger(SimpleHttpLogger.DEFAULT_LINE_LENGTH, logAdapter));
56 |
57 | // If you want to disable logging, use a NoopHttpLogger instead:
58 | // redditClient.setLogger(new NoopHttpLogger());
59 |
60 | return null;
61 | });
62 | }
63 |
64 | public static AccountHelper getAccountHelper() { return accountHelper; }
65 | public static SharedPreferencesTokenStore getTokenStore() { return tokenStore; }
66 | }
--------------------------------------------------------------------------------
/lib/src/main/kotlin/net/dean/jraw/android/ManifestAppInfoProvider.kt:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android
2 |
3 | import android.content.Context
4 | import android.content.pm.PackageManager
5 | import android.os.Bundle
6 | import net.dean.jraw.http.UserAgent
7 |
8 | /**
9 | * This class produces [AppInfo] instances from application manifest metadata.
10 | *
11 | * Include this in your `AndroidManifest.xml`:
12 | *
13 | * ```xml
14 | * <application android:name="foo" (...)>
15 | * (...)
16 | *
17 | * <meta-data
18 | * android:name="net.dean.jraw.android.REDDIT_USERNAME"
19 | * android:value="(your reddit username)" />
20 | *
21 | * <meta-data
22 | * android:name="net.dean.jraw.android.CLIENT_ID"
23 | * android:value="(your client ID)" />
24 | *
25 | * <meta-data
26 | * android:name="net.dean.jraw.android.REDIRECT_URL"
27 | * android:value="(your redirect URL)" />
28 | * </application>
29 | * ```
30 | *
31 | * If the application's ID is "com.example.app", then the resulting AppInfo's UserAgent will be
32 | * something like this: `android:com.example.app:${version} (by /u/${username})` where `${version}`
33 | * is `BuildConfig.VERSION_NAME`.
34 | *
35 | * If this doesn't suit your needs, use `net.dean.jraw.android.USER_AGENT_OVERRIDE` instead of
36 | * `net.dean.jraw.android.REDDIT_USERNAME` to specify a custom user agent.
37 | */
38 | class ManifestAppInfoProvider(private val context: Context) : AppInfoProvider {
39 | override fun provide(): AppInfo {
40 | // Get the app's tags from the manifest
41 | val metadata = context
42 | .packageManager
43 | .getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
44 | .metaData
45 |
46 | // Pull version from here instead of BuildConfig. The end result will be the same for the
47 | // user.
48 | val version = context.packageManager.getPackageInfo(context.packageName, 0).versionName
49 |
50 | val ua = userAgent(metadata, version)
51 |
52 | return AppInfo(
53 | clientId = requireString(metadata, KEY_CLIENT_ID, "client ID"),
54 | redirectUrl = requireString(metadata, KEY_REDIRECT_URL, "redirect URL"),
55 | userAgent = ua
56 | )
57 | }
58 |
59 | private fun userAgent(b: Bundle, version: String): UserAgent {
60 | val username = b.getString(KEY_REDDIT_USERNAME)
61 |
62 | if (username != null)
63 | return UserAgent(PLATFORM, context.packageName, version, username)
64 |
65 | val override = b.getString(KEY_USER_AGENT_OVERRIDE)
66 | if (override != null)
67 | return UserAgent(override)
68 |
69 | throw IllegalStateException("Could produce a UserAgent from the manifest. Make sure to " +
70 | "include a tag with either the $KEY_REDDIT_USERNAME or " +
71 | "$KEY_USER_AGENT_OVERRIDE key.")
72 | }
73 |
74 | private fun requireString(bundle: Bundle, key: String, what: String): String {
75 | return bundle.getString(key) ?:
76 | throw IllegalStateException("Could not produce a $what from the manifest. Make " +
77 | "sure to include a tag with the $key key.")
78 | }
79 |
80 | companion object {
81 | internal const val KEY_USER_AGENT_OVERRIDE = "net.dean.jraw.android.USER_AGENT_OVERRIDE"
82 | internal const val KEY_REDDIT_USERNAME = "net.dean.jraw.android.REDDIT_USERNAME"
83 | internal const val KEY_CLIENT_ID = "net.dean.jraw.android.CLIENT_ID"
84 | internal const val KEY_REDIRECT_URL = "net.dean.jraw.android.REDIRECT_URL"
85 |
86 | private const val PLATFORM = "android"
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/lib/src/test/kotlin/net/dean/jraw/android/ManifestAppInfoProviderTest.kt:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android
2 |
3 | import android.content.Context
4 | import android.content.pm.ApplicationInfo
5 | import android.content.pm.PackageInfo
6 | import android.content.pm.PackageManager
7 | import android.os.Bundle
8 | import com.nhaarman.mockito_kotlin.doReturn
9 | import com.nhaarman.mockito_kotlin.mock
10 | import com.winterbe.expekt.should
11 | import net.dean.jraw.http.UserAgent
12 | import org.junit.Test
13 | import org.junit.runner.RunWith
14 | import org.robolectric.RobolectricTestRunner
15 | import org.robolectric.annotation.Config
16 |
17 | @RunWith(RobolectricTestRunner::class)
18 | @Config(sdk = [25])
19 | class ManifestAppInfoProviderTest {
20 | private val mockClientId = ""
21 | private val mockRedirectUrl = ""
22 | private val mockUsername = ""
23 | private val mockVersionName = ""
24 |
25 | private fun init(includeCreds: Boolean, initBundle: (empty: Bundle) -> Unit = {}): ManifestAppInfoProvider {
26 | val b = Bundle()
27 | if (includeCreds) {
28 | b.putString(ManifestAppInfoProvider.KEY_CLIENT_ID, mockClientId)
29 | b.putString(ManifestAppInfoProvider.KEY_REDIRECT_URL, mockRedirectUrl)
30 | }
31 |
32 | initBundle(b)
33 |
34 | val appInfo = ApplicationInfo()
35 | appInfo.metaData = b
36 |
37 | val packageInfo = PackageInfo()
38 | packageInfo.versionName = mockVersionName
39 |
40 | // Mock the call to context.getPackageManager().getApplicationInfo(...). There's probably a
41 | // better way to do this.
42 | val mockPm = mock {
43 | on { getApplicationInfo(BuildConfig.APPLICATION_ID, PackageManager.GET_META_DATA) }
44 | .doReturn(appInfo)
45 | on { getPackageInfo(BuildConfig.APPLICATION_ID, 0) }
46 | .doReturn(packageInfo)
47 | }
48 |
49 | val mockContext = mock {
50 | on { packageName } doReturn BuildConfig.APPLICATION_ID
51 | on { packageManager } doReturn mockPm
52 | }
53 |
54 | return ManifestAppInfoProvider(mockContext)
55 | }
56 |
57 | @Test
58 | fun shouldWorkWithOverrideKey() {
59 | val provider = init(includeCreds = true) {
60 | it.putString(ManifestAppInfoProvider.KEY_REDDIT_USERNAME, mockUsername)
61 | }
62 |
63 | provider.provide().should.equal(AppInfo(mockClientId, mockRedirectUrl,
64 | UserAgent("android", BuildConfig.APPLICATION_ID, mockVersionName, mockUsername)))
65 | }
66 |
67 | @Test
68 | fun shouldWorkWithUsernameKey() {
69 | val someUserAgent = ""
70 | val provider = init(includeCreds = true) {
71 | it.putString(ManifestAppInfoProvider.KEY_USER_AGENT_OVERRIDE, someUserAgent)
72 | }
73 |
74 | provider.provide().should.equal(AppInfo(mockClientId, mockRedirectUrl, UserAgent(someUserAgent)))
75 | }
76 |
77 | @Test
78 | fun shouldRequireUserAgent() {
79 | val provider = init(includeCreds = true)
80 |
81 | expectException { provider.provide() }.message.should.contain("UserAgent")
82 | }
83 |
84 | @Test
85 | fun shouldRequireClientId() {
86 | val provider = init(includeCreds = false) {
87 | it.putString(ManifestAppInfoProvider.KEY_USER_AGENT_OVERRIDE, "")
88 | it.putString(ManifestAppInfoProvider.KEY_REDIRECT_URL, mockRedirectUrl)
89 | }
90 |
91 | expectException { provider.provide() }.message.should.contain("client ID")
92 | }
93 |
94 | @Test
95 | fun shouldRequireRedirectUrl() {
96 | val provider = init(includeCreds = false) {
97 | it.putString(ManifestAppInfoProvider.KEY_CLIENT_ID, mockClientId)
98 | it.putString(ManifestAppInfoProvider.KEY_REDDIT_USERNAME, mockUsername)
99 | }
100 |
101 | expectException { provider.provide() }.message.should.contain("redirect URL")
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/example-app/src/main/res/layout/activity_user_overview.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
18 |
19 |
31 |
32 |
42 |
43 |
52 |
53 |
62 |
63 |
73 |
74 |
86 |
87 |
97 |
98 |
--------------------------------------------------------------------------------
/example-app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
10 |
12 |
14 |
16 |
18 |
20 |
22 |
24 |
26 |
28 |
30 |
32 |
34 |
36 |
38 |
40 |
42 |
44 |
46 |
48 |
50 |
52 |
54 |
56 |
58 |
60 |
62 |
64 |
66 |
68 |
70 |
72 |
74 |
75 |
--------------------------------------------------------------------------------
/example-app/src/main/java/net/dean/jraw/android/example/UserOverviewActivity.java:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android.example;
2 |
3 | import android.os.AsyncTask;
4 | import android.os.Bundle;
5 | import android.support.annotation.IdRes;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.view.View;
8 | import android.widget.ProgressBar;
9 | import android.widget.TextView;
10 |
11 | import net.dean.jraw.RedditClient;
12 | import net.dean.jraw.models.Account;
13 | import net.dean.jraw.models.PersistedAuthData;
14 | import net.dean.jraw.oauth.DeferredPersistentTokenStore;
15 |
16 | import java.lang.ref.WeakReference;
17 | import java.text.NumberFormat;
18 | import java.util.Date;
19 | import java.util.concurrent.TimeUnit;
20 |
21 | /**
22 | * Shows some very simple information about the currently authenticated user. Currently, it shows
23 | * their username, link karma, comment karma, access token expiration, and if we have a refresh
24 | * token for them.
25 | */
26 | public class UserOverviewActivity extends AppCompatActivity {
27 |
28 | @Override
29 | protected void onCreate(Bundle savedInstanceState) {
30 | super.onCreate(savedInstanceState);
31 | setContentView(R.layout.activity_user_overview);
32 |
33 | // Fetch the user's account information
34 | new GetUserInfoTask(this).execute(App.getAccountHelper().getReddit());
35 | }
36 |
37 | @Override
38 | public void onBackPressed() {
39 | super.onBackPressed();
40 |
41 | // Provide the user two ways to log out: the "log out" button, and exiting this activity
42 | onLogout(null);
43 | }
44 |
45 | private void show(Account account) {
46 | // Basics
47 | textView(R.id.username).setText(account.getName());
48 | textView(R.id.linkKarma).setText(getString(R.string.link_karma, formatInt(account.getLinkKarma())));
49 | textView(R.id.commentKarma).setText(getString(R.string.comment_karma, formatInt(account.getCommentKarma())));
50 |
51 | // OAuth2 stuff
52 | DeferredPersistentTokenStore tokenStore = App.getTokenStore();
53 | PersistedAuthData data = tokenStore.inspect(account.getName());
54 | if (data != null) {
55 | if (data.getLatest() != null) {
56 | // Calculate the amount of minutes in which the OAuthData will expire
57 | long diffMillis = data.getLatest().getExpiration().getTime() - new Date().getTime();
58 | long diffMinutes = TimeUnit.MINUTES.convert(diffMillis, TimeUnit.MILLISECONDS);
59 |
60 | // Update the TextView with this information
61 | textView(R.id.accessTokenStatus).setText(getString(R.string.access_token_status, diffMinutes));
62 | }
63 |
64 | // Show whether or not the data includes a refresh token
65 | textView(R.id.refreshToken).setText(data.getRefreshToken() == null ?
66 | R.string.no_refresh_token : R.string.refresh_token);
67 | }
68 | }
69 |
70 | private TextView textView(@IdRes int id) {
71 | return (TextView) findViewById(id);
72 | }
73 |
74 | private static String formatInt(int n) {
75 | return NumberFormat.getInstance().format(n);
76 | }
77 |
78 | public void onLogout(View view) {
79 | // All this does is remove the current RedditClient reference. If we tried to do
80 | // App.getAccountHelper().getReddit(), it would throw an IllegalStateException.
81 | App.getAccountHelper().logout();
82 | finish();
83 | }
84 |
85 | private static final class GetUserInfoTask extends AsyncTask {
86 | // Use a WeakReference to avoid leaking a Context
87 | private final WeakReference activity;
88 |
89 | GetUserInfoTask(UserOverviewActivity activity) {
90 | this.activity = new WeakReference<>(activity);
91 | }
92 |
93 | @Override
94 | protected void onPreExecute() {
95 | ProgressBar progressBar = getProgressBar();
96 | if (progressBar != null)
97 | progressBar.setVisibility(View.VISIBLE);
98 | }
99 |
100 | @Override
101 | protected Account doInBackground(RedditClient... redditClients) {
102 | return redditClients[0].me().about();
103 | }
104 |
105 | @Override
106 | protected void onPostExecute(Account account) {
107 | // Display the fetched account if the Activity still exists
108 | UserOverviewActivity activity = this.activity.get();
109 | if (activity != null)
110 | activity.show(account);
111 |
112 | // Prefer INVISIBLE instead of GONE so everything doesn't get shifted up a few pixels
113 | // once loading is done
114 | ProgressBar progressBar = getProgressBar();
115 | if (progressBar != null)
116 | progressBar.setVisibility(View.INVISIBLE);
117 | }
118 |
119 | private ProgressBar getProgressBar() {
120 | if (this.activity.get() != null)
121 | return this.activity.get().findViewById(R.id.progress);
122 | return null;
123 | }
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/example-app/src/main/java/net/dean/jraw/android/example/NewUserActivity.java:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android.example;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.graphics.Bitmap;
6 | import android.os.AsyncTask;
7 | import android.os.Build;
8 | import android.os.Bundle;
9 | import android.support.v7.app.AppCompatActivity;
10 | import android.view.View;
11 | import android.webkit.CookieManager;
12 | import android.webkit.CookieSyncManager;
13 | import android.webkit.WebView;
14 | import android.webkit.WebViewClient;
15 |
16 | import net.dean.jraw.oauth.OAuthException;
17 | import net.dean.jraw.oauth.StatefulAuthHelper;
18 |
19 | import java.lang.ref.WeakReference;
20 |
21 | /**
22 | * This activity is dedicated to a WebView to guide the user through the authentication process.
23 | *
24 | * First, a StatefulAuthHelper is created by calling App.getAccountHelper().switchToNewUser(). We
25 | * pull data from/send data to this object during the authentication phase. When the user has been
26 | * authenticated or the user has denied our app access to their account, the activity finishes.
27 | */
28 | public class NewUserActivity extends AppCompatActivity {
29 |
30 | @Override
31 | protected void onCreate(Bundle savedInstanceState) {
32 | super.onCreate(savedInstanceState);
33 | setContentView(R.layout.activity_new_user);
34 |
35 | // Don't save any cookies, cache, or history from previous sessions. If we don't, once the
36 | // first user logs in and authenticates, the next time we go to add a new user, the first
37 | // user will be automatically logged in, which is not what we want.
38 | final WebView webView = findViewById(R.id.webView);
39 | webView.clearCache(true);
40 | webView.clearHistory();
41 |
42 | // Stolen from https://github.com/ccrama/Slide/blob/a2184269/app/src/main/java/me/ccrama/redditslide/Activities/Login.java#L92
43 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
44 | CookieManager.getInstance().removeAllCookies(null);
45 | CookieManager.getInstance().flush();
46 | } else {
47 | CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(this);
48 | cookieSyncMngr.startSync();
49 | CookieManager cookieManager = CookieManager.getInstance();
50 | cookieManager.removeAllCookie();
51 | cookieManager.removeSessionCookie();
52 | cookieSyncMngr.stopSync();
53 | cookieSyncMngr.sync();
54 | }
55 |
56 | // Get a StatefulAuthHelper instance to manage interactive authentication
57 | final StatefulAuthHelper helper = App.getAccountHelper().switchToNewUser();
58 |
59 | // Watch for pages loading
60 | webView.setWebViewClient(new WebViewClient() {
61 | @Override
62 | public void onPageStarted(WebView view, String url, Bitmap favicon) {
63 | if (helper.isFinalRedirectUrl(url)) {
64 | // No need to continue loading, we've already got all the required information
65 | webView.stopLoading();
66 | webView.setVisibility(View.GONE);
67 |
68 | // Try to authenticate the user
69 | new AuthenticateTask(NewUserActivity.this, helper).execute(url);
70 | }
71 | }
72 | });
73 |
74 | // Generate an authentication URL
75 | boolean requestRefreshToken = true;
76 | boolean useMobileSite = true;
77 | String[] scopes = new String[]{ "read", "identity" };
78 | String authUrl = helper.getAuthorizationUrl(requestRefreshToken, useMobileSite, scopes);
79 |
80 | // Finally, show the authorization URL to the user
81 | webView.loadUrl(authUrl);
82 | }
83 |
84 | /**
85 | * An async task that takes a final redirect URL as a parameter and reports the success of
86 | * authorizing the user.
87 | */
88 | private static final class AuthenticateTask extends AsyncTask {
89 | // Use a WeakReference so that we don't leak a Context
90 | private final WeakReference context;
91 |
92 | private final StatefulAuthHelper helper;
93 |
94 | AuthenticateTask(Activity context, StatefulAuthHelper helper) {
95 | this.context = new WeakReference<>(context);
96 | this.helper = helper;
97 | }
98 |
99 | @Override
100 | protected Boolean doInBackground(String... urls) {
101 | try {
102 | helper.onUserChallenge(urls[0]);
103 | return true;
104 | } catch (OAuthException e) {
105 | // Report failure if an OAuthException occurs
106 | return false;
107 | }
108 | }
109 |
110 | @Override
111 | protected void onPostExecute(Boolean success) {
112 | // Finish the activity if it's still running
113 | Activity host = this.context.get();
114 | if (host != null) {
115 | host.setResult(success ? Activity.RESULT_OK : Activity.RESULT_CANCELED, new Intent());
116 | host.finish();
117 | }
118 | }
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # JRAW-Android
2 |
3 | [](https://travis-ci.org/mattbdean/JRAW-Android)
4 | [](https://bintray.com/thatjavanerd/maven/JRAW-Android/_latestVersion)
5 | [](http://kotlinlang.org)
6 | [](https://codecov.io/gh/mattbdean/JRAW-Android)
7 |
8 | This is an extension to the [Java Reddit API Wrapper](https://github.com/mattbdean/JRAW) that adds some Android-specific classes.
9 |
10 | ## Getting Started
11 |
12 | ```groovy
13 | repositories {
14 | jcenter()
15 | }
16 |
17 | dependencies {
18 | // If you include JRAW-Android, you don't need to also include JRAW.
19 | implementation 'net.dean.jraw:JRAW-Android:1.1.0'
20 | }
21 | ```
22 |
23 | Before using this library it is highly recommended that you first read the [OAuth2 page](https://mattbdean.gitbooks.io/jraw/oauth2.html) in the JRAW documentation.
24 |
25 | First create a reddit OAuth2 app [here](https://www.reddit.com/prefs/apps). Note the client ID and redirect URL, you'll need these later.
26 |
27 | Add these `` keys to your manifest:
28 |
29 | ```xml
30 |
31 | ...
32 |
35 |
38 |
41 |
42 | ```
43 |
44 | The `REDDIT_USERNAME` key is used to create a UserAgent for your app. See [here](https://github.com/mattbdean/JRAW-Android/blob/master/lib/src/main/kotlin/net/dean/jraw/android/ManifestAppInfoProvider.kt) for more details.
45 |
46 | Create your `Application` class:
47 |
48 | ```java
49 | public final class App extends Application {
50 | private static AccountHelper accountHelper;
51 | private static SharedPreferencesTokenStore tokenStore;
52 |
53 | @Override
54 | public void onCreate() {
55 | super.onCreate();
56 |
57 | // Get UserAgent and OAuth2 data from AndroidManifest.xml
58 | AppInfoProvider provider = new ManifestAppInfoProvider(getApplicationContext());
59 |
60 | // Ideally, this should be unique to every device
61 | UUID deviceUuid = UUID.randomUUID();
62 |
63 | // Store our access tokens and refresh tokens in shared preferences
64 | tokenStore = new SharedPreferencesTokenStore(getApplicationContext());
65 | // Load stored tokens into memory
66 | tokenStore.load();
67 | // Automatically save new tokens as they arrive
68 | tokenStore.setAutoPersist(true);
69 |
70 | // An AccountHelper manages switching between accounts and into/out of userless mode.
71 | accountHelper = AndroidHelper.accountHelper(provider, deviceUuid, tokenStore);
72 |
73 | // Every time we use the AccountHelper to switch between accounts (from one account to
74 | // another, or into/out of userless mode), call this function
75 | accountHelper.onSwitch(redditClient -> {
76 | // By default, JRAW logs HTTP activity to System.out. We're going to use Log.i()
77 | // instead.
78 | LogAdapter logAdapter = new SimpleAndroidLogAdapter(Log.INFO);
79 |
80 | // We're going to use the LogAdapter to write down the summaries produced by
81 | // SimpleHttpLogger
82 | redditClient.setLogger(
83 | new SimpleHttpLogger(SimpleHttpLogger.DEFAULT_LINE_LENGTH, logAdapter));
84 |
85 | // If you want to disable logging, use a NoopHttpLogger instead:
86 | // redditClient.setLogger(new NoopHttpLogger());
87 |
88 | return null;
89 | });
90 | }
91 |
92 | public static AccountHelper getAccountHelper() { return accountHelper; }
93 | public static SharedPreferencesTokenStore getTokenStore() { return tokenStore; }
94 | }
95 | ```
96 |
97 | Now you can start using JRAW! The [example app](https://github.com/mattbdean/JRAW-Android/tree/master/example-app) fully implements the reddit authentication process. I highly encourage you to build and install the app and read the source code to get a better understanding of the whole process.
98 |
99 | ## Javadoc
100 |
101 | JRAW-Android uses JitPack to host its Javadoc.
102 |
103 | ```
104 | https://jitpack.io/com/github/mattbdean/JRAW-Android/VERSION/javadoc/index.html
105 | ```
106 |
107 | `VERSION` can be a specific commit hash (like [`9390529`](https://jitpack.io/com/github/mattbdean/JRAW-Android/9390529/javadoc/index.html)), a tag, or the HEAD of a branch (like [`master-SNAPSHOT`](https://jitpack.io/com/github/mattbdean/JRAW-Android/master-SNAPSHOT/javadoc/index.html)).
108 |
109 | JitPack produces Javadoc only when necessary, so the first time someone accesses the Javadoc for a specific build it may take a little bit.
110 |
111 | ## FAQ
112 |
113 | ### How do I pass data around?
114 |
115 | All JRAW models implement Serializable, so methods like [`Parcel.writeSerializable`](https://developer.android.com/reference/android/os/Parcel.html#writeSerializable(java.io.Serializable)) and [`Bundle.getSerializable`](https://developer.android.com/reference/android/os/Bundle.html#getParcelable(java.lang.String)) should work fine. You can also transform models to/from JSON if you're concerned about speed:
116 |
117 | ```java
118 | // The serializeNulls() here is very important
119 | JsonAdapter adapter = JrawUtils.moshi.adapter(Submission.class).serializeNulls();
120 | String json = adapter.toJson(someSubmission);
121 |
122 | // Add the JSON to your Bundle/Parcel/whatever
123 | bundle.putString("mySubmission", json);
124 |
125 | // Later...
126 | Submission pojo = adapter.fromJson(bundle.getString("mySubmission"));
127 | someSubmission.equals(pojo); // => true
128 | ```
129 |
130 | See [mattbdean/JRAW#221](https://github.com/mattbdean/JRAW/issues/221) for why the adapter needs to serialize nulls.
131 |
132 | ### How do I use a different version of JRAW (i.e. from JitPack)?
133 |
134 | To use a different version of JRAW than the one directly depended on by JRAW-Android, use this:
135 |
136 | ```groovy
137 | repositories {
138 | // Assuming that you want to use a JitPack build
139 | maven { url 'https://jitpack.io' }
140 | }
141 | dependencies {
142 | compile('net.dean.jraw:JRAW-Android:1.0.0') {
143 | // Don't use the version of JRAW that JRAW-Android depends on
144 | exclude group: 'net.dean.jraw'
145 | }
146 | // JRAW-Android still expects JRAW classes to be available on the classpath. Include a specific
147 | // version of them via JitPack. See https://jitpack.io/#mattbdean/JRAW for more information.
148 | compile 'com.github.mattbdean:JRAW:'
149 | }
150 | ```
151 |
152 | ## Versioning
153 |
154 | Unless otherwise noted, JRAW-Android's version is the same as JRAW. So JRAW-Android v1.1.0 would use JRAW v1.1.0.
155 |
156 | ## Contributing
157 |
158 | This project uses Robolectric for unit tests. Linux and Mac users on Android Studio should see [this](http://robolectric.org/getting-started/#note-for-linux-and-mac-users) when running tests through the IDE.
159 |
--------------------------------------------------------------------------------
/example-app/src/main/java/net/dean/jraw/android/example/MainActivity.java:
--------------------------------------------------------------------------------
1 | package net.dean.jraw.android.example;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.os.AsyncTask;
6 | import android.os.Bundle;
7 | import android.support.v7.app.AppCompatActivity;
8 | import android.support.v7.widget.DividerItemDecoration;
9 | import android.support.v7.widget.LinearLayoutManager;
10 | import android.support.v7.widget.RecyclerView;
11 | import android.view.View;
12 | import android.view.ViewGroup;
13 |
14 | import net.dean.jraw.models.PersistedAuthData;
15 | import net.dean.jraw.oauth.DeferredPersistentTokenStore;
16 |
17 | import java.lang.ref.WeakReference;
18 | import java.util.ArrayList;
19 | import java.util.List;
20 | import java.util.TreeMap;
21 |
22 | /**
23 | * The main activity is a list of all stored authentication data. This data is provided from
24 | * App.getTokenStore(). When an item in the list is clicked, we attempt to authenticate ourselves as
25 | * that user. If we have an unexpired access token, we use that. If we only have a refresh token,
26 | * we use that and request a fresh access token on the next normal request. After we authenticate,
27 | * the UserOverviewActivity is started.
28 | *
29 | * This activity has a FAB in the bottom right-hand corner for authenticating new users. When
30 | * pressed, the NewUserActivity is started. See that class' documentation for what it does.
31 | */
32 | public class MainActivity extends AppCompatActivity {
33 | private static final int REQ_CODE_LOGIN = 0;
34 |
35 | private RecyclerView storedDataList;
36 | private AuthDataAdapter adapter;
37 |
38 | @Override
39 | protected void onCreate(Bundle savedInstanceState) {
40 | super.onCreate(savedInstanceState);
41 | setContentView(R.layout.activity_main);
42 |
43 | // Create the RecyclerView's LayoutManager and Adapter
44 | this.storedDataList = findViewById(R.id.storedDataList);
45 | LinearLayoutManager layoutManager = new LinearLayoutManager(this);
46 | this.adapter = new AuthDataAdapter(this, storedDataList, App.getTokenStore());
47 |
48 | // Configure the RecyclerView
49 | storedDataList.setLayoutManager(layoutManager);
50 | storedDataList.setAdapter(adapter);
51 | storedDataList.addItemDecoration(new DividerItemDecoration(this, layoutManager.getOrientation()));
52 | }
53 |
54 | @Override
55 | protected void onResume() {
56 | super.onResume();
57 |
58 | // The data in the TokenStore might have changed, let's update the RecyclerView
59 | adapter.update();
60 |
61 | // Show the RecyclerView if there's data, otherwise show a message
62 | boolean hasData = App.getTokenStore().size() == 0;
63 | storedDataList.setVisibility(hasData ? View.GONE : View.VISIBLE);
64 | findViewById(R.id.noDataMessage).setVisibility(hasData ? View.VISIBLE : View.GONE);
65 | }
66 |
67 | // Called when the FAB is clicked
68 | public void onNewUserRequested(View view) {
69 | startActivityForResult(new Intent(this, NewUserActivity.class), REQ_CODE_LOGIN);
70 | }
71 |
72 | @Override
73 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
74 | // The user could have pressed the back button before authorizing our app, make sure we have
75 | // an authenticated user before starting the UserOverviewActivity.
76 | if (requestCode == REQ_CODE_LOGIN && resultCode == RESULT_OK) {
77 | startActivity(new Intent(this, UserOverviewActivity.class));
78 | }
79 | }
80 |
81 | /**
82 | * This Adapter pulls its data from a TokenStore
83 | */
84 | private static class AuthDataAdapter extends RecyclerView.Adapter {
85 | private final WeakReference activity;
86 | private final DeferredPersistentTokenStore tokenStore;
87 | private List usernames;
88 | private TreeMap data;
89 | private RecyclerView recyclerView;
90 |
91 | private AuthDataAdapter(MainActivity mainActivity, RecyclerView recyclerView, DeferredPersistentTokenStore tokenStore) {
92 | this.activity = new WeakReference<>(mainActivity);
93 | this.recyclerView = recyclerView;
94 | this.tokenStore = tokenStore;
95 | update();
96 | }
97 |
98 | private void update() {
99 | this.data = new TreeMap<>(tokenStore.data());
100 |
101 | // Prefer this instead of tokenStore.getUsernames() because this.data.keySet() is sorted
102 | this.usernames = new ArrayList<>(this.data.keySet());
103 | notifyDataSetChanged();
104 | }
105 |
106 | @Override
107 | public AuthDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
108 | // Create a new TokenStoreUserView when requested
109 | TokenStoreUserView view = new TokenStoreUserView(parent.getContext());
110 |
111 | // Give the view max width and minimum height
112 | view.setLayoutParams(new RecyclerView.LayoutParams(
113 | ViewGroup.LayoutParams.MATCH_PARENT,
114 | ViewGroup.LayoutParams.WRAP_CONTENT
115 | ));
116 |
117 | // Listen for the view being clicked
118 | view.setOnClickListener(clickedView -> {
119 | int itemPos = recyclerView.getChildLayoutPosition(clickedView);
120 |
121 | // Potential bug: Clicking on two different items in a very short period of time
122 | // could cause this task to be executed twice
123 | new ReauthenticationTask(activity).execute(usernames.get(itemPos));
124 | });
125 |
126 | return new AuthDataViewHolder(view);
127 | }
128 |
129 | @Override
130 | public void onBindViewHolder(AuthDataViewHolder holder, int position) {
131 | // Tell the TokenStoreUserView to change the data it's showing when the view holder gets
132 | // recycled
133 | String username = this.usernames.get(position);
134 | holder.view.display(username, data.get(username));
135 | }
136 |
137 | @Override
138 | public int getItemCount() {
139 | return data.size();
140 | }
141 | }
142 |
143 | private static class AuthDataViewHolder extends RecyclerView.ViewHolder {
144 | private TokenStoreUserView view;
145 |
146 | private AuthDataViewHolder(TokenStoreUserView itemView) {
147 | super(itemView);
148 | this.view = itemView;
149 | }
150 | }
151 |
152 | private static class ReauthenticationTask extends AsyncTask {
153 | private final WeakReference activity;
154 |
155 | ReauthenticationTask(WeakReference activity) {
156 | this.activity = activity;
157 | }
158 |
159 | @Override
160 | protected Void doInBackground(String... usernames) {
161 | App.getAccountHelper().switchToUser(usernames[0]);
162 | return null;
163 | }
164 |
165 | @Override
166 | protected void onPostExecute(Void aVoid) {
167 | Activity activity = this.activity.get();
168 |
169 | if (activity != null) {
170 | activity.startActivity(new Intent(activity, UserOverviewActivity.class));
171 | }
172 | }
173 | }
174 | }
175 |
--------------------------------------------------------------------------------