Gitter.im Java SDK that facilitates communication with Gitter API.
Java
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
gradle/wrapper
library
samples
.gitignore
.travis.yml
LICENSE
README.md
build.gradle
gradlew
gradlew.bat
settings.gradle

README.md

Build Status

Gitter.im Java SDK

👍 Fully compatible with Android

Async : Download

Sync : Download

Rx : Download Coverage Status

Android Arsenal

Join the chat at https://gitter.im/Gitteroid/GitterRxJavaSDK

Gitter.im Java SDK that facilitates communication with Gitter API, Gitter Streaming API, Gitter Faye API.

It provides three approaches to work with API:

  • RxJava approach;
  • Async (callback) approach.
  • Sync approach.

Table of content

Setup

Add gradle dependency:

For RxJava:

repositories {
      jcenter()
}

dependencies {
      compile 'com.github.amatkivskiy:gitter.sdk.rx:1.6.1'
}

For async:

repositories {
      jcenter()
}

dependencies {
      compile 'com.github.amatkivskiy:gitter.sdk.async:1.6.1'
}

For sync:

repositories {
      jcenter()
}

dependencies {
      compile 'com.github.amatkivskiy:gitter.sdk.sync:1.6.1'
}

Release notes

  • 1.6.1 (04.01.2018)

    • Rx,Async,Sync:
      • Add getRoomIdByUri to room API
    • Update dependencies used in the SDK
  • 1.6.0 (12.01.2017)

    • RoomResponse:

      • Remove favouriteOrder
      • Add avatarUrl
      • Add groupId
      • Add public
      • Add activity
      • Add premium
    • UserResponse:

      • Add avatarUrl
      • Add role
      • Add staff
    • Rx,Async,Sync:

      • Add delete room API
      • Remove channels API
      • Fix joinRoom API
      • Add getRoomById API
      • Add getBannedusers API
      • Add banUser API
      • Add unBanUser API
      • Add Welcome API support
    • Faye

      • Update OkHttp to version 3.5.0
  • 1.5.1 (07.05.2016)

    • Updated RoomRepsonse data structure.
    • Added aroundId and q params for chat messages request.
    • Added Update room request.
    • Fixed Issue data structure type.
    • Faye: added ability to set custom OkHttpClient.
    • Faye: changed onSubscribed() params, no it passes messages snapshots.
  • 1.5 (14.01.2016)

    • Added faye api support.
    • Added room events streaming api support.
  • 1.4

    • Refactored library structure
    • Added async api support.
    • Added async api samples.
    • Added sync api support.
    • Added sync api samples.
  • 1.2.1

    • Added ability to retrieve unread messages.
  • 1.2.0

    • Added ability to search users
    • Added ability to search rooms
    • Added ability to leave room
  • 1.1.0

    • Added room messages streaming API.

Features

  • Authentication

Rooms resource

  • List rooms
  • Room users
  • Channels
  • Join a room
  • Remove user from the room
  • Leave room
  • Search rooms

User resource

  • Current user
  • User rooms
  • User orgs
  • User repos
  • User channels
  • Search users

Messages resource

  • Unread items
  • List messages
  • Send a message
  • Update a message

❗️ Streaming (Avalible only in Rx part.)

  • Room messages stream
  • Room events stream

❗️ Faye API (Avalible only in Async part.)

  • Room messages events
  • Room user presence events
  • Room user managment events

Description

Authentication Please read Authentication article on Gitter Developer before.

How to authenticate user with SDK

  1. Setup GitterDeveloperCredentials with info from here:
GitterDeveloperCredentials.init(new SimpleGitterCredentialsProvider(your_oauth_key, your_oauth_secret, your_redirect_url));
  1. Get Gitter request access URL:
String gitterAccessUrl = GitterOauthUtils.buildOauthUrl();
  1. Open this url in something like embedded browser and listen for redirects.
  2. When user grants access gitter redirects back with url like:
