Example #1
0
Template.permissions.onCreated(function() {
	this.roles = new ReactiveVar([]);
	this.permissionByRole = {};
	this.actions = {
		added: {},
		removed: {},
	};

	Tracker.autorun(() => {
		this.roles.set(Roles.find().fetch());
	});

	Tracker.autorun(() => {
		ChatPermissions.find().observeChanges({
			added: (id, fields) => {
				this.permissionByRole[id] = fields.roles;
			},
			changed: (id, fields) => {
				this.permissionByRole[id] = fields.roles;
			},
			removed: (id) => {
				delete this.permissionByRole[id];
			},
		});
	});
});
Example #2
0
Meteor.startup(function() {
	TimeSync.loggingEnabled = false;

	Session.setDefault('AvatarRandom', 0);

	window.lastMessageWindow = {};
	window.lastMessageWindowHistory = {};

	Tracker.autorun(function(computation) {
		if (!Meteor.userId() && !RocketChat.settings.get('Accounts_AllowAnonymousRead')) {
			return;
		}
		Meteor.subscribe('userData');
		Meteor.subscribe('activeUsers');
		computation.stop();
	});

	let status = undefined;
	Tracker.autorun(function() {
		if (!Meteor.userId()) {
			return;
		}
		const user = RocketChat.models.Users.findOne(Meteor.userId(), {
			fields: {
				status: 1,
				'settings.preferences.idleTimeLimit': 1,
				'settings.preferences.enableAutoAway': 1,
			},
		});

		if (!user) {
			return;
		}

		if (RocketChat.getUserPreference(user, 'enableAutoAway')) {
			const idleTimeLimit = RocketChat.getUserPreference(user, 'idleTimeLimit') || 300;
			UserPresence.awayTime = idleTimeLimit * 1000;
		} else {
			delete UserPresence.awayTime;
			UserPresence.stopTimer();
		}

		UserPresence.start();

		if (user.status !== status) {
			status = user.status;
			fireGlobalEvent('status-changed', status);
		}
	});
});
Example #3
0
Meteor.startup(function() {
	Tracker.autorun(() => {
		if (!settings.get('Threads_enabled')) {
			return MessageAction.removeButton('reply-in-thread');
		}
		MessageAction.addButton({
			id: 'reply-in-thread',
			icon: 'thread',
			label: 'Reply_in_thread',
			context: ['message', 'message-mobile', 'threads'],
			action() {
				const { msg: message } = messageArgs(this);
				const { input } = chatMessages[message.rid];
				const $input = $(input);

				const messages = addMessageToList($input.data('reply') || [], message, input);

				$(input)
					.focus()
					.data('mention-user', true)
					.data('reply', messages)
					.trigger('dataChange');
			},
			condition(message) {
				return Boolean(Subscriptions.findOne({ rid: message.rid }));
			},
			order: 1,
			group: 'menu',
		});
	});
});
Meteor.startup(function() {
	Tracker.autorun(function() {

		if (!RocketChat.settings.get('Livechat_continuous_sound_notification_new_livechat_room')) {
			stop(audio);
			return;
		}

		const subs = RocketChat.models.Subscriptions.find({ t: 'l', ls : { $exists: 0 }, open: true }).count();
		if (subs === 0) {
			stop(audio);
			return;
		}

		const user = RocketChat.models.Users.findOne(Meteor.userId(), {
			fields: {
				'settings.preferences.newRoomNotification': 1,
			},
		});

		const newRoomNotification = RocketChat.getUserPreference(user, 'newRoomNotification');

		[audio] = $(`#${ newRoomNotification }`);
		play(audio);

	});
});
Example #5
0
Meteor.startup(function() {
	Tracker.autorun(function() {
		if (Meteor.userId()) {
			Meteor.call('getUserRoles', (error, results) => {
				if (error) {
					return handleError(error);
				}

				for (const record of results) {
					UserRoles.upsert({ _id: record._id }, record);
				}
			});

			RocketChat.Notifications.onLogged('roles-change', function(role) {
				if (role.type === 'added') {
					if (role.scope) {
						RoomRoles.upsert({ rid: role.scope, 'u._id': role.u._id }, { $setOnInsert: { u: role.u }, $addToSet: { roles: role._id } });
					} else {
						UserRoles.upsert({ _id: role.u._id }, { $addToSet: { roles: role._id }, $set: { username: role.u.username } });
						ChatMessage.update({ 'u._id': role.u._id }, { $addToSet: { roles: role._id } }, { multi: true });
					}
				} else if (role.type === 'removed') {
					if (role.scope) {
						RoomRoles.update({ rid: role.scope, 'u._id': role.u._id }, { $pull: { roles: role._id } });
					} else {
						UserRoles.update({ _id: role.u._id }, { $pull: { roles: role._id } });
						ChatMessage.update({ 'u._id': role.u._id }, { $pull: { roles: role._id } }, { multi: true });
					}
				} else if (role.type === 'changed') {
					ChatMessage.update({ roles: role._id }, { $inc: { rerender: 1 } }, { multi: true });
				}
			});
		}
	});
});
Example #6
0
Meteor.startup(function() {
	Tracker.autorun(() => {
		const user = Meteor.user();

		if (user && Object.keys(user.banners || {}).length > 0) {
			const firstBanner = Object.values(user.banners).filter((b) => b.read !== true).sort((a, b) => b.priority - a.priority)[0];

			if (!firstBanner) {
				return;
			}

			firstBanner.textArguments = firstBanner.textArguments || [];

			alerts.open({
				title: TAPi18n.__(firstBanner.title),
				text: TAPi18n.__(firstBanner.text, ...firstBanner.textArguments),
				modifiers: firstBanner.modifiers,
				action() {
					if (firstBanner.link) {
						window.open(firstBanner.link, '_system');
					}
				},
				onClose() {
					Meteor.call('banner/dismiss', {
						id: firstBanner.id,
					});
				},
			});
		}
	});
});
Example #7
0
export default (reaction) => {
  let mobxDisposer = null;
  let computation = null;
  let hasBeenStarted = false;
  return {
    start() {
      let isFirstRun = true;
      computation = Tracker.autorun(() => {
        if (mobxDisposer) {
          mobxDisposer();
          isFirstRun = true;
        }
        mobxDisposer = mobxAutorun(() => {
          if (isFirstRun) {
            reaction();
          } else {
            computation.invalidate();
          }
          isFirstRun = false;
        });
      });
      hasBeenStarted = true;
    },
    stop() {
      if (hasBeenStarted) {
        computation.stop();
        mobxDisposer();
      }
    }
  };
};
Example #8
0
Template.vocTable.onCreated(function(){
    // reactively get confounders w/ this organ site-category
    let objects = new ReactiveVar([]),
        vocs = new ReactiveVar([]);
    Tracker.autorun(()=>{

        let obj = NtpEpiConfounder
            .find({organSiteCategory: this.data.organSiteCategory})
            .fetch();
        _.each(obj, (d)=>d.getDescription());
        objects.set(obj);

        let vocs_ = _.chain(obj)
            .map((d)=> _.pluck(d.variablesOfConcern, 'vocName'))
            .flatten()
            .uniq()
            .sort()
            .value();
        vocs.set(vocs_);
    });
    _.extend(this, {
        objects,
        vocs,
    });
});
Example #9
0
Meteor.startup(() => {
  const PORT = window.socketPort || 3003;
  let socket = require('socket.io-client')(`http://localhost:${PORT}`);

  socket.on('connect', function() {
    console.log('Client connected');
  });
  socket.on('disconnect', function() {
    console.log('Client disconnected');
  });

  // Get counter updates from server
  let serverCounter = counter.get();
  socket.on('counter', function(value) {
    console.log(`counter changed on server: ${value}`);
    if (serverCounter !== value) {
      serverCounter = value;
      counter.set(value);
    }
  });

  // Update counter from client to server
  Tracker.autorun(() => {
    const c = counter.get();
    if (c !== serverCounter) {
      console.log(c);
      socket.emit('counter', c);
    }
  });
});
Router.go = (path, params, query) => {
  let actualPath;

  const routerGo = () => {
    if (typeof path === "string" && path.startsWith("/")) {
      actualPath = path;
    } else {
      actualPath = Router.pathFor(path, {
        hash: {
          ...params,
          query
        }
      });
    }

    if (window) {
      history.push(actualPath);
    }
  };

  // if Router is in a non ready/initialized state yet, wait until it is
  if (!Router.ready()) {
    Tracker.autorun((routerReadyWaitFor) => {
      if (Router.ready()) {
        routerReadyWaitFor.stop();
        routerGo();
      }
    });

    return;
  }

  routerGo();
};
Example #11
0
Template.main.onRendered(function() {
	$('#initial-page-loading').remove();
	window.addEventListener('focus', function() {
		return Meteor.setTimeout(function() {
			if (!$(':focus').is('INPUT,TEXTAREA')) {
				return $('.input-message').focus();
			}
		}, 100);
	});
	return Tracker.autorun(function() {
		const userId = Meteor.userId();
		const Show_Setup_Wizard = settings.get('Show_Setup_Wizard');

		if ((!userId && Show_Setup_Wizard === 'pending') || (userId && hasRole(userId, 'admin') && Show_Setup_Wizard === 'in_progress')) {
			FlowRouter.go('setup-wizard');
		}
		if (getUserPreference(userId, 'hideUsernames')) {
			$(document.body).on('mouseleave', 'button.thumb', function() {
				return tooltip.hide();
			});
			return $(document.body).on('mouseenter', 'button.thumb', function(e) {
				const avatarElem = $(e.currentTarget);
				const username = avatarElem.attr('data-username');
				if (username) {
					e.stopPropagation();
					return tooltip.showElement($('<span>').text(username), avatarElem);
				}
			});
		} else {
			$(document.body).off('mouseenter', 'button.thumb');
			return $(document.body).off('mouseleave', 'button.thumb');
		}
	});
});
Example #12
0
    Template.incidents.onCreated( function() {
        this.pagination = new Meteor.Pagination( incidents, {
            fields: {
                _id: 1,
                summary: 1,
                description: 1,
                phase: 1,
                dateOpened: 1,
                dateClosed: 1,
                creator: 1
            },
            sort: {
                dateOpened: -1
            },
            perPage: prefs().pageSize,
        } );

        Template.instance().searchQuery = new ReactiveVar();

        Tracker.autorun( () => {
            const filter_Text = this.searchQuery.get();

            if ( filter_Text && filter_Text.length > 0 ) {
                this.pagination.filters( { $text: { $search: filter_Text } } );
            } else {
                this.pagination.filters( {} );
            }
        } );
    } );
    return new Promise((resolve, reject) => {
      if (this._image.files.length === 0) {
        resolve(this.state.lesson);
      }

      const image = this._image.files[0];

      const ImageUploader = new Slingshot.Upload('imageUploads');

      ImageUploader.send(image, (error, url) => {
        if (error) {
          alert(error);
          reject(error);
        } else {
          const filename = path.basename(url);
          const lesson = this.state.lesson.set('image', filename);
          this.setState({lesson});
          resolve(lesson);
        }
      });

      Tracker.autorun(c => {
        const progress = ImageUploader.progress() || 0;

        this.setState({progress});

        if (progress === 1) {
          c.stop();
        }
      });
    });
