all files / src/ Reach.js

43.42% Statements 33/76
23.08% Branches 9/39
51.22% Functions 21/41
44% Lines 33/75
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 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338                                                                  12×   12×         12×                                                                                                               25×               10×                                                                                                                                                                                                                                                                                                                                                                                                                          
import {browser} from './definitions/Browser';
import StreamTypes from './definitions/StreamTypes';
import * as Events from './definitions/Events';
import {audio, video} from './definitions/Codec';
import User from './core/User';
import Room from './core/Room';
import Invite from './core/Invite';
import * as DataSync from './core/util/DataSync';
import cache from './core/util/cache';
import * as Log from './core/util/Log';
import Media from './core/util/Media';
import Webcom from 'webcom/webcom';
 
/**
 * Entry point for Reach SDK
 * @public
 */
export default class Reach {
	/**
	 * Create Reach's data structure where the url points to (might not be the root of your namespace)
	 * @public
	 * @param {string|Webcom} url The url of your namespace or an existing Webcom reference.
	 * @param {Config} [cfg] Reach configuration. You can pass constraints here
	 * @example <caption>Init with the default configuration</caption>
	 * var myReach = new Reach('https://io.datasync.orange.com/base/<my_namespace>');
	 * @example <caption>Init and set constraints for SD video and logLevel to 'info'</caption>
	 * var myReach = new Reach('https://io.datasync.orange.com/base/<my_namespace>', {
	 *  constraints: Reach.media.constraints('SD'),
	 *  logLevel: 'INFO'
	 * });
	 */
	constructor(url, cfg = null) {
		// Set shared reference
		cache.base = url;
		// Set shared configuration
		cache.config = cfg;
		/**
		 * List of declared callbacks
		 * @type {Object}
		 */
		this._callbacks = {};
	}
 
	/**
	 * Get versions of SDK and DataModel.The Schema version can be used to determine compatibility with the Android & iOS SDK.
	 * @return {{sdk: string, schema: string}}
	 */
	static get version() {
		return {sdk: SDK_VERSION, schema: SCHEMA_VERSION};
	}
 
	/**
	 * The supported stream types
	 * @returns {StreamTypes}
	 */
	static get types() {
		return StreamTypes;
	}
 
	/**
	 * The supported events
	 * @return {{room: Events/Room, reach: Events/Reach, stream: Events/Stream}}
	 */
	static get events() {
		return {room: Events.room, reach: Events.reach, stream: Events.stream, invite: Events.invite};
	}
 
	/**
	 * The browser's details
	 * @return {Browser}
	 */
	static get browser() {
		return browser;
	}
 
	/**
	 * Media utility functions
	 * @return {Media}
	 */
	static get media() {
		return Media;
	}
 
	/**
	 * The codec presets to use when setting {@link Config#preferredAudioCodec} or {@link Config#preferredVideoCodec}
	 * @return {{audio: Codec/audio, video: Codec/video}}
	 */
	static get codecs() {
		return {audio, video};
	}
	/**
	 * DataSync reference
	 * @type {Webcom}
	 */
	get base() {
		return cache.base;
	}
 
	/**
	 * The configuration
	 * @type {Config}
	 */
	get config() {
		return cache.config;
	}
 
	/**
	 * The connected User
	 * @type {User}
	 */
	get current() {
		return cache.user;
	}
 
	/**
	 * Register & Sign-in as a new user
	 * @param {string} email The email of the user
	 * @param {string} password The password of the user
	 * @param {string} [name] The display name of the user (defaults to email)
	 * @param {boolean} [rememberMe=false] keep user connected ?
	 * @returns {Promise<User>}
	 */
	register(email, password, name, rememberMe) {
		return cache.base.createUser(email, password)
			.then(auth => {
				if(auth) {
					return this.login(email, password, name || email, rememberMe);
				}
			})
			.catch(Log.r('Reach~register'));
	}
 
	/**
	 * Sign-in an existing user
	 * @param {string} email The email of the user
	 * @param {string} password The password of the user
 	 * @param {string} [name] The name of the user. Defaults to the value in base.
	 * @param {boolean} [rememberMe=false] keep user connected ?
	 * @returns {Promise<User>}
	 */
	login(email, password, name, rememberMe = false) {
		// Force logout to bypass Webcom bug
		let p = Promise.resolve();
		Iif(this.current && this.current.email !== email) {
			p = this.logout();
		}
		return p
			.then(() => cache.base.authWithPassword({email, password, rememberMe}))
			.then(auth => User.init(auth.uid, name))
			.then(u => {
				cache.user = u;
				return u;
			})
			.catch(Log.r('Reach~login'));
	}
 
	/**
	 * Resume previous session
	 * @returns {Promise<User>}
	 */
	resume() {
		return new Promise((resolve, reject) => {
			// Resume session
			if(Webcom.INTERNAL.PersistentStorage.get('session')){
				cache.base.resume((error, auth) => {
					if(auth && !this.current) {
						User.init(auth.uid).then(u => {
							cache.user = u;
							resolve(u);
						}, reject);
					}
				});
			} else {
				reject(new Error('No session to resume'));
			}
		});
	}
 
