RxSocialConnect-Android


Source link: https://github.com/FuckBoilerplate/RxSocialConnect-Android

OAuth RxJava extension for Android. iOS version is located at this repository.

RxSocialConnect

RxSocialConnect simplifies the process of retrieving authorizations tokens from multiple social networks to a minimalist observable call, from any Fragment or Activity.

OAuth20Service facebookService = //...  RxSocialConnect.with(fragmentOrActivity, facebookService)

.subscribe(response -> response.targetUI().showResponse(response.token()));

Features:

  • Webview implementation to handle the sequent steps of oauth process.
  • Storage of tokens encrypted locally
  • Automatic refreshing tokens taking care of expiration date.
  • I/O operations performed on secondary threads and automatic sync with user interface on the main thread, thanks to RxAndroid
  • Mayor social network supported, more than 16 providers; including Facebook, Twitter, GooglePlus, LinkedIn and so on. Indeed, it supports as many providers as ScribeJava does, because RxSocialConnect is a reactive-android wrapper around it.
  • Honors the observable chain. RxOnActivityResult allows RxSocialConnect to transform every oauth process into an observable for a wonderful chaining process.

Setup

Add the JitPack repository in your build.gradle (top level module):

allprojects {

  repositories {

jcenter()

maven {
 url "https://jitpack.io" 
}

  
}
 
}

And add next dependencies in the build.gradle of android app module:

dependencies {

  compile 'com.github.VictorAlbertos.RxSocialConnect-Android:core:1.0.1-2.x'
  compile 'io.reactivex.rxjava2:rxjava:2.0.5' 
}

Usage

Because RxSocialConnect uses RxActivityResult to deal with intent calls, all its requirements and features are inherited too.

Before attempting to use RxSocialConnect, you need to call RxSocialConnect.register in your Android Application class, supplying as parameter the current instance and an encryption key in order to save the tokens on disk encrypted, as long as an implementation of JSONConverter interface.

Because RxSocialConnect uses internally Jolyglot to save on disk the tokens retrieved, you need to add one of the next dependency to gradle.

dependencies {

  // To use Gson 
  compile 'com.github.VictorAlbertos.Jolyglot:gson:0.0.3'

 // To use Jackson
  compile 'com.github.VictorAlbertos.Jolyglot:jackson:0.0.3'

 // To use Moshi
  compile 'com.github.VictorAlbertos.Jolyglot:moshi:0.0.3' 
}
public class SampleApp extends Application {

@Override public void onCreate() {

super.onCreate();

RxSocialConnect.register(this, "myEncryptionKey")

 .using(new GsonSpeaker());

  
}
 
}

Every feature RxSocialConnect exposes can be accessed from both, an activity or a fragment instance.

Limitation:: Your fragments need to extend from android.support.v4.app.Fragment instead of android.app.Fragment, otherwise they won't be notified.

The generic type of the observable returned by RxSocialConnect when subscribing to any of its providers is always an instance of Response class.

This instance holds a reference to the current Activity/Fragment, accessible calling targetUI() method. Because the original one may be recreated it would be unsafe calling it. Instead, you must call any method/variable of your Activity/Fragment from this instance encapsulated in the response instance.

Also, this instance holds a reference to the token.

Retrieving tokens using OAuth1.

On social networks which use OAuth1 protocol to authenticate users (such us Twitter), you need to build a OAuth10aService instance and pass it to RxSocialConnect.

OAuth10aService twitterService = new ServiceBuilder()

  .apiKey(consumerKey)

  .apiSecret(consumerSecret)

  .callback(callbackUrl)

  .build(TwitterApi.instance());

RxSocialConnect.with(fragmentOrActivity, twitterService)

.subscribe(response -> {

 OAuth1AccessToken token = response.token();

 response.targetUI().showToken(token.getToken());

 response.targetUI().showToken(token.getTokenSecret());

}
);

Once the OAuth1 process has been successfully completed, you can retrieve the cached token calling RxSocialConnect.getTokenOAuth1(defaultApi10aClass) -where defaultApi10aClass is the provider class used on the oauth1 process.


  RxSocialConnect.getTokenOAuth1(TwitterApi.class)

  .subscribe(token -> showResponse(token),

 error -> showError(error));
 

Retrieving tokens using OAuth2.

On social networks which use OAuth2 protocol to authenticate users (such us Facebook, Google+ or LinkedIn), you need to build a OAuth20Service instance and pass it to RxSocialConnect.

OAuth20Service facebookService = new ServiceBuilder()

  .apiKey(appId)

  .apiSecret(appSecret)

  .callback(callbackUrl)

  .scope("public_profile")

  .build(FacebookApi.instance());

RxSocialConnect.with(fragmentOrActivity, facebookService)