Example #14
0
Meteor.startup(function () {
  // warn on insecure exporting of PackageRegistry settings
  if (typeof PackageRegistry !== "undefined" && PackageRegistry !== null) {
    let msg = "PackageRegistry: Insecure export to client.";
    Logger.warn(msg, PackageRegistry);
  }
  // init the core
  Reaction.init();
  // initialize anonymous guest users
  return Tracker.autorun(function () {
    const userId = Meteor.userId();
    // TODO: maybe `visibilityState` will be better here
    let isHidden;
    let loggingIn;
    let sessionId;
    Tracker.nonreactive(function () {
      isHidden = document[hidden];
      loggingIn = Accounts.loggingIn();
      sessionId = amplify.store("Reaction.session");
    });
    if (!userId) {
      if (!isHidden && !loggingIn || typeof sessionId !== "string") {
        Accounts.loginWithAnonymous();
      }
    }
  });
});
 componentDidMount() {
     this.tracker = Tracker.autorun(() => {
         this.setState({
             showVisible: Session.get('showVisible')
         })
     });
 }
Example #16
0
Meteor.startup(function () {
  Tracker.autorun(function () {
    // initialize client routing

    if (Reaction.Subscriptions.Packages.ready() && Reaction.Subscriptions.Shops.ready()) {
      //  initBrowserRouter calls Router.initPackageRoutes which calls shopSub.ready which is reactive,
      //  So we have to call initBrowserRouter in a non reactive context.
      //  Otherwise initBrowserRouter is called twice each time a Reaction.Subscriptions.Packages.ready() and
      //  Reaction.Subscriptions.Shops.ready() are true

      Tracker.nonreactive(()=> {
        initBrowserRouter();
      });
    }
  });

  //
  // we need to sometimes force
  // router reload on login to get
  // the entire layout to rerender
  // we only do this when the routes table
  // has already been generated (existing user)
  //
  Accounts.onLogin(() => {
    if (Meteor.loggingIn() === false && Router._routes.length > 0) {
      initBrowserRouter();
    }
  });
});
Example #17
0
	constructor() {
		this._online = new ReactiveVar(null);

		this._customColor = new ReactiveVar();
		this._onlineColor = new ReactiveVar('#C1272D');
		this._offlineColor = new ReactiveVar('#666666');

		this._customFontColor = new ReactiveVar();
		this._onlineFontColor = new ReactiveVar('#FFFFFF');
		this._offlineFontColor = new ReactiveVar('#FFFFFF');

		this._title = new ReactiveVar('Rocket.Chat');
		this._registrationForm = new ReactiveVar(true);
		this._showSwitchDepartmentForm = new ReactiveVar(false);
		this._allowSwitchingDepartments = new ReactiveVar(false);
		this._offlineMessage = new ReactiveVar('');
		this._offlineUnavailableMessage = new ReactiveVar('');
		this._displayOfflineForm = new ReactiveVar(true);
		this._offlineSuccessMessage = new ReactiveVar(TAPi18n.__('Thanks_We_ll_get_back_to_you_soon'));
		this._videoCall = new ReactiveVar(false);
		this._fileUpload = new ReactiveVar(false);
		this._transcriptMessage = new ReactiveVar('');
		this._conversationFinishedMessage = new ReactiveVar('');
		this._nameFieldRegistrationForm = new ReactiveVar(false);
		this._emailFieldRegistrationForm = new ReactiveVar(false);
		this._connecting = new ReactiveVar(false);
		this._room = new ReactiveVar(null);
		this._department = new ReactiveVar(null);
		this._widgetOpened = new ReactiveVar(false);
		this._ready = new ReactiveVar(false);
		this._agent = new ReactiveVar();

		this.stream = new Meteor.Streamer('livechat-room');

		this._guestName = new ReactiveVar();
		this._guestEmail = new ReactiveVar();

		Tracker.autorun(() => {
			if (this._room.get() && visitor.getId()) {
				RoomHistoryManager.getMoreIfIsEmpty(this._room.get());
				visitor.subscribeToRoom(this._room.get());
				visitor.setRoom(this._room.get());

				Meteor.call('livechat:getAgentData', { roomId: this._room.get(), token: visitor.getToken() }, (error, result) => {
					if (!error) {
						this._agent.set(result);
					}
				});
				this.stream.on(this._room.get(), { token: visitor.getToken() }, (eventData) => {
					if (!eventData || !eventData.type) {
						return;
					}

					if (eventData.type === 'agentData') {
						this._agent.set(eventData.data);
					}
				});
			}
		});
	}
Example #18
0
Template.directory.onRendered(function() {
	Tracker.autorun(() => {
		const searchConfig = {
			text: this.searchText.get(),
			type: this.searchType.get(),
			sortBy: this.searchSortBy.get(),
			sortDirection: this.sortDirection.get(),
			limit: this.limit.get(),
			page: this.page.get(),
		};
		if (this.end.get() || this.loading) {
			return;
		}
		this.loading = true;
		this.isLoading.set(true);
		directorySearch(searchConfig, (result) => {
			this.loading = false;
			this.isLoading.set(false);
			this.end.set(!result);

			if (!Array.isArray(result)) {
				result = [];
			}

			if (this.page.get() > 0) {
				return this.results.set([...this.results.get(), ...result]);
			}
			return this.results.set(result);
		});
	});
});
Example #19
0
    return new Promise((resolve, reject) => {
      let trackerControl = null;

      const timeout = setTimeout(() => {
        clearTimeout(timeout);
        trackerControl.stop();
        this.callback({
          status: this.baseCallStates.failed,
          error: this.baseErrorCodes.REQUEST_TIMEOUT,
          bridgeError: 'Timeout on call transfer',
        });
        reject(this.baseErrorCodes.REQUEST_TIMEOUT);
      }, CALL_TRANSFER_TIMEOUT);

      // This is is the call transfer code ask @chadpilkey
      this.currentSession.dtmf(1);

      Tracker.autorun((c) => {
        trackerControl = c;
        const selector = { meetingId: this.userData.meetingId, intId: this.userData.userId };
        const query = VoiceUsers.find(selector);

        query.observeChanges({
          changed: (id, fields) => {
            if (fields.joined) {
              clearTimeout(timeout);
              onTransferSuccess();
              c.stop();
              resolve();
            }
          },
        });
      });
    });