http://some.redirect.url?code=deadbeef

extract code parameter value.

  1. Exchange code for access token:
  • Rx:
RxGitterAuthenticationClient authenticationClient = new RxGitterAuthenticationClient.Builder().build();

authenticationClient.getAccessToken(code).subscribe(new Action1<AccessTokenResponse>() {
      @Override
      public void call(AccessTokenResponse accessTokenResponse) {
        System.out.println("Access token = " + accessTokenResponse.accessToken);
      }
    });
  • Async:
AsyncGitterAuthenticationClient authenticationClient = new AsyncGitterAuthenticationClient.Builder()
        .build();

authenticationClient.getAccessToken(code, new Callback<AccessTokenResponse>() {
	
		@Override
        public void success(AccessTokenResponse tokenResponse, Response response) {
		System.out.println("Access token = " + accessTokenResponse.accessToken);
        }

        @Override
        public void failure(RetrofitError error) {}
});
  • Sync:
SyncGitterAuthenticationClient authenticationClient = new SyncGitterAuthenticationClient.Builder()
        .build();

AccessTokenResponse accessTokenResponse = authenticationClient.getAccessToken(code);
System.out.println("Access token = " + accessTokenResponse.accessToken);
  1. Save and use this accessToken to make requests to the REST API.

How to get data from Gitter REST API

  1. Create GitterApiClient with help of GitterApiClient.Builder:
  • Rx:
RxGitterApiClient client = new RxGitterApiClient.Builder()
        .withAccountToken("user_access_token")
        .build();
  • Async:
AsyncGitterApiClient client = new AsyncGitterApiClient.Builder()
        .withAccountToken("user_access_token")
        .build();
  • Sync:
SyncGitterApiClient client = new SyncGitterApiClient.Builder()
        .withAccountToken("user_access_token")
        .build();

also you can provide some Retrofit config for requests (same for Rx and Async):

RxGitterApiClient client = new RxGitterApiClient.Builder()
        .withAccountToken("user_access_token")
        .withClient(new OkClient())
        .withExecutors(httpExecutor, callbackExecutor)
        .withLogLevel(RestAdapter.LogLevel.BASIC)
        .build();
  1. Execute any request that you need:
  • Rx:
client.getCurrentUser().subscribe(new Action1<UserResponse>() {
      @Override
      public void call(UserResponse user) {
        System.out.println("user.displayName = " + user.displayName);
      }
    });
  • Async:
client.getCurrentUser(new Callback<UserResponse>() {
      @Override
      public void success(UserResponse userResponse, Response response) {
        System.out.println("userResponse.displayName = " + userResponse.displayName);
      }

      @Override
      public void failure(RetrofitError error) {
        System.err.println("error = " + error);
      }
    });
  • Sync:
UserResponse userResponse = client.getCurrentUser();
System.out.println("userResponse.displayName = " + userResponse.displayName);

or

  • Rx:
ChatMessagesRequestParams params = new ChatMessagesRequestParamsBuilder().limit(20).build();
String roomId = "room_id";

client.getRoomMessages(roomId, params).subscribe(new Action1<List<MessageResponse>>() {
      @Override
      public void call(List<MessageResponse> messages) {
        System.out.println("Received " + messages.size() + " messages");
      }
    });
  • Async:
ChatMessagesRequestParams params = new ChatMessagesRequestParamsBuilder().limit(20).build();
String roomId = "room_id";

client.getRoomMessages(roomId, params, new Callback<List<MessageResponse>>() {
      @Override
      public void success(List<MessageResponse> messages, Response response) {
        System.out.println("Received " + messages.size() + " messages");
      }

      @Override
      public void failure(RetrofitError error) {}
    });
  • Sync:
ChatMessagesRequestParams params = new ChatMessagesRequestParamsBuilder().limit(20).build();
String roomId = "room_id";

List<MessageResponse> messages = client.getRoomMessages(roomId, params);
System.out.println("Received " + messages.size() + " messages");

or

  • Rx:
client.getUserChannels("user_id").subscribe(new Action1<List<RoomResponse>>() {
      @Override
      public void call(List<RoomResponse> rooms) {
        System.out.println("Received " + rooms.size() + " rooms");
      }
    });
  • Async:
client.getUserChannels("user_id", new Callback<List<RoomResponse>>() {
      @Override
      public void success(List<RoomResponse> rooms, Response response) {
        System.out.println("Received " + rooms.size() + " rooms");
      }

      @Override
      public void failure(RetrofitError error) {}
    });
  • Sync:
List<RoomResponse> rooms = client.getUserChannels("user_id");
System.out.println("Received " + rooms.size() + " rooms");

How to get streaming data from Gitter Streaming API

❗️ Please don't set any log level for RxGitterStreamingApiClient as it blocks the stream.

❗️ If you get java.net.SocketTimeoutException: Read timed out try to encrease ReadTimeout in your retrofit.client.Client and spicify this client for GutterApiClient (withClient()).

RxGitterStreamingApiClient client = new RxGitterStreamingApiClient.Builder()
        .withAccountToken("user_access_token")
        .build();

String roomId = "room_id";

client.getRoomMessagesStream(roomId).subscribe(new Action1<MessageResponse>() {
	@Override
	public void call(MessageResponse messageResponse) {
		System.out.println("messageResponse = " + messageResponse);
	}
});

or

RxGitterStreamingApiClient client = new RxGitterStreamingApiClient.Builder()
        .withAccountToken("user_access_token")
        .build();

String roomId = "room_id";

client.getRoomEventsStream(roomId).subscribe(new Action1<RoomEvent>() {
	@Override
	public void call(RoomEvent event) {
		System.out.println(event.sent);
	        System.out.println(event.meta);
	}
});

How to work with Gitter Faye API

1 Setup AsyncGitterFayeClient:

AsyncGitterFayeClient client = new AsyncGitterFayeClientBuilder()
        .withAccountToken("account_token")
        .withOnDisconnected(new DisconnectionListener() {
          @Override
          public void onDisconnected() {
            // Client has disconnected. You can reconnect it here.
          }
        })
        .withOkHttpClient(new OkHttpClient())
        .build();

2 Connect it to the server:

client.connect(new ConnectionListener() {
      @Override
      public void onConnected() {
        // Client is ready. Subscribe to channels you are intereseted in.
      }
    });

3 Subscribe to desighed channel:

client.subscribe(new RoomMessagesChannel("room_id") {
          @Override
          public void onMessage(String channel, MessageEvent message) {
            // Yeah, you've got message here.
          }
});

or

client.subscribe(new RoomUserPresenceChannel("room_id") {
          @Override
          public void onMessage(String channel, UserPresenceEvent message) {
            // User is active or not.
          }
});

or

client.subscribe(new RoomUsersChannel("room_id") {
          @Override
          public void onMessage(String channel, UserEvent message) {
            // User left ot joined the room.
          }
});

or define your custom channel:

client.subscribe("channel_name",new ChannelListener(){
@Override
public void onMessage(String channel,JsonObject message){
//        Handle message here.
    }

@Override
public void onFailed(String channel,Exception ex){
    }

@Override
public void onSubscribed(String channel, List<MessageResponse> messagesSnapshot){
    }

@Override
public void onUnSubscribed(String channel){
    }
    });

You can unsubscribe from channel:

client.unSubscribe("channel_name");

or

RoomMessagesChannel channel = new RoomMessagesChannel("room_id") {
        @Override
        public void onMessage(String channel, MessageEvent message) {
        }
};
client.subscribe(channel);

client.unSubscribe(channel);

Finally when your are finished with client, you need to call:

client.disconnect();

Thats all =).

Samples

You can see some code samples here

Feel free to ask any questions.

LICENSE

The MIT License (MIT)

Copyright (c) 2017 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.