Ejemplo n.º 1
0
	Meteor.call('spotlight', currentFilter, usernamesFromClient, type, (err, results) => {
		if (currentFilter !== filterText) {
			return;
		}

		isLoading.set(false);

		if (err) {
			console.log(err);
			return false;
		}

		const resultsFromServer = [];
		const usersLength = results.users.length;
		const roomsLength = results.rooms.length;

		if (usersLength) {
			for (let i = 0; i < usersLength; i++) {
				resultsFromServer.push({
					_id: results.users[i]._id,
					t: 'd',
					name: results.users[i].username,
					fname: results.users[i].name,
				});
			}
		}

		if (roomsLength) {
			for (let i = 0; i < roomsLength; i++) {
				const alreadyOnClient = resultsFromClient.find((item) => item._id === results.rooms[i]._id);
				if (alreadyOnClient) {
					continue;
				}

				resultsFromServer.push({
					_id: results.rooms[i]._id,
					t: results.rooms[i].t,
					name: results.rooms[i].name,
					lastMessage: results.rooms[i].lastMessage,
				});
			}
		}

		if (resultsFromServer.length) {
			cb(resultsFromClient.concat(resultsFromServer));
		}
	});
Ejemplo n.º 2
0
	record() {
		this.chunks = [];
		if (this.stream == null) {
			return;
		}
		this.mediaRecorder = new MediaRecorder(this.stream);
		this.mediaRecorder.stream = this.stream;
		this.mediaRecorder.mimeType = 'video/webm';
		this.mediaRecorder.ondataavailable = (blobev) => {
			this.chunks.push(blobev.data);
			if (!this.recordingAvailable.get()) {
				return this.recordingAvailable.set(true);
			}
		};
		this.mediaRecorder.start();
		return this.recording.set(true);
	}
Ejemplo n.º 3
0
	setVideoEnabled(enabled = true) {
		if (this.localStream != null) {
			if (enabled === true && this.media.video !== true) {
				delete this.localStream;
				this.media.video = true;
				this.getLocalUserMedia(() => {
					this.stopAllPeerConnections();
					this.joinCall();
				});
			} else {
				this.localStream.getVideoTracks().forEach(function(video) {
					video.enabled = enabled;
				});
				this.videoEnabled.set(enabled);
			}
		}
	}
Ejemplo n.º 4
0
	Tracker.autorun(() => {
		const isMapViewEnabled = settings.get('MapView_Enabled') === true;
		const isGeolocationWatchSupported = navigator.geolocation && navigator.geolocation.watchPosition;
		const googleMapsApiKey = settings.get('MapView_GMapsAPIKey');
		const canGetGeolocation =
			isMapViewEnabled && isGeolocationWatchSupported && (googleMapsApiKey && googleMapsApiKey.length);

		if (!canGetGeolocation) {
			geolocation.set(false);
			return;
		}

		navigator.geolocation.watchPosition(handleGeolocation, handleGeolocationError, {
			enableHighAccuracy: true,
			maximumAge: 0,
			timeout: 10000,
		});
	});
Ejemplo n.º 5
0
Template.vocTables.onCreated(function(){
    // reactively get distinct organ site categories
    let organSites = new ReactiveVar([]);
    Tracker.autorun(()=>{
        let results = NtpEpiConfounder.find().fetch(),
            sites = _.chain(results)
                    .pluck('organSiteCategory')
                    .uniq()
                    .sort()
                    .value();
        organSites.set(sites);
    });

    _.extend(this, {
        organSites,
        showForm: new ReactiveVar(true),
    });
});
Ejemplo n.º 6
0
Template.registerHelper("monthOptions", (showDefaultOption = true) => {
  const label = i18next.t("app.monthOptions", "Choose month");

  // Call to get monthOptionsVar ReactiveVar
  lazyLoadMonths();
  let monthOptions = [];

  if (showDefaultOption) {
    monthOptions.push({
      value: "",
      label
    });
  }

  monthOptions = monthOptions.concat(monthOptionsVar.get());

  return monthOptions;
});
Ejemplo n.º 7
0
    'click .run ': function (e, t) {

        let result = {};
        result.branchId = $('[name="branchId"]').val();
        result.date = $('[name="date"]').val();
        result.currencyId = $('[name="currencyId"]').val();
        result.exchangeDate = $('[name="exchangeDate"]').val();
        result.accountType = $('[name="accountType"]').val();
        result.chartAccount = $('[name="chartAccount"]').val();

        if (result.accountType == "" || result.exchangeDate == "") {
            alertify.warning("Required!!!");
            return false;
        }


        formDataState.set(result);
    },
