Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add realtime functionality to drawer. Close #3. #4

Merged
merged 6 commits into from
Feb 27, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,5 @@ dependencies {
compile "com.android.support:appcompat-v7:23.0.1"
compile "com.facebook.react:react-native:0.20.+"
compile project(':ExtraDimensions')
compile project(':react-native-gitter-faye')
}
1 change: 1 addition & 0 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
package="com.gittermobile">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
android:allowBackup="true"
Expand Down
5 changes: 4 additions & 1 deletion android/app/src/main/java/com/gittermobile/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

import ca.jaysoo.extradimensions.ExtraDimensionsPackage;

import com.terrysahaidak.faye.FayeGitterPackage;

public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
Expand Down Expand Up @@ -36,7 +38,8 @@ protected boolean getUseDeveloperSupport() {
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new ExtraDimensionsPackage(this)
new ExtraDimensionsPackage(this),
new FayeGitterPackage()
);
}
}
3 changes: 2 additions & 1 deletion android/settings.gradle
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
rootProject.name = 'gittermobile'

include ':app', ':ExtraDimensions'
include ':app', ':ExtraDimensions', ':react-native-gitter-faye'
project(':react-native-gitter-faye').projectDir = new File(rootProject.projectDir, '../libs/react-native-gitter-faye')
project(':ExtraDimensions').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-extra-dimensions-android/android')
2 changes: 1 addition & 1 deletion app/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {Provider} from 'react-redux'
import configureStore from './configureStore'

import App from './screens'
import {init} from './modules/init'
import {init} from './modules/app'

const store = configureStore()

Expand Down
172 changes: 172 additions & 0 deletions app/modules/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import {getItem, removeItem} from '../utils/storage'
import {getCurrentUser} from './viewer'
import {getRooms, getSuggestedRooms, subscribeToRooms, updateRoomState} from './rooms'
import FayeGitter from '../../libs/react-native-gitter-faye'
import {DeviceEventEmitter, NetInfo, AppState} from 'react-native'

/**
* Constants
*/

export const INITIALIZED = 'app/INITIALIZED'
export const CHANGE_NET_STATUS = 'app/CHANGE_NET_STATUS'
export const CHANGE_APP_STATE = 'app/CHANGE_APP_STATE'
export const FAYE_CONNECT = 'app/FAYE_CONNECT'

/**
* Action Creators
*/

export function init() {
return async (dispatch, getState) => {
dispatch(setupAppStatusListener())
dispatch(setupFayeEvents())
try {
const token = await getItem('token')
const netStatus = await NetInfo.fetch()
dispatch({ type: INITIALIZED, token, netStatus })

// TODO: do things belowe only if the internet is awailible (netStatus)

// getting base current user's information
await dispatch(getCurrentUser())
await Promise.all([
dispatch(getRooms()),
dispatch(getSuggestedRooms())
])

// setup faye
await dispatch(setupFaye())
await dispatch(setupNetStatusListener())
} catch (error) {
dispatch({ type: INITIALIZED, error })
}
}
}

function setupFaye() {
return async (dispatch, getState) => {
FayeGitter.setAccessToken(getState().auth.token)
FayeGitter.create()
FayeGitter.logger()
try {
const result = await FayeGitter.connect()
dispatch({type: FAYE_CONNECT, payload: result})
dispatch(subscribeToRooms())
} catch (err) {
console.log(err) // eslint-disable-line no-console
}
}
}

function onNetStatusChangeFaye(status) {
return async (dispatch, getState) => {
const {fayeConnected} = getState().app
if (!status && fayeConnected) {
dispatch({type: FAYE_CONNECT, payload: status})
}
if (status && !fayeConnected) {
dispatch(setupFaye())
}
}
}

function setupNetStatusListener() {
return dispatch => {
NetInfo.isConnected.addEventListener('change',
async status => {
dispatch({type: CHANGE_NET_STATUS, payload: status})
await dispatch(onNetStatusChangeFaye(status))
}
);
}
}

function setupAppStatusListener() {
return dispatch => {
AppState.addEventListener('change',
status => dispatch({type: CHANGE_APP_STATE, payload: status})
);
}
}


function setupFayeEvents() {
return (dispatch, getState) => {
DeviceEventEmitter
.addListener('FayeGitter:onDisconnected', log => {
console.warn(log) // eslint-disable-line no-console
dispatch(setupFaye())
})

DeviceEventEmitter
.addListener('FayeGitter:onFailedToCreate', log => {
console.warn(log) // eslint-disable-line no-console
if (getState().app.netStatus) {
dispatch(setupFaye())
}
})
DeviceEventEmitter
.addListener('FayeGitter:Message', event => {
dispatch(parseEvent(event))
})
DeviceEventEmitter
.addListener('FayeGitter:SubscribtionFailed', log => console.warn(log)) // eslint-disable-line no-console
DeviceEventEmitter
.addListener('FayeGitter:Subscribed', log => console.log(log)) // eslint-disable-line no-console
DeviceEventEmitter
.addListener('FayeGitter:Unsubscribed', log => console.log(log)) // eslint-disable-line no-console
DeviceEventEmitter
.addListener('FayeGitter:log', log => console.log(log)) // eslint-disable-line no-console
}
}