function subscribeAll (subscriptions) {
  if (subscriptions.length === 0) {
    return new ReactiveVar(true);
  }

  const ready = new ReactiveVar(false);

  Tracker.autorun(() => {
    if (Meteor.user()) {
      if (ready.get()) {
        return;
      }

      Tracker.nonreactive(() => {
        subscribeAllWithCallback(subscriptions, () => {
          ready.set(true);
        });
      })
    } else {
      ready.set(false);
    }
  });

  return ready;
}
Example #21
0
 track() {
   this._tracker = Tracker.autorun(() => {
     Groups.find(this._query, {sort: {ordering: 1}}).observe({
       added: (doc) => {
         this.newItemGroup(doc);
       },
       removed: (doc) => {
         this.removeItemGroup(doc._id);
       }
     });
     Groups.find(this._query).observeChanges({
       changed: (id, fields) => {
         this.changedItemGroup(id, fields);
       }
     });
     Items.find(this._query, {sort: {ordering: 1}}).observe({
       added: (doc) => {
         this.newItem(doc);
       },
       removed: (doc) => {
         console.log(doc)
         this.removeItem(doc._id);
       }
     });
     Items.find(this._query).observeChanges({
       changed: (id, fields) => {
         this.changedItem(id, fields);
       }
     });
   });
   return this;
 }
Example #22
0
Meteor.startup(() => {
	Tracker.autorun(function() {
		const user = Users.findOne(Meteor.userId(), {
			fields: {
				'settings.preferences.newRoomNotification': 1,
				'settings.preferences.notificationsSoundVolume': 1,
			},
		});
		const newRoomNotification = getUserPreference(user, 'newRoomNotification');
		const audioVolume = getUserPreference(user, 'notificationsSoundVolume');

		if ((Session.get('newRoomSound') || []).length > 0) {
			Meteor.defer(function() {
				if (newRoomNotification !== 'none') {
					const [audio] = $(`audio#${ newRoomNotification }`);
					if (audio && audio.play) {
						audio.volume = Number((audioVolume / 100).toPrecision(2));
						return audio.play();
					}
				}
			});
		} else {
			const [room] = $(`audio#${ newRoomNotification }`);
			if (!room) {
				return;
			}
			if (room.pause) {
				room.pause();
				return room.currentTime = 0;
			}
		}
	});
});
Example #23
0
  const loadFetchDataAndToggle = () => {
    dispatch(setOrgsLoading(true));

    const onReady = () => {
      const query = {
        _id: { $ne: organizationId },
        ...createOrgQueryWhereUserIsOwner(userId),
      };
      const options = { sort: { serialNumber: 1 } };
      const organizations = Organizations.find(query, options).fetch();
      const actions = [
        setOwnOrgs(organizations),
        setOrgsLoaded(true),
        setOrgsLoading(false),
        setOrgsCollapsed(false),
      ];

      dispatch(batchActions(actions));
    };
    const sub = OrgSubs.subscribe('dataImportUserOwnOrganizations');

    Tracker.autorun((comp) => {
      if (sub.ready()) {
        onReady();
        comp.stop();
      }
    });
  };
Example #24
0
Meteor.startup(function() {
	Tracker.autorun(function() {
		let unreadCount = 0;
		let unreadAlert = false;

		const subscriptions = ChatSubscription.find({ open: true, hideUnreadStatus: { $ne: true } }, { fields: { unread: 1, alert: 1, rid: 1, t: 1, name: 1, ls: 1, unreadAlert: 1 } });

		let openedRoomId = undefined;
		Tracker.nonreactive(function() {
			if (['channel', 'group', 'direct'].includes(FlowRouter.getRouteName())) {
				openedRoomId = Session.get('openedRoom');
			}
		});

		for (const subscription of subscriptions.fetch()) {
			fireGlobalEvent('unread-changed-by-subscription', subscription);

			if (subscription.alert || subscription.unread > 0) {
				// This logic is duplicated in /client/notifications/notification.coffee.
				const hasFocus = readMessage.isEnable();
				const subscriptionIsTheOpenedRoom = openedRoomId === subscription.rid;
				if (hasFocus && subscriptionIsTheOpenedRoom) {
					// The user has probably read all messages in this room.
					// TODO: readNow() should return whether it has actually marked the room as read.
					Meteor.setTimeout(function() {
						readMessage.readNow();
					}, 500);
				}

				// Increment the total unread count.
				unreadCount += subscription.unread;
				if (subscription.alert === true && subscription.unreadAlert !== 'nothing') {
					const userUnreadAlert = RocketChat.getUserPreference(Meteor.userId(), 'unreadAlert');
					if (subscription.unreadAlert === 'all' || userUnreadAlert !== false) {
						unreadAlert = '•';
					}
				}
			}

			if (RoomManager.openedRooms[subscription.t + subscription.name]) {
				readMessage.refreshUnreadMark(subscription.rid);
			}
		}

		menu.updateUnreadBars();

		if (unreadCount > 0) {
			if (unreadCount > 999) {
				Session.set('unread', '999+');
			} else {
				Session.set('unread', unreadCount);
			}
		} else if (unreadAlert !== false) {
			Session.set('unread', unreadAlert);
		} else {
			Session.set('unread', '');
		}
	});
});
Example #25
0
FlowRouter.subscriptions = function() {
	Tracker.autorun(() => {
		if (Meteor.userId()) {
			this.register('userData', Meteor.subscribe('userData'));
			this.register('activeUsers', Meteor.subscribe('activeUsers'));
		}
	});
};
Example #26
0
 return dispatch => {
   Tracker.autorun(() => {
     dispatch({
       type: 'FETCH_TAGS',
       tags: fromJS(Tags.find().fetch()),
     });
   });
 };
Example #27
0
	Meteor.startup(function() {
		Tracker.autorun(function() {
			if (settings.get('API_Drupal_URL')) {
				config.serverURL = settings.get('API_Drupal_URL');
				Drupal.configure(config);
			}
		});
	});
Example #28
0
	Meteor.startup(function() {
		Tracker.autorun(function() {
			if (RocketChat.settings.get('API_GitHub_Enterprise_URL')) {
				config.serverURL = RocketChat.settings.get('API_GitHub_Enterprise_URL');
				GitHubEnterprise.configure(config);
			}
		});
	});
Example #29
0
Meteor.startup(() => {
  if (Package['accounts-base']) { // eslint-disable-line no-undef
    Tracker.autorun(trackLogins);
  }
  initSession();
  initTrackAlive();
  initFlowRouter();
});
Example #30
0
	Meteor.startup(function() {
		Tracker.autorun(function() {
			if (RocketChat.settings.get('API_Tokenpass_URL')) {
				config.serverURL = RocketChat.settings.get('API_Tokenpass_URL');
				Tokenpass.configure(config);
			}
		});
	});