all files / src/core/ Invite.js

1.56% Statements 1/64
0% Branches 0/38
0% Functions 0/24
1.61% Lines 1/62
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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import {ONGOING, ACCEPTED, REJECTED, CANCELED} from './util/constants';
import * as DataSync from './util/DataSync';
import * as Log from './util/Log';
import cache from './util/cache';
import Room from './Room';
import * as Events from '../definitions/Events';
 
/**
 * Update
 * @param {Invite} invite The invite
 * @param {string} status The new status
 * @param {string} [reason=null] The reason (a message)
 * @param {object} [_ended=null]
 * @access private
 * @returns {Promise<Invite, Error>}
 */
const update = (invite, status, reason = null, _ended = null) => {
	const values = {
		status,
		reason,
		_ended
	};
 
	if(invite.status !== ONGOING) {
		return Promise.reject(new Error('This invitation has already been answered'));
	}
	return DataSync.update(`_/invites/${invite.to}/${invite.uid}`, values)
		.then(() => {
			Object.keys(values).forEach(prop => {
				invite[prop] = values[prop];
			});
			return Room.get(invite.room);
		})
		.then(room => ({room, invite}))
		.catch(Log.r('Invite_update'));
};
 
/**
 * Invitation
 * @public
 */
export default class Invite {
 
	/**
	 * Create an invite
	 * @param {Webcom/api.DataSnapshot|object} snapData The data snapshot
	 * @access protected
	 */
	constructor(snapData) {
		let values = snapData;
		if(snapData && snapData.val && typeof snapData.val === 'function'){
			values = Object.assign({}, snapData.val(), {uid: snapData.name(), to: snapData.ref().parent().name()});
		}
		/**
		 * Invite's unique id
		 * @type string
		 */
		this.uid = values.uid;
		/**
		 * Invite's sender uid
		 * @type {string}
		 */
		this.from = values.from;
		/**
		 * Invitee's uid
		 * @type {string}
		 */
		this.to = values.to;
		/**
		 * The id of the room associated to the invite
		 * @type {string}
		 */
		this.room = values.room;
		/**
		 * The invitation status :
		 * - ONGOING - The receiver has not yet responded to the invitation
		 * - ACCEPTED - The receiver has accepted the invitation
		 * - REJECTED - The receiver has rejected the invitation
		 * - CANCELED - The sender canceled the invitation
		 * @type {string}
		 */
		this.status = values.status;
		/**
		 * Invite message. This will be either a custom message if the status is ONGOING or a reason when status is CANCELED|REJECTED.
		 * @type {string}
		 */
		this.topic = values.topic;
		/**
		 * Invite creation timestamp
		 * @type {number}
		 */
		this._created = values._created;
		/**
		 * Invite expiration timestamp
		 * @type {number}
		 */
		this._ended = values._ended;
		/**
		 * Invite events callbacks
		 * @type {{}}
		 * @private
		 */
		this._callbacks = {};
	}
 
	/**
	 * Is this invitation waiting for a reply ?
	 * @type {boolean}
	 */
	get isOnGoing() {
		return this.status === ONGOING;
	}
 
	/**
	 * Was this invitation rejected ?
	 * @type {boolean}
	 */
	get isRejected() {
		return this.status === REJECTED;
	}
 
	/**
	 * Was this invitation accepted ?
	 * @type {boolean}
	 */
	get isAccepted() {
		return this.status === ACCEPTED;
	}
 
	/**
	 * Was this invitation canceled ?
	 * @type {boolean}
	 */
	get isCanceled() {
		return this.status === CANCELED;
	}
 
	/**
	 * Cancels the invitation. Only the sender can cancel the invitation.
	 * @param {string} [reason] The reason the sender is canceling the invite
	 * @return {Promise<Invite>}
	 */
	cancel(reason) {
		return update(this, CANCELED, reason, DataSync.ts());
	}
 
	/**
	 * Rejects the invitation. Only the receiver can reject the invitation.
	 * @param {string} [reason] The reason the receiver is rejecting the invite
	 * @return {Promise<Invite>}
	 */
	reject(reason) {
		return update(this, REJECTED, reason, DataSync.ts());
	}
 
	/**
	 * Accept the invitation. Only the receiver can accept the invitation.
	 * @return {Promise<Invite>}
	 */
	accept() {
		return update(this, ACCEPTED);
	}
 
	/**
	 * Register a callback for a status update
	 * @param {string} status Can be:
	 * - ACCEPTED
	 * - REJECTED
	 * - CANCELED
	 * @param {function} callback
	 */
	on(status, callback) {
		if(Events.invite.supports(status)) {
			// Register callback
			if (!this._callbacks[status]) {
				this._callbacks[status] = [];
			}
			this._callbacks[status].push(callback);
			// Defined listener & subscribe if needed
			if (!this._listener) {
				/**
				 * Invite status update callback
				 * @type {function}
				 * @private
				 */
				this._listener = snapData => {
					const updated = snapData.val();
					if (updated !== null && updated !== this.status) {
						this.status = updated;
						(this._callbacks[updated] || []).forEach(cb => {
							cb(this);
						});
					}
				};
				DataSync.on(`_/invites/${this.to}/${this.uid}/status`, 'value', this._listener.bind(this));
			}
		}
	}
 
	/**
	 * Register a callback for all status change events
	 * @param {function} callback
	 */
	onStatusChange(callback) {
		[ACCEPTED, REJECTED, CANCELED].forEach(event => {
			this.on(event, callback);
		});
	}
 
	/**
	 * Un-register a callback for a status update
	 * @param {string} [status] Can be:
	 * - ACCEPTED
	 * - REJECTED
	 * - CANCELED
	 * - null This will un-register all callbacks
	 * @param {function} [callback]
	 */
	off(status, callback) {
		if(!status) {
			this._callbacks = {};
		} else if(this._callbacks[status]) {
			if(callback) {
				const idx = this._callbacks[status].findIndex(cb => cb === callback);
				if (idx >= 0) {
					this._callbacks.splice(idx, 1);
				}
			} else {
				this._callbacks[status] = [];
			}
		}
		if(![CANCELED, ACCEPTED, REJECTED].some(event => this._callbacks[event] && this._callbacks[event].length > 0)){
			DataSync.off(`_/invites/${this.to}/${this.uid}/status`, 'value');
		}
	}
 
	/**
	 * Un-register a callback for all status change events
	 * @param {function} [callback]
	 */
	offStatusChange(callback) {
		if(!callback) {
			this.off();
		} else {
			[ACCEPTED, REJECTED, CANCELED].forEach(event => {
				this.off(event, callback);
			});
		}
	}
 
	/**
	 * Create the invitation & add the user to the participants list
	 * @access protected
	 * @param {User} invitee The user to invite
	 * @param {Room} room The room to invite the user to
	 * @param {string} [message] A message for the invitee
	 */
	static send(invitee, room, message = null) {
		if(!cache.user) {
			return Promise.reject(new Error('Only an authenticated user can send an invite.'));
		}
 
		const inviteMetaData = {
			from: cache.user.uid,
			room: room.uid,
			status: ONGOING,
			_created: DataSync.ts(),
			topic: message
		};
 
		return DataSync.push(`_/invites/${invitee.uid}`, inviteMetaData)
			.then(inviteRef => {
				const inviteId = inviteRef.name();
				return new Invite(Object.assign({uid: inviteId, to: invitee.uid}, inviteMetaData));
			})
			.catch(Log.r('Invite#send'));
	}
}