	/**
	 * Sign-in an anonymous user
	 * @param {string} name The display name of the user
	 * @returns {Promise<User>}
	 */
	anonymous(name) {
		// Force logout to bypass Webcom bug
		let p = Promise.resolve();
		Iif(this.current && (!this.current.anonymous || this.current.name !== name)) {
			p = this.logout();
		}
		return p
			.then(() => cache.base.authAnonymously())
			.then(auth => User.init(auth.uid, name))
			.then(u => {
				cache.user = u;
				return u;
			})
			.catch(Log.r('Reach~anonymous'));
	}
 
	/**
	 * Logout current user
	 * @returns {Promise}
	 */
	logout() {
		return new Promise((resolve, reject) => {
			let p = Promise.resolve();
			Iif(this.current != null) {
				p = User.disconnect(this.current);
			}
			p.then(() => {
				Object.keys(this._callbacks).forEach(
					event => DataSync.off(Events.reach.toPath(event)(cache.user), event)
				);
				cache.base.logout(() => {
					cache.user = null;
					resolve();
				});
			})
			.catch(e => {
				Log.e(e);
				reject(e);
			});
		});
	}
 
	/**
	 * Get the list of registered users
	 * @experimental Since 'search' and 'paging' features are not yet implemented in DataSync, this call can lead to a lot data being exchanged over the WebSocket.
	 * Avoid it if your users base is pretty large.
	 * @param {boolean} [include=false] Include current user in user's list
	 * @return {Promise<User[], Error>}
	 */
	users(include) {
		return DataSync.list('users', User)
			.then(users => {
				return !include && users && this.current ? users.filter(user => user.uid !== this.current.uid) : users;
			})
			.catch(Log.r('Reach~users'));
	}
 
	/**
	 * Get the list of rooms
	 * @return {Promise<Room[], Error>}
	 */
	rooms() {
		return DataSync.list('rooms', Room)
			.catch(Log.r('Reach~rooms'));
	}
 
	/**
	 * Get the list of invites
	 * @return {Promise<Invite[], Error>}
	 */
	invites() {
		if(!this.current) {
			return Promise.reject(new Error('Cannot list invites without a User being logged in.'));
		}
		return DataSync.list(`_/invites/${this.current.uid}`, Invite)
			.catch(Log.r('Reach~invites'));
	}
 
	/**
	 * Register a callback for a specific event
	 * @param {string} event The event name ({@link Events/Reach}). Can be:
	 * - USER_ADDED
	 * - USER_CHANGED
	 * - USER_REMOVED
	 * - ROOM_ADDED
	 * - ROOM_CHANGED
	 * - ROOM_REMOVED
	 * - INVITE_ADDED
	 * - INVITE_CHANGED
	 * @param {function} callback The callback for the event, the arguments depends on the type of event:
	 * - USER_*: callback({@link User} u)
	 * - ROOM_*: callback({@link Room} r)
	 * - INVITE_*: callback({@link Invite} i)
	 * @param {Webcom/api.Query~cancelCallback} [cancelCallback] The error callback for the event, takes an Error as only argument
	 */
	on(event, callback, cancelCallback) {
		const path = Events.reach.toPath(event)(cache.user);
		if(path) {
			const cls = Events.reach.toClass(event);
			const cb = snapData => {
				const d = cls ? new cls(snapData) : null;
				Log.i(`Reach~on(${event})`, d);
				callback(d);
			};
			DataSync.on(path, event, cb, cancelCallback);
			if(!this._callbacks[event]) {
				this._callbacks[event] = [];
			}
			this._callbacks[event].push(cb);
		}
	}
 
	/**
	 * Create a new room
	 * @param {string} [name] The room name
	 * @param {object} [extra] Extra informations
	 * @param {boolean} [publicRoom=false] Indicates public room
	 * @returns {Promise<Room>}
	 */
	createRoom(name, extra, publicRoom = false) {
		Eif(!this.current) {
			return Promise.reject(new Error('Cannot create a Room without a User being logged in.'));
		}
		return Room.create(name, extra, publicRoom);
	}
 
	/**
	 * Get a list of all opened {@link PeerConnection}s
	 * @return {*}
	 */
	get peerConnections () {
		return cache.peerConnections.stacks;
	}
 
	/**
	 * Get a {@link Room} from its `uid`
	 * @param {string} uid The room's UID
	 * @returns {Promise.<Room>}
	 */
	getRoom (uid) {
		return Room.get(uid);
	}
 
	/**
	 * Get a {@link User} from its `uid`
	 * @param {string} uid The user's UID
	 * @returns {Promise.<User>}
	 */
	getUser (uid) {
		return User.get(uid);
	}
}
 
module.exports = Reach;