function parseEvent(event) {
return (dispatch, getState) => {
const message = JSON.parse(event.json)
const {id} = getState().viewer.user
const roomsChannel = `/api/v1/user/${id}/rooms`

if (event.channel.match(roomsChannel)) {
dispatch(updateRoomState(message))
}
}
}


/**
* Reducer
*/

const initialState = {
online: null,
appState: null,
fayeConnected: false
}

export default function app(state = initialState, action) {
switch (action.type) {
case INITIALIZED:
return {...state,
online: action.netStatus
}

case CHANGE_NET_STATUS:
return {...state,
online: action.payload
}

case CHANGE_APP_STATE:
return {...state,
appState: action.payload
}

case FAYE_CONNECT:
return {...state,
fayeConnected: action.payload
}

default:
return state
}
}
2 changes: 1 addition & 1 deletion app/modules/auth.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {INITIALIZED} from './init'
import {INITIALIZED} from './app'
import {setItem, removeItem} from '../utils/storage'
import _ from 'lodash'
import {getCurrentUser} from './viewer'
Expand Down
2 changes: 2 additions & 0 deletions app/modules/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import {combineReducers} from 'redux'
import app from './app'
import auth from './auth'
import rooms from './rooms'
import viewer from './viewer'


const rootReducer = combineReducers({
app,
auth,
rooms,
viewer
Expand Down
31 changes: 0 additions & 31 deletions app/modules/init.js

This file was deleted.

39 changes: 38 additions & 1 deletion app/modules/rooms.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import * as Api from '../api/gitter'
import _ from 'lodash'
import FayeGitter from '../../libs/react-native-gitter-faye'
import normalize from '../utils/normalize'
import {LOGOUT} from './auth'

Expand All @@ -14,6 +16,9 @@ export const SUGGESTED_ROOMS = 'rooms/SUGGESTED_ROOMS'
export const SUGGESTED_ROOMS_RECEIVED = 'rooms/SUGGESTED_ROOMS_RECEIVED'
export const SUGGESTED_ROOMS_FAILED = 'rooms/SUGGESTED_ROOMS_FAILED'
export const SELECT_ROOM = 'rooms/SELECT_ROOM'
export const ROOMS_SUBSCRIBED = 'rooms/ROOMS_SUBSCRIBED'
export const ROOMS_UNSUBSCRIBED = 'rooms/ROOMS_UNSUBSCRIBED'
export const UPDATE_ROOM_STATE = 'rooms/UPDATE_ROOM_STATE'


/**
Expand Down Expand Up @@ -62,6 +67,28 @@ export function selectRoom(roomId) {
return {type: SELECT_ROOM, payload: roomId}
}

/**
* Subscribe current user rooms changes (Drawer)
*/

export function subscribeToRooms() {
return (dispatch, getState) => {
const {id} = getState().viewer.user
FayeGitter.subscribe(`/api/v1/user/${id}/rooms`)
dispatch({type: ROOMS_SUBSCRIBED})
}
}

/**
* Update unread count by faye action
*/

export function updateRoomState(json) {
return dispatch => {
dispatch({type: UPDATE_ROOM_STATE, payload: json})
}
}

/**
* Reducer
*/
Expand Down Expand Up @@ -107,8 +134,18 @@ export default function rooms(state = initialState, action) {
}
}

case UPDATE_ROOM_STATE: {
const {id} = action.payload.model
const room = state.rooms[id]
return {...state,
rooms: {...state.rooms,
[id]: _.merge(room, action.payload.model)
}
}
}

case LOGOUT: {
return Object.assign({}, initialState)
return initialState
}

case SUGGESTED_ROOMS_FAILED:
Expand Down
21 changes: 21 additions & 0 deletions libs/react-native-gitter-faye/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
## react-native-gitter-faye

#### example
```
FayeGitter.setAccessToken('token')
FayeGitter.create()

FayeGitter.connect().then(() => {
FayeGitter.subscribe('/api/v1/user/555e610f15522ed4b3e0c169/rooms')
FayeGitter.logger()
})

// events
FayeGitter:onDisconnected
FayeGitter:onFailedToCreate
FayeGitter:Message
FayeGitter:SubscribtionFailed
FayeGitter:Subscribed
FayeGitter:Unsubscribed
FayeGitter:log
```
Loading