Ejemplo n.º 8
0
 return Meteor.call("products/cloneProduct", products, (error, result) => {
   if (error) {
     Alerts.add(error, "danger", { placement: "productGridItem" });
     throw new ReactionError("error-occurred", error);
   }
   if (result) {
     if (products.length === 1) {
       Alerts.add(i18next.t("productDetail.clonedAlert", { product: products[0].title }), "success", {
         placement: "productGridItem",
         id: products[0]._id,
         autoHide: true,
         dismissable: false
       });
     } else {
       Alerts.add(
         i18next.t("productDetail.clonedAlert_plural", {
           product: i18next.t("productDetail.theSelectedProducts"),
           count: 0
         }),
         "success",
         {
           placement: "productGridItem",
           id: products[0]._id,
           autoHide: true,
           dismissable: false
         }
       );
     }
   }
   // this statement allow us to redirect to a new clone PDP if clone action
   // was fired within PDP, not within productGrid.
   if (!Array.isArray(productOrArray)) {
     Router.go("product", {
       handle: result[0]
     });
   } else {
     resubscribeAfterCloning.set(true);
   }
 });
Ejemplo n.º 9
0
	async getInstanceByRoomId(roomId) {
		if (!this.enabled.get()) {
			return;
		}

		const room = Rooms.findOne({
			_id: roomId,
		});

		if (!room) {
			return;
		}

		if (room.encrypted !== true) {
			return;
		}

		if (!this.instancesByRoomId[roomId]) {
			const subscription = Subscriptions.findOne({
				rid: roomId,
			});

			if (!subscription || (subscription.t !== 'd' && subscription.t !== 'p')) {
				return;
			}

			this.instancesByRoomId[roomId] = new E2ERoom(Meteor.userId(), roomId, subscription.t);
		}

		const e2eRoom = this.instancesByRoomId[roomId];

		await this.ready();

		if (e2eRoom) {
			await e2eRoom.handshake();
			return e2eRoom;
		}
	}
Ejemplo n.º 10
0
		this.loadFromCache((cacheLoaded) => {
			this.ready.set(cacheLoaded);

			if (cacheLoaded === false) {
				// If there is no cache load data immediately
				this.loadFromServerAndPopulate();
			} else if (this.useSync === true) {
				this.trySync();
			}

			if (this.useSync === true) {
				CachedCollectionManager.onReconnect(() => {
					this.trySync();
				});
			}

			if (this.listenChangesForLoggedUsersOnly) {
				CachedCollectionManager.onLogin(() => {
					this.setupListener();
				});
			} else {
				this.setupListener();
			}
		});
Ejemplo n.º 11
0
	onRemoteStatus(data) {
		// this.log(onRemoteStatus, arguments);
		this.callInProgress.set(true);
		Meteor.clearTimeout(this.callInProgressTimeout);
		this.callInProgressTimeout = Meteor.setTimeout(this.resetCallInProgress.bind(this), 2000);
		if (this.active !== true) {
			return;
		}
		const remoteConnections = [{
			id: data.from,
			media: data.media,
		},
		...data.remoteConnections];

		remoteConnections.forEach((remoteConnection) => {
			if (remoteConnection.id !== this.selfId && (this.peerConnections[remoteConnection.id] == null)) {
				this.log('reconnecting with', remoteConnection.id);
				this.onRemoteJoin({
					from: remoteConnection.id,
					media: remoteConnection.media,
				});
			}
		});
	}
Ejemplo n.º 12
0
		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);
					}
				});
			}
		});
Ejemplo n.º 13
0
	resetCallInProgress() {
		this.callInProgress.set(false);
	}
Ejemplo n.º 14
0
export const MsgTyping = (function() {
	const timeout = 15000;
	const timeouts = {};
	let renew = true;
	const renewTimeout = 10000;
	const selfTyping = new ReactiveVar(false);
	const usersTyping = {};
	const dep = new Tracker.Dependency;

	const shownName = function(user) {
		if (!user) {
			return;
		}
		if (RocketChat.settings.get('UI_Use_Real_Name')) {
			return user.name;
		}
		return user.username;
	};

	const addStream = function(room) {
		if (!_.isEmpty(usersTyping[room] && usersTyping[room].users)) {
			return;
		}
		usersTyping[room] = { users: {} };
		return RocketChat.Notifications.onRoom(room, 'typing', function(username, typing) {
			const user = Meteor.users.findOne(Meteor.userId(), { fields: { name: 1, username: 1 } });
			if (username === shownName(user)) {
				return;
			}
			const { users } = usersTyping[room];
			if (typing === true) {
				users[username] = Meteor.setTimeout(function() {
					delete users[username];
					usersTyping[room].users = users;
					return dep.changed();
				}, timeout);
			} else {
				delete users[username];
			}
			usersTyping[room].users = users;
			return dep.changed();
		});
	};

	Tracker.autorun(() => Session.get('openedRoom') && addStream(Session.get('openedRoom')));
	const stop = function(room) {
		renew = true;
		selfTyping.set(false);
		if (timeouts && timeouts[room]) {
			clearTimeout(timeouts[room]);
			timeouts[room] = null;
		}
		const user = Meteor.user();
		return RocketChat.Notifications.notifyRoom(room, 'typing', shownName(user), false);
	};
	const start = function(room) {
		if (!renew) { return; }

		setTimeout(() => renew = true, renewTimeout);

		renew = false;
		selfTyping.set(true);
		const user = Meteor.user();
		RocketChat.Notifications.notifyRoom(room, 'typing', shownName(user), true);
		clearTimeout(timeouts[room]);
		return timeouts[room] = Meteor.setTimeout(() => stop(room), timeout);
	};


	const get = function(room) {
		dep.depend();
		if (!usersTyping[room]) {
			usersTyping[room] = { users: {} };
		}
		const { users } = usersTyping[room];
		return _.keys(users) || [];
	};

	return { start, stop, get, selfTyping };
}());
Ejemplo n.º 15
0
/**
 * @summary Products composer
 * @param {Object} props Props from parent
 * @param {Function} onData Call with props changes
 * @returns {undefined}
 */
function composer(props, onData) {
  window.prerenderReady = false;

  const queryParams = Object.assign({}, Reaction.Router.current().query);

  // Filter by tag
  const tagIdOrSlug = Reaction.Router.getParam("slug");
  if (tagIdOrSlug) {
    const tag = Tags.findOne({ slug: tagIdOrSlug }) || Tags.findOne({ _id: tagIdOrSlug });
    // if we get an invalid slug, don't return all products
    if (!tag) {
      onData(null, {
        showNotFound: true
      });
      return;
    }

    queryParams.tags = [tag._id];
  }

  // Filter by shop
  const shopIdOrSlug = Reaction.Router.getParam("shopSlug");
  if (shopIdOrSlug) {
    queryParams.shops = [shopIdOrSlug];
  }

  const scrollLimit = Session.get("productScrollLimit");
  const sort = { createdAt: 1 };

  // if we have a "viewAs" preference and the preference is not set to "administrator", then edit mode is false
  const viewAsPref = Reaction.getUserPreferences("reaction-dashboard", "viewAs");
  const editMode = !viewAsPref || viewAsPref === "administrator";

  // Now that we have the necessary info, we can subscribe to Products we need
  const productsSubscription = Meteor.subscribe("Products", scrollLimit, queryParams, sort, editMode);
  if (productsSubscription.ready()) {
    window.prerenderReady = true;
  }

  const activeShopsIds = Shops.find({
    $or: [
      { "workflow.status": "active" },
      { _id: Reaction.getPrimaryShopId() }
    ]
  }).map((activeShop) => activeShop._id);

  const products = Products.find({
    ancestors: [],
    type: "simple",
    shopId: { $in: activeShopsIds }
  }, {
    sort
  }).fetch();
  Session.set("productGrid/products", products);

  // Update ID list for ProductGridMedia subscription
  const productIds = products.map((product) => product._id);
  reactiveProductIds.set(productIds);

  const selectedProducts = Session.get("productGrid/selectedProducts");

  if (!Reaction.isPreview() && Array.isArray(selectedProducts)) {
    if (selectedProducts.length > 0) {
      // Show the actionView if there are products selected.
      Reaction.showActionView({
        label: "Grid Settings",
        i18nKeyLabel: "gridSettingsPanel.title",
        template: "productSettings",
        type: "product"
      });
    } else {
      // If no products are selected, and we're currently displaying the "productSettings" grid admin component,
      // then hide the actionView.
      const currentActionView = Reaction.getActionView();
      if (currentActionView && currentActionView.template === "productSettings") {
        Reaction.hideActionView();
      }
    }
  }

  onData(null, {
    canLoadMoreProducts: products.length >= scrollLimit,
    isProductsSubscriptionReady: productsSubscription.ready(),
    products
  });
}
Ejemplo n.º 16
0
 onSuccess: function (formType, result) {
     formDataState.set(result);
 },
Ejemplo n.º 17
0
    onSubmit: function (insertDoc, updateDoc, currentDoc) {
        this.event.preventDefault();
        formDataState.set(null);

        this.done(null, insertDoc);
    },
Ejemplo n.º 18
0
indexTmpl.onDestroyed(function () {
    formDataState.set(null);
});
import './app-body.html';

import { Meteor } from 'meteor/meteor';
import { ReactiveVar } from 'meteor/reactive-var';
import { Template } from 'meteor/templating';

import '../components/loading.js';

const CONNECTION_ISSUE_TIMEOUT = 5000;

// A store which is local to this file?
const showConnectionIssue = new ReactiveVar(false);

Meteor.startup(() => {
  // Only show the connection error box if it has been 5 seconds since
  // the app started
  setTimeout(() => {
    // Show the connection error box
    showConnectionIssue.set(true);
  }, CONNECTION_ISSUE_TIMEOUT);
});

Template.App_body.onCreated(function appBodyOnCreated() {
  this.subscribe('messages');
});

Template.App_body.helpers({
  cordova() {
    return Meteor.isCordova && 'cordova';
  },
  connected() {
Ejemplo n.º 20
0
 }).then(function (result) {
     defaultPrice.set(result.price);
 }).catch(function (err) {
Ejemplo n.º 21
0
Tracker.autorun(() => {
  Meteor.subscribe("ProductGridMedia", reactiveProductIds.get());
});
Ejemplo n.º 22
0
Meteor.startup( () => {

  //// Get a handle on the Mongo database and driver. 
  const db          = MongoInternals.defaultRemoteCollectionDriver().mongo.db
  //  , mc          = MongoInternals.NpmModules.mongodb.module.MongoClient
      , dbName      = db.databaseName //@todo use this
      , url         = db.options.url // eg 'mongodb://127.0.0.1:3001/meteor'
      , driver      = new MongoInternals.RemoteCollectionDriver(url)
      , collections = new ReactiveVar([]) // contains `{name:'Coll', fields:[]}`
  ;

  //// Analyse each Mongo collection. 
  db.collectionNames( (error, results) => {
    if (error) throw new Meteor.Error(500, 'failed');
    results.forEach( (result) => {

      //// A Fiber is needed to avoid a ‘Can't wait without Fiber’ error. 
      Fiber( () => {
        const fields = [] // contains `{ key:'foo',types:['object','boolean'] }`
            , items  = []
        ;
        driver.open(result.name).find({}).forEach( (item) => { //@todo limit the sample
          Object.keys(item).forEach( (key) => {
            const type = typeof item[key];
            if (! fields[key]) {
              const field = { key:key, types:[ type ] };
              fields[key] = field;
              fields.push(field);
            } else if (-1 === fields[key].types.indexOf(type) ) {
              fields[key].types.push(type);
            }
          });
          items.push(item);
        });

        const documents = [];
        items.forEach( (item) => {
          const doc = { fields:[] };
          fields.forEach( (field) => {
            doc.fields.push({
              value: item[ field.key ]
            });
          });
          documents.push(doc);
        });

        const tmp = collections.get();
        tmp.push({
          name:      result.name,
          fields:    fields,
          documents: documents,
        });
        collections.set(tmp);

      }).run();
    });

  });

  //// Publish the Collections collection as a reactive data source. 
  Meteor.publish('Collections', function() {
    const self = this;

    //// Uncomment this block to add sample collections. 
    // ([
    //   { name:'first' , fields:[{key:'hi',types:['number']},{key:'ok',types:['string']}] },
    //   { name:'second', fields:[] },
    //   { name:'third' , fields:[{key:'abc',types:['object','boolean']}] },
    // ]).forEach( (collection) => {
    //   self.added('Collections', Random.id(), collection);
    // });

    //// Uncomment this block to read collections directly from config. 
    // config.collections.forEach( (collection) => {
    //   console.log(collection);
    //   self.added('Collections', Random.id(), collection);
    // });

    //// Publish the collections found above. @todo make reactive
    collections.get().forEach( (collection) => {
      // console.log(collection);
      self.added('Collections', Random.id(), collection);
    });

    self.ready();
  });


});
 setTimeout(() => {
   // Show the connection error box
   showConnectionIssue.set(true);
 }, CONNECTION_ISSUE_TIMEOUT);
Ejemplo n.º 24
0
import { ReactiveVar } from 'meteor/reactive-var'
import { Template } from 'meteor/templating'
import { $ } from './globals-client'

import { get_collection_from_name } from '../lib/export_data'

let recent_changes_n_days = new ReactiveVar(2)

Template.RecentChanges.helpers({
  last_n_days () {
    return recent_changes_n_days.get()
  }
})

Template.RecentChanges.events({
  ['input, change'] (e) {
    e.preventDefault()
    let n_days = $('#last_n_days_widget').val()
    return recent_changes_n_days.set(n_days)
  }
})

Template.ChangeList.helpers({
  wrapped_changes () {
    let result = []
    let collection = this.collname // create local variable
    let coll = get_collection_from_name(this.collname)
    let options = {'sort': {'last_edit_time': -1}} // ,'limit':10}

    let { last_n_days } = this
Ejemplo n.º 25
0
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

import './main.html';

function handleError(e) {
	console.log(e);
}

daoAddr = "0xd0719067cc351e028d3dae14d8e93fe8ba030665";
daoFactory = contracts["ethenianDAOFactoryContract"].at("0x3b3d3de7a3271f0f6bea0b6b99e6f26a64dd3617");
currentReg = new ReactiveVar();
lastRegEntry = new ReactiveVar();
modalCB = new ReactiveVar();
currentMember = new ReactiveVar();
currentDelegate = new ReactiveVar();
currentMatter = new ReactiveVar();
currentDAO = new ReactiveVar();

if (daoAddr) {
	currentDAO.set(contracts["ethenianDAOContract"].at(daoAddr))
	memberAddress = currentDAO.get().getMemberFromOwner(EthAccounts.findOne().address);
	if(memberAddress != 0)
		currentMember.set(contracts["memberContract"].at(memberAddress));
} else {
	deploy["deployNewEthenianDAO"]();
}



Ejemplo n.º 26
0
 /**
  * Get data
  * Returns all forms' data.
  */
 getData() {
   return this.array.get().map(form => form.getData())
 }
Ejemplo n.º 27
0
function composer(props, onData) {
  window.prerenderReady = false;

  let canLoadMoreProducts = false;

  const slug = Reaction.Router.getParam("slug");
  const shopIdOrSlug = Reaction.Router.getParam("shopSlug");

  const tag = Tags.findOne({ slug }) || Tags.findOne(slug);
  const scrollLimit = Session.get("productScrollLimit");
  let tags = {}; // this could be shop default implementation needed
  let shopIds = {};

  if (tag) {
    tags = { tags: [tag._id] };
  }

  if (shopIdOrSlug) {
    shopIds = { shops: [shopIdOrSlug] };
  }

  // if we get an invalid slug, don't return all products
  if (!tag && slug) {
    onData(null, {
      showNotFound: true
    });

    return;
  }

  const currentTag = ReactionProduct.getTag();

  const sort = {
    [`positions.${currentTag}.position`]: 1,
    [`positions.${currentTag}.createdAt`]: 1,
    createdAt: 1
  };

  const viewAsPref = Reaction.getUserPreferences("reaction-dashboard", "viewAs");

  // Edit mode is true by default
  let editMode = true;

  // if we have a "viewAs" preference and the preference is not set to "administrator", then edit mode is false
  if (viewAsPref && viewAsPref !== "administrator") {
    editMode = false;
  }

  const queryParams = Object.assign({}, tags, Reaction.Router.current().query, shopIds);
  const productsSubscription = Meteor.subscribe("Products", scrollLimit, queryParams, sort, editMode);
  if (resubscribeAfterCloning.get()) {
    resubscribeAfterCloning.set(false);
    productsSubscription.stop();
  }

  if (productsSubscription.ready()) {
    window.prerenderReady = true;
  }

  const activeShopsIds = Shops.find({
    $or: [
      { "workflow.status": "active" },
      { _id: Reaction.getPrimaryShopId() }
    ]
  }).map((activeShop) => activeShop._id);

  const productCursor = Products.find({
    ancestors: [],
    type: { $in: ["simple"] },
    shopId: { $in: activeShopsIds }
  });

  const productIds = [];
  const products = productCursor.map((product) => {
    productIds.push(product._id);

    return applyProductRevision(product);
  });

  const sortedProducts = ReactionProduct.sortProducts(products, currentTag);
  Session.set("productGrid/products", sortedProducts);

  reactiveProductIds.set(productIds);

  canLoadMoreProducts = productCursor.count() >= Session.get("productScrollLimit");

  const isActionViewOpen = Reaction.isActionViewOpen();
  if (isActionViewOpen === false) {
    Session.set("productGrid/selectedProducts", []);
  }

  onData(null, {
    canLoadMoreProducts,
    products: sortedProducts,
    productsSubscription
  });
}
Ejemplo n.º 28
0
import { Template } from 'meteor/templating';
import { HTTP } from 'meteor/http';
import { ReactiveVar } from 'meteor/reactive-var';

import './main.html';

let fileSize = new ReactiveVar('0 bytes');

Template.output.helpers({
  getFileSize() {
    return fileSize.get();
  },
});

Template.fileForm.events({
  'submit form'(event, instance) {
    event.preventDefault();
    const data = new FormData(event.target);

    HTTP.post(`${window.location.origin}/api/fileanalyse`, {
      content: data,
    }, (error, response) => {
      if (error) throw error;
      fileSize.set(response.content);
    });
  },
});
	Tracker.autorun((c) => {
		const cancel = Session.get(`uploading-cancel-${ upload.id }`);

		if (!cancel) {
			return;
		}

		upload.stop();
		c.stop();

		updateUploadProgress(upload, { progress: 0 });
		unregisterUploadProgress(upload);
	});
};

const recordingInterval = new ReactiveVar(null);
const recordingRoomId = new ReactiveVar(null);

Template.messageBoxAudioMessage.onCreated(function() {
	this.state = new ReactiveVar(null);
	this.time = new ReactiveVar('00:00');
	this.isMicrophoneDenied = new ReactiveVar(true);

	if (navigator.permissions) {
		navigator.permissions.query({ name: 'microphone' })
			.then((permissionStatus) => {
				this.isMicrophoneDenied.set(permissionStatus.state === 'denied');
				permissionStatus.onchange = () => {
					this.isMicrophoneDenied.set(permissionStatus.state === 'denied');
				};
			});
Ejemplo n.º 30
0
 }, (error, response) => {
   if (error) throw error;
   fileSize.set(response.content);
 });