1+ import promisify from '../promisify'
2+ import { Base , ReferenceBase } from './base'
3+
4+ class PresenceRef extends ReferenceBase {
5+ constructor ( presence , ref ) {
6+ super ( presence . firestack ) ;
7+
8+ const db = this . firestack . database ;
9+ this . ref = ref ;
10+ this . _connectedRef = db . ref ( '.info/connected' ) ;
11+
12+ this . _onConnect = [ ] ;
13+ }
14+
15+ setOnlineFor ( path ) {
16+ const connectedDeviceRef = this . ref . child ( path )
17+ this . _lastOnlineRef = connectedDeviceRef . child ( 'lastOnline' ) ;
18+
19+ this . _connectedRef . on ( 'value' , ( snapshot ) => {
20+ const val = snapshot . val ( ) ;
21+ if ( val ) {
22+ // add self to connection list
23+ // this.ref.push()
24+ connectedDeviceRef . setAt ( {
25+ online : true
26+ } )
27+ . then ( ( ) => {
28+ connectedDeviceRef . onDisconnect ( )
29+ . setValue ( {
30+ online : false
31+ } ) ;
32+
33+ this . _lastOnlineRef . onDisconnect ( )
34+ . setValue ( this . firestack . ServerValue . TIMESTAMP )
35+
36+ this . _onConnect . forEach ( fn => {
37+ if ( fn && typeof fn === 'function' ) {
38+ fn . bind ( this ) ( connectedDeviceRef ) ;
39+ }
40+ } )
41+ } )
42+ }
43+ } )
44+ }
45+
46+ }
47+
48+ export class Presence extends Base {
49+ constructor ( firestack , options = { } ) {
50+ super ( firestack , options ) ;
51+ }
52+
53+ on ( path = 'presence/connections' ) {
54+ const _ref = this . firestack . database . ref ( path ) ;
55+ return new PresenceRef ( this , _ref ) ;
56+ }
57+
58+ ref ( dbRef , path ) {
59+ return new PresenceRef ( this , dbRef , path ) ;
60+ }
61+
62+ _pathKey ( ...path ) {
63+ return path . join ( '-' ) ;
64+ }
65+
66+ get namespace ( ) {
67+ return 'firestack:presence'
68+ }
69+ }
70+
71+ export default Presence ;
0 commit comments