all files / src/core/ User.js

1.72% Statements 1/58
0% Branches 0/16
0% Functions 0/24
1.75% Lines 1/57
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199                                                                                                                                                                                                                                                                                                                                                                                                           
import * as DataSync from './util/DataSync';
import cache from './util/cache';
import * as Log from './util/Log';
import Room from './Room';
import Device from './Device';
import {CONNECTED, NOT_CONNECTED} from './util/constants';
import Webcom from 'webcom/webcom';
 
let initializing = false;
 
/**
 * User informations
 * @public
 */
export default class User {
	/**
	 * Create a user
	 * @param {Webcom/api.DataSnapshot|object} snapData The data snapshot
	 * @access protected
	 */
	constructor(snapData) {
		const values = Object.assign({}, snapData.val());
		/**
		 * User's unique id
		 * @type {string}
		 */
		this.uid = snapData.name();
		/**
		 * User's display name
		 * @type {string}
		 */
		this.name = values.name;
		/**
		 * User's status
		 * @type {string}
		 */
		this.status = values.status;
		/**
		 * User's last know connection ts
		 * @type {number}
		 */
		this.lastSeen = values.lastSeen;
		/**
		 * Indicates if the user is an anonymous user
		 * @type {boolean}
		 */
		this.anonymous = /^anonymous/.test(this.uid);
		// TODO #Feat: Add 'extra' property for unrestricted additional information ?
	}
 
	/**
	 * Invite a user directly. This will create a new Room, log you in it & invite the user.
	 * @param {string} [message] a message to add to the invite
	 * @return {Promise<{room: Room, invite: Invite}, Error>}
	 */
	invite(message) {
		if(!cache.user) {
			return Promise.reject(new Error('Only an authenticated user can invite another User.'));
		}
		return Room.create(`${cache.user.uid}-${this.uid}`)
			.then(room => {
				return room.invite([this], null, message);
			})
			.then(data => {
				return {room: data.room, invite: data.invites[0]};
			})
			.catch(Log.r('User~invite'));
	}
 
	/**
	 * List Users's devices. Only for current user.
	 * @access protected
	 * @return {Promise<Device[], Error>}
	 */
	devices() {
		return DataSync.list(`_/devices/${this.uid}`, Device);
	}
 
	/**
	 * Init the current user
	 * @access protected
	 * @param {string} uid The user's uid
	 * @param {string} [name] The user's display name
	 * @returns {Promise<User, Error>}
	 */
	static init (uid, name) {
		if(!initializing) {
			initializing = true;
			const d = {status: CONNECTED, lastSeen: DataSync.ts()};
			if(name) {
				Object.assign(d, {name});
			}
			let deviceId = Webcom.INTERNAL.PersistentStorage.get(uid);
			return DataSync.update(`users/${uid}`, d)
				// Register current device
				.then(() => {
					const deviceMetadata = {
						status: CONNECTED,
						sdk: {
							reach: SDK_VERSION,
							webcom: Webcom.SDK_VERSION
						},
						userAgent: navigator.userAgent
					};
					if(deviceId) {
						return DataSync.update(`_/devices/${uid}/${deviceId}`, deviceMetadata);
					}
					return DataSync.push(`_/devices/${uid}`, deviceMetadata);
				})
				// Save device
				.then(deviceRef => {
					if (!deviceId) {
						deviceId = deviceRef.name();
						Webcom.INTERNAL.PersistentStorage.set(uid, deviceId);
					}
					cache.device = deviceId;
				})
				// Add onDisconnect actions
				.then(() => {
					// Disconnect device
					DataSync.onDisconnect(`_/devices/${uid}/${deviceId}/status`).set(NOT_CONNECTED);
					// Update user status
					DataSync.onDisconnect(`users/${uid}`).update({
						status: NOT_CONNECTED,
						lastSeen: DataSync.ts()
					});
				})
				// Get user
				.then(() => User.get(uid))
				.then(user => {
					initializing = false;
					return user;
				})
				.catch(e => {
					Log.e(e);
					initializing = false;
					return Promise.reject(e);
				});
		}
		return User.get(uid);
	}
 
	/**
	 * Disconnect the current user
	 * @access protected
	 * @param {User} user The current user
	 * @returns {Promise}
	 */
	static disconnect(user) {
		// Cancel onDisconnect
		DataSync.onDisconnect(`_/devices/${user.uid}/${cache.device}/status`).cancel();
		DataSync.onDisconnect(`users/${user.uid}`).cancel();
 
		if(user.anonymous) {
			return DataSync.remove(`_/devices/${user.uid}`)
				.then(() => DataSync.get(`_/invites/${user.uid}`))
				.then(invites => {
					const inviteIds = [];
					invites.forEach(invite => {
						inviteIds.push(invite.name());
					});
					return Promise.all(inviteIds.map(inviteId => DataSync.remove(`_/invites/${user.uid}/${inviteId}`)));
				})
				// TODO refactor data model for invites so we can delete _/invites/${user.uid}
				// .then(() => DataSync.remove(`_/invites/${user.uid}`))
				.then(() => DataSync.remove(`users/${user.uid}`))
				.then(() => {
					Webcom.INTERNAL.PersistentStorage.remove(user.uid);
				})
				.catch(Log.r('User#anonymous_disconnect'));
		}
		return DataSync.set(`_/devices/${user.uid}/${cache.device}/status`, NOT_CONNECTED)
			.then(() => DataSync.get(`_/devices/${user.uid}`))
			.then(devices => {
				// Only change user's status if no other device connected
				const hasConnectedDevices = devices.forEach(device => {
					return (new RegExp(`^${CONNECTED}$`)).test(device.val().status);
				});
				if(!hasConnectedDevices) {
					return DataSync.update(`users/${user.uid}`, {status: NOT_CONNECTED});
				}
				return true;
			})
			.catch(Log.r('User#disconnect'));
	}
 
	/**
	 * Get a user by its uid
	 * @access private
	 * @param {string} uid The user's uid
	 * @returns {Promise<User, Error>}
	 */
	static get(uid) {
		return DataSync.get(`users/${uid}`)
		.then(snapData => snapData ? new User(snapData) : null)
		.catch(Log.r('User#get'));
	}
}