.subscribe(response -> {

 OAuth2AccessToken token = response.token();

 response.targetUI().showToken(token.getAccessToken());

}
);

Once the OAuth2 process has been successfully completed, you can retrieve the cached token calling RxSocialConnect.getTokenOAuth2(defaultApi20Class) -where defaultApi20Class is the provider class used on the oauth2 process.


  RxSocialConnect.getTokenOAuth2(FacebookApi.class)

  .subscribe(token -> showResponse(token),

 error -> showError(error));
 

Token lifetime.

After retrieving the token, RxSocialConnect will save it on disk to return it on future calls without doing again the oauth process. This token only will be evicted from cache if it is a OAuth2AccessToken instance and its expiration time has been fulfilled.

But, if you need to close an specific connection (or delete the token from the disk for that matters), you can call RxSocialConnect.closeConnection(baseApiClass) at any time to evict the cached token -where baseApiClass is the provider class used on the oauth process.

//Facebook RxSocialConnect.closeConnection(FacebookApi.class)

  .subscribe(_I ->  showToast("Facebook disconnected"));
  //Twitter RxSocialConnect.closeConnection(TwitterApi.class)

  .subscribe(_I ->  showToast("Twitter disconnected"));

You can also close all the connections at once, calling RxSocialConnect.closeConnections()

RxSocialConnect.closeConnections()

  .subscribe(_I ->  showToast("All disconnected"));

OkHttp interceptors.

RxSocialConnect can be powered with OkHttp (or Retrofit for that matters) to bypass authentication header configuration when dealing with specific endpoints. Using the interceptors provided by RxSocialConnect, it's a 0 configuration process to be able to reach any http resource from any api client (Facebook, Twitter, etc).

First of all, install RxSocialConnectInterceptors library using gradle:

dependencies {

  compile 'com.github.VictorAlbertos.RxSocialConnect-Android:okhttp_interceptors:1.0.1-2.x' 
}

After you have retrieved a valid token -if you attempt to use these interceptors prior to retrieving a valid token a NotActiveTokenFoundException will be thrown, you can now use OAuth1Interceptor or OAuth2Interceptor classes to bypass the authentication headers configuration, depending on the OAuth version of your social network of interest.

OAuth1Interceptor.

OAuth10aService yahooService = //...  OkHttpClient client = new OkHttpClient.Builder()

  .addInterceptor(new OAuth1Interceptor(yahooService))

  .build();
  //If using retrofit...  YahooApiRest yahooApiRest = new Retrofit.Builder()

.baseUrl("")

.client(client)

.build().create(YahooApiRest.class);

OAuth2Interceptor.

OkHttpClient client = new OkHttpClient.Builder()

  .addInterceptor(new OAuth2Interceptor(FacebookApi.class))

  .build();
  //If using retrofit...  FacebookApiRest facebookApiRest = new Retrofit.Builder()

.baseUrl("")

.client(client)

.build().create(FacebookApiRest.class);

Now you are ready to perform any http call against any api in the same way you would do it for no OAuth apis.

Examples

  • Social networks connections examples can be found here.
  • OkHttp interceptors examples can be found here.

Proguard

-dontwarn javax.xml.bind.DatatypeConverter -dontwarn org.apache.commons.codec.** -dontwarn com.ning.http.client.** 

Credits

Author

Víctor Albertos

Another author's libraries using RxJava:

  • RxCache: Reactive caching library for Android and Java.
  • Mockery: Android and Java library for mocking and testing networking layers with built-in support for Retrofit
  • RxActivityResult: A reactive-tiny-badass-vindictive library to break with the OnActivityResult implementation as it breaks the observables chain.
  • RxFcm: RxJava extension for Android Firebase Cloud Messaging (aka fcm).
  • RxPaparazzo: RxJava extension for Android to take images using camera and gallery.

Resources

A Gradle plugin witch automatically packs texture for a libgdx game, using libgdx texture packer. Before packing, the plugin can do some actions on the resources provided, such as:

  • Resize images for variants
  • Generate 1 pixel 9-patches automatically
  • Convert SVG to PNG images

Gradle tasks for easy integration with ImageMagick.

The code brings up an easy way of using recyclerView, with the new recycler adapters. It also contains a BaseRecyclerFragment and a RecyclerStandalone that removes a lot of boiler plate for fragments that contains either grids or lists. It also offers out of the box a DividerItemDecoration that handles the drawing of the divider in the recycler view. As well selectors for the items in your lists are handled.

RecyclerView-FlexibleDivider - Android library providing simple way to control divider items of RecyclerView.

JDeferred is a Java Deferred/Promise library similar to JQuery's Deferred Object.

android-deferred-object is a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes