<commit_before>/*
 Copyright 2017 Michael Telatynski <7t3chguy@gmail.com>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import { getCurrentLanguage, _t, _td } from './languageHandler';
import PlatformPeg from './PlatformPeg';
import SdkConfig from './SdkConfig';
import Modal from './Modal';
import sdk from './index';

const hashRegex = /#\/(groups?|room|user|settings|register|login|forgot_password|home|directory)/;
const hashVarRegex = /#\/(group|room|user)\/.*$/;

// Remove all but the first item in the hash path. Redact unexpected hashes.
function getRedactedHash(hash) {
    // Don't leak URLs we aren't expecting - they could contain tokens/PII
    const match = hashRegex.exec(hash);
    if (!match) {
        console.warn(`Unexpected hash location "${hash}"`);
        return '#/<unexpected hash location>';
    }

    if (hashVarRegex.test(hash)) {
        return hash.replace(hashVarRegex, "#/$1/<redacted>");
    }

    return hash.replace(hashRegex, "#/$1");
}

// Return the current origin and hash separated with a `/`. This does not include query parameters.
function getRedactedUrl() {
    const { origin, pathname, hash } = window.location;
    return origin + pathname + getRedactedHash(hash);
}

const customVariables = {
    'App Platform': {
        id: 1,
        expl: _td('The platform you\'re on'),
        example: 'Electron Platform',
    },
    'App Version': {
        id: 2,
        expl: _td('The version of Riot.im'),
        example: '15.0.0',
    },
    'User Type': {
        id: 3,
        expl: _td('Whether or not you\'re logged in (we don\'t record your user name)'),
        example: 'Logged In',
    },
    'Chosen Language': {
        id: 4,
        expl: _td('Your language of choice'),
        example: 'en',
    },
    'Instance': {
        id: 5,
        expl: _td('Which officially provided instance you are using, if any'),
        example: 'app',
    },
    'RTE: Uses Richtext Mode': {
        id: 6,
        expl: _td('Whether or not you\'re using the Richtext mode of the Rich Text Editor'),
        example: 'off',
    },
    'Homeserver URL': {
        id: 7,
        expl: _td('Your homeserver\'s URL'),
        example: 'https://matrix.org',
    },
    'Identity Server URL': {
        id: 8,
        expl: _td('Your identity server\'s URL'),
        example: 'https://vector.im',
    },
};

function whitelistRedact(whitelist, str) {
    if (whitelist.includes(str)) return str;
    return '<redacted>';
}

class Analytics {
    constructor() {
        this._paq = null;
        this.disabled = true;
        this.firstPage = true;
    }

    /**
     * Enable Analytics if initialized but disabled
     * otherwise try and initalize, no-op if piwik config missing
     */
    enable() {
        if (this._paq || this._init()) {
            this.disabled = false;
        }
    }

    /**
     * Disable Analytics calls, will not fully unload Piwik until a refresh,
     * but this is second best, Piwik should not pull anything implicitly.
     */
    disable() {
        this.trackEvent('Analytics', 'opt-out');
        // disableHeartBeatTimer is undocumented but exists in the piwik code
        // the _paq.push method will result in an error being printed in the console
        // if an unknown method signature is passed
        this._paq.push(['disableHeartBeatTimer']);
        this.disabled = true;
    }

    _init() {
        const config = SdkConfig.get();
        if (!config || !config.piwik || !config.piwik.url || !config.piwik.siteId) return;

        const url = config.piwik.url;
        const siteId = config.piwik.siteId;
        const self = this;

        window._paq = this._paq = window._paq || [];

        this._paq.push(['setTrackerUrl', url+'piwik.php']);
        this._paq.push(['setSiteId', siteId]);

        this._paq.push(['trackAllContentImpressions']);
        this._paq.push(['discardHashTag', false]);
        this._paq.push(['enableHeartBeatTimer']);
        // this._paq.push(['enableLinkTracking', true]);

        const platform = PlatformPeg.get();
        this._setVisitVariable('App Platform', platform.getHumanReadableName());
        platform.getAppVersion().then((version) => {
            this._setVisitVariable('App Version', version);
        }).catch(() => {
            this._setVisitVariable('App Version', 'unknown');
        });

        this._setVisitVariable('Chosen Language', getCurrentLanguage());

        if (window.location.hostname === 'riot.im') {
            this._setVisitVariable('Instance', window.location.pathname);
        }

        (function() {
            const g = document.createElement('script');
            const s = document.getElementsByTagName('script')[0];
            g.type='text/javascript'; g.async=true; g.defer=true; g.src=url+'piwik.js';

            g.onload = function() {
                console.log('Initialised anonymous analytics');
                self._paq = window._paq;
            };

            s.parentNode.insertBefore(g, s);
        })();

        return true;
    }

    trackPageChange(generationTimeMs) {
        if (this.disabled) return;
        if (this.firstPage) {
            // De-duplicate first page
            // router seems to hit the fn twice
            this.firstPage = false;
            return;
        }

        if (typeof generationTimeMs === 'number') {
            this._paq.push(['setGenerationTimeMs', generationTimeMs]);
        } else {
            console.warn('Analytics.trackPageChange: expected generationTimeMs to be a number');
            // But continue anyway because we still want to track the change
        }

        this._paq.push(['setCustomUrl', getRedactedUrl()]);
        this._paq.push(['trackPageView']);
    }

    trackEvent(category, action, name) {
        if (this.disabled) return;
        this._paq.push(['trackEvent', category, action, name]);
    }

    logout() {
        if (this.disabled) return;
        this._paq.push(['deleteCookies']);
    }

    _setVisitVariable(key, value) {
        if (this.disabled) return;
        this._paq.push(['setCustomVariable', customVariables[key].id, key, value, 'visit']);
    }

    setLoggedIn(isGuest, homeserverUrl, identityServerUrl) {
        if (this.disabled) return;

        const config = SdkConfig.get();
        if (!config.piwik) return;

        const whitelistedHSUrls = config.piwik.whitelistedHSUrls || [];
        const whitelistedISUrls = config.piwik.whitelistedISUrls || [];

        this._setVisitVariable('User Type', isGuest ? 'Guest' : 'Logged In');
        this._setVisitVariable('Homeserver URL', whitelistRedact(whitelistedHSUrls, homeserverUrl));
        this._setVisitVariable('Identity Server URL', whitelistRedact(whitelistedISUrls, identityServerUrl));
    }

    setRichtextMode(state) {
        if (this.disabled) return;
        this._setVisitVariable('RTE: Uses Richtext Mode', state ? 'on' : 'off');
    }

    showDetailsModal() {
        let rows = [];
        if (window.Piwik) {
            const Tracker = window.Piwik.getAsyncTracker();
            rows = Object.values(customVariables).map((v) => Tracker.getCustomVariable(v.id)).filter(Boolean);
        } else {
            // Piwik may not have been enabled, so show example values
            rows = Object.keys(customVariables).map(
                (k) => [
                    k,
                    _t('e.g. %(exampleValue)s', { exampleValue: customVariables[k].example }),
                ],
            );
        }

        const resolution = `${window.screen.width}x${window.screen.height}`;
        const otherVariables = [
            {
                expl: _td('Every page you use in the app'),
                value: _t(
                    'e.g. <CurrentPageURL>',
                    {},
                    {
                        CurrentPageURL: getRedactedUrl(),
                    },
                ),
            },
            { expl: _td('Your User Agent'), value: navigator.userAgent },
            { expl: _td('Your device resolution'), value: resolution },
        ];

        const ErrorDialog = sdk.getComponent('dialogs.ErrorDialog');
        Modal.createTrackedDialog('Analytics Details', '', ErrorDialog, {
            title: _t('Analytics'),
            description:

                    { _t('The information being sent to us to help make Riot.im better includes:') }

                    { rows.map((row) =>

                        { _t(customVariables[row[0]].expl) }
                        { row[1] !== undefined && { row[1] }	 }

) }
                    { otherVariables.map((item, index) =>

                            { _t(item.expl) }
                            { item.value }

,
                    ) }

                    { _t('Where this page includes identifiable information, such as a room, '
                        + 'user or group ID, that data is removed before being sent to the server.') }

,
        });
    }
}

if (!global.mxAnalytics) {
    global.mxAnalytics = new Analytics();
}
module.exports = global.mxAnalytics;
<commit_msg>Redact pathnames with origin `file://`<commit_after>/*
 Copyright 2017 Michael Telatynski <7t3chguy@gmail.com>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import { getCurrentLanguage, _t, _td } from './languageHandler';
import PlatformPeg from './PlatformPeg';
import SdkConfig from './SdkConfig';
import Modal from './Modal';
import sdk from './index';

const hashRegex = /#\/(groups?|room|user|settings|register|login|forgot_password|home|directory)/;
const hashVarRegex = /#\/(group|room|user)\/.*$/;

// Remove all but the first item in the hash path. Redact unexpected hashes.
function getRedactedHash(hash) {
    // Don't leak URLs we aren't expecting - they could contain tokens/PII
    const match = hashRegex.exec(hash);
    if (!match) {
        console.warn(`Unexpected hash location "${hash}"`);
        return '#/<unexpected hash location>';
    }

    if (hashVarRegex.test(hash)) {
        return hash.replace(hashVarRegex, "#/$1/<redacted>");
    }

    return hash.replace(hashRegex, "#/$1");
}

// Return the current origin, path and hash separated with a `/`. This does
// not include query parameters.
function getRedactedUrl() {
    const { origin, pathname, hash } = window.location;

    // Redact paths which could contain unexpected PII
    if (origin.startsWith('file://')) {
        pathname = "/<redacted>/";
    }

    return origin + pathname + getRedactedHash(hash);
}

const customVariables = {
    'App Platform': {
        id: 1,
        expl: _td('The platform you\'re on'),
        example: 'Electron Platform',
    },
    'App Version': {
        id: 2,
        expl: _td('The version of Riot.im'),
        example: '15.0.0',
    },
    'User Type': {
        id: 3,
        expl: _td('Whether or not you\'re logged in (we don\'t record your user name)'),
        example: 'Logged In',
    },
    'Chosen Language': {
        id: 4,
        expl: _td('Your language of choice'),
        example: 'en',
    },
    'Instance': {
        id: 5,
        expl: _td('Which officially provided instance you are using, if any'),
        example: 'app',
    },
    'RTE: Uses Richtext Mode': {
        id: 6,
        expl: _td('Whether or not you\'re using the Richtext mode of the Rich Text Editor'),
        example: 'off',
    },
    'Homeserver URL': {
        id: 7,
        expl: _td('Your homeserver\'s URL'),
        example: 'https://matrix.org',
    },
    'Identity Server URL': {
        id: 8,
        expl: _td('Your identity server\'s URL'),
        example: 'https://vector.im',
    },
};

function whitelistRedact(whitelist, str) {
    if (whitelist.includes(str)) return str;
    return '<redacted>';
}

class Analytics {
    constructor() {
        this._paq = null;
        this.disabled = true;
        this.firstPage = true;
    }

    /**
     * Enable Analytics if initialized but disabled
     * otherwise try and initalize, no-op if piwik config missing
     */
    enable() {
        if (this._paq || this._init()) {
            this.disabled = false;
        }
    }

    /**
     * Disable Analytics calls, will not fully unload Piwik until a refresh,
     * but this is second best, Piwik should not pull anything implicitly.
     */
    disable() {
        this.trackEvent('Analytics', 'opt-out');
        // disableHeartBeatTimer is undocumented but exists in the piwik code
        // the _paq.push method will result in an error being printed in the console
        // if an unknown method signature is passed
        this._paq.push(['disableHeartBeatTimer']);
        this.disabled = true;
    }

    _init() {
        const config = SdkConfig.get();
        if (!config || !config.piwik || !config.piwik.url || !config.piwik.siteId) return;

        const url = config.piwik.url;
        const siteId = config.piwik.siteId;
        const self = this;

        window._paq = this._paq = window._paq || [];

        this._paq.push(['setTrackerUrl', url+'piwik.php']);
        this._paq.push(['setSiteId', siteId]);

        this._paq.push(['trackAllContentImpressions']);
        this._paq.push(['discardHashTag', false]);
        this._paq.push(['enableHeartBeatTimer']);
        // this._paq.push(['enableLinkTracking', true]);

        const platform = PlatformPeg.get();
        this._setVisitVariable('App Platform', platform.getHumanReadableName());
        platform.getAppVersion().then((version) => {
            this._setVisitVariable('App Version', version);
        }).catch(() => {
            this._setVisitVariable('App Version', 'unknown');
        });

        this._setVisitVariable('Chosen Language', getCurrentLanguage());

        if (window.location.hostname === 'riot.im') {
            this._setVisitVariable('Instance', window.location.pathname);
        }

        (function() {
            const g = document.createElement('script');
            const s = document.getElementsByTagName('script')[0];
            g.type='text/javascript'; g.async=true; g.defer=true; g.src=url+'piwik.js';

            g.onload = function() {
                console.log('Initialised anonymous analytics');
                self._paq = window._paq;
            };

            s.parentNode.insertBefore(g, s);
        })();

        return true;
    }

    trackPageChange(generationTimeMs) {
        if (this.disabled) return;
        if (this.firstPage) {
            // De-duplicate first page
            // router seems to hit the fn twice
            this.firstPage = false;
            return;
        }

        if (typeof generationTimeMs === 'number') {
            this._paq.push(['setGenerationTimeMs', generationTimeMs]);
        } else {
            console.warn('Analytics.trackPageChange: expected generationTimeMs to be a number');
            // But continue anyway because we still want to track the change
        }

        this._paq.push(['setCustomUrl', getRedactedUrl()]);
        this._paq.push(['trackPageView']);
    }

    trackEvent(category, action, name) {
        if (this.disabled) return;
        this._paq.push(['trackEvent', category, action, name]);
    }

    logout() {
        if (this.disabled) return;
        this._paq.push(['deleteCookies']);
    }

    _setVisitVariable(key, value) {
        if (this.disabled) return;
        this._paq.push(['setCustomVariable', customVariables[key].id, key, value, 'visit']);
    }

    setLoggedIn(isGuest, homeserverUrl, identityServerUrl) {
        if (this.disabled) return;

        const config = SdkConfig.get();
        if (!config.piwik) return;

        const whitelistedHSUrls = config.piwik.whitelistedHSUrls || [];
        const whitelistedISUrls = config.piwik.whitelistedISUrls || [];

        this._setVisitVariable('User Type', isGuest ? 'Guest' : 'Logged In');
        this._setVisitVariable('Homeserver URL', whitelistRedact(whitelistedHSUrls, homeserverUrl));
        this._setVisitVariable('Identity Server URL', whitelistRedact(whitelistedISUrls, identityServerUrl));
    }

    setRichtextMode(state) {
        if (this.disabled) return;
        this._setVisitVariable('RTE: Uses Richtext Mode', state ? 'on' : 'off');
    }

    showDetailsModal() {
        let rows = [];
        if (window.Piwik) {
            const Tracker = window.Piwik.getAsyncTracker();
            rows = Object.values(customVariables).map((v) => Tracker.getCustomVariable(v.id)).filter(Boolean);
        } else {
            // Piwik may not have been enabled, so show example values
            rows = Object.keys(customVariables).map(
                (k) => [
                    k,
                    _t('e.g. %(exampleValue)s', { exampleValue: customVariables[k].example }),
                ],
            );
        }

        const resolution = `${window.screen.width}x${window.screen.height}`;
        const otherVariables = [
            {
                expl: _td('Every page you use in the app'),
                value: _t(
                    'e.g. <CurrentPageURL>',
                    {},
                    {
                        CurrentPageURL: getRedactedUrl(),
                    },
                ),
            },
            { expl: _td('Your User Agent'), value: navigator.userAgent },
            { expl: _td('Your device resolution'), value: resolution },
        ];

        const ErrorDialog = sdk.getComponent('dialogs.ErrorDialog');
        Modal.createTrackedDialog('Analytics Details', '', ErrorDialog, {
            title: _t('Analytics'),
            description:

                    { _t('The information being sent to us to help make Riot.im better includes:') }

                    { rows.map((row) =>

                        { _t(customVariables[row[0]].expl) }
                        { row[1] !== undefined && { row[1] }	 }

) }
                    { otherVariables.map((item, index) =>

                            { _t(item.expl) }
                            { item.value }

,
                    ) }

                    { _t('Where this page includes identifiable information, such as a room, '
                        + 'user or group ID, that data is removed before being sent to the server.') }

,
        });
    }
}

if (!global.mxAnalytics) {
    global.mxAnalytics = new Analytics();
}
module.exports = global.mxAnalytics;
<|endoftext|>


<commit_before>//TODO this is necessary during DEV, to reload bkg page
// var bkg = chrome.extension.getBackgroundPage();
// bkg.location.reload();
//reload code ends

document.addEventListener('DOMContentLoaded', function () {
  document.getElementById("getSelectionBtn").addEventListener('click', getSelectionHandler);
  document.getElementById('aesGenBtn').addEventListener('click', genAES);
  document.getElementById('addFriend').addEventListener('click', addFriend);
});

// Send message to background script
function getSelectionHandler() {

	chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {

	  chrome.tabs.sendMessage(tabs[0].id, {method: "encrypt"},

      function(res){

        var selectedElements = $('#friendSelect option:selected');
        var encryptedMsgs = "Message by www.dispeakable.me\n";
        encryptedMsgs += "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
        $.each(selectedElements, function(i, ele){
          var uid = $(ele).attr("data-uid");
          encryptedMsgs += uid + "\n";
          encryptedMsgs += encrypt(uid, res);
          encryptedMsgs += "\n";
          encryptedMsgs += "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
          // console.log(encrypted);
          // console.log(decrypt(uid, encrypted));
        });
        console.log(encryptedMsgs);
        chrome.tabs.sendMessage(tabs[0].id, {method:"updateViewWithEncryptedMessage", encryptedMessage: encryptedMsgs});

	  });
	});
}

var genAES = function(e){
  var pass = $('#password').val();
  var me = localStorage.getItem('me');
  var enc = GibberishAES.enc(me, pass);
  $('#aes').html(enc);
  e.preventDefault();
}

var addFriend = function(e){
  var fname = $('#friend_name').val();
  var secret = $('#f_secretKey').val();
  var fPasskey = $('#fPasskey').val();

  var dec = GibberishAES.dec(fPasskey, secret);

  var obj = JSON.parse(dec);
  obj.name = fname;

  var flist = JSON.parse(localStorage.getItem('friends'));
  flist.push(obj);
  localStorage.setItem('friends', JSON.stringify(flist));

  var newFriend = $("<option></option>").attr("data-uid", obj.uid).html(fname);

  $("#friendSelect").append(newFriend);

  $('#friend_name').val("");
  $('#f_secretKey').val("");
  $('#fPasskey').val("");
  e.preventDefault();
}

var decrypt = function(uid, msg){
  var flist = JSON.parse(localStorage.getItem('friends'));
  for (var _i = 0; _i < flist.length; _i++){
    if (flist[_i].uid === uid){
      var decrypt = new JSEncrypt({default_key_size : 2048});
      decrypt.setPrivateKey(flist[_i].private);
      return decrypt.decrypt(msg);
    }
  }

  var me = JSON.parse(localStorage.getItem('me'));
  var decrypt = new JSEncrypt({default_key_size : 2048});
  decrypt.setPrivateKey(me.private);
  return decrypt.decrypt(msg);
}

var encrypt = function(uid, msg){
  var flist = JSON.parse(localStorage.getItem('friends'));
  for (var _i = 0; _i < flist.length; _i++){
    if (flist[_i].uid === uid){
      var encrypt = new JSEncrypt({default_key_size : 2048});
      // TODO : Should be public key. Library bug?
      encrypt.setPrivateKey(flist[_i].private);
      // encrypt.setPublicKey(flist[_i].public);
      return encrypt.encrypt(msg);
    }
  }
}

//WILS AREA, STAY THE FUCK OUT!!!
// (function($){
  pageInitialized = false;
  $(function() {
    if(pageInitialized) return;
    pageInitialized = true;
    // Handler for .ready() called.
    var $goggles = $('#goggles');
    var mouseleft = false;
    $(document).on('mouseup', function(e){
      $goggles.css({
        'top': 33,
        'left': 29
      });
      if(e.pageX<0 || e.pageX>300 || e.pageY < 0 || e.pageY > 626){
        //TODO send message to background
        chrome.runtime.sendMessage({greeting: "potato"}, function(response) {
          if(response.farewell == "banana"){
            $goggles.hide();
          }else{
            console.log(response.farewell);
          }
        });
      }
      return false;
    });
    $goggles.draggable();
  });
// })(jQuery);

//END OF WILS AREA
<commit_msg>friends localStorage initialize bug fix<commit_after>//TODO this is necessary during DEV, to reload bkg page
// var bkg = chrome.extension.getBackgroundPage();
// bkg.location.reload();
//reload code ends

document.addEventListener('DOMContentLoaded', function () {
  document.getElementById("getSelectionBtn").addEventListener('click', getSelectionHandler);
  document.getElementById('aesGenBtn').addEventListener('click', genAES);
  document.getElementById('addFriend').addEventListener('click', addFriend);
});

// Send message to background script
function getSelectionHandler() {

	chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {

	  chrome.tabs.sendMessage(tabs[0].id, {method: "encrypt"},

      function(res){

        var selectedElements = $('#friendSelect option:selected');
        var encryptedMsgs = "Message by www.dispeakable.me\n";
        encryptedMsgs += "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
        $.each(selectedElements, function(i, ele){
          var uid = $(ele).attr("data-uid");
          encryptedMsgs += uid + "\n";
          encryptedMsgs += encrypt(uid, res);
          encryptedMsgs += "\n";
          encryptedMsgs += "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
          // console.log(encrypted);
          // console.log(decrypt(uid, encrypted));
        });
        console.log(encryptedMsgs);
        chrome.tabs.sendMessage(tabs[0].id, {method:"updateViewWithEncryptedMessage", encryptedMessage: encryptedMsgs});

	  });
	});
}

var genAES = function(e){
  var pass = $('#password').val();
  var me = localStorage.getItem('me');
  var enc = GibberishAES.enc(me, pass);
  $('#aes').html(enc);
  e.preventDefault();
}

var addFriend = function(e){
  var fname = $('#friend_name').val();
  var secret = $('#f_secretKey').val();
  var fPasskey = $('#fPasskey').val();

  var dec = GibberishAES.dec(fPasskey, secret);

  var obj = JSON.parse(dec);
  obj.name = fname;

  var flist = JSON.parse(localStorage.getItem('friends')) ? JSON.parse(localStorage.getItem('friends')) : [];
  flist.push(obj);
  localStorage.setItem('friends', JSON.stringify(flist));

  var newFriend = $("<option></option>").attr("data-uid", obj.uid).html(fname);

  $("#friendSelect").append(newFriend);

  $('#friend_name').val("");
  $('#f_secretKey').val("");
  $('#fPasskey').val("");
  e.preventDefault();
}

var decrypt = function(uid, msg){
  var flist = JSON.parse(localStorage.getItem('friends'));
  for (var _i = 0; _i < flist.length; _i++){
    if (flist[_i].uid === uid){
      var decrypt = new JSEncrypt({default_key_size : 2048});
      decrypt.setPrivateKey(flist[_i].private);
      return decrypt.decrypt(msg);
    }
  }

  var me = JSON.parse(localStorage.getItem('me'));
  var decrypt = new JSEncrypt({default_key_size : 2048});
  decrypt.setPrivateKey(me.private);
  return decrypt.decrypt(msg);
}

var encrypt = function(uid, msg){
  var flist = JSON.parse(localStorage.getItem('friends'));
  for (var _i = 0; _i < flist.length; _i++){
    if (flist[_i].uid === uid){
      var encrypt = new JSEncrypt({default_key_size : 2048});
      // TODO : Should be public key. Library bug?
      encrypt.setPrivateKey(flist[_i].private);
      // encrypt.setPublicKey(flist[_i].public);
      return encrypt.encrypt(msg);
    }
  }
}

//WILS AREA, STAY THE FUCK OUT!!!
// (function($){
  pageInitialized = false;
  $(function() {
    if(pageInitialized) return;
    pageInitialized = true;
    // Handler for .ready() called.
    var $goggles = $('#goggles');
    var mouseleft = false;
    $(document).on('mouseup', function(e){
      $goggles.css({
        'top': 33,
        'left': 29
      });
      if(e.pageX<0 || e.pageX>300 || e.pageY < 0 || e.pageY > 626){
        //TODO send message to background
        chrome.runtime.sendMessage({greeting: "potato"}, function(response) {
          if(response.farewell == "banana"){
            $goggles.hide();
          }else{
            console.log(response.farewell);
          }
        });
      }
      return false;
    });
    $goggles.draggable();
  });
// })(jQuery);

//END OF WILS AREA
<|endoftext|>


<commit_before>module.exports = function (grunt) {
  'use strict';

  grunt.initConfig({
    lint: {
      files: ['grunt.js', 'shield.js']
    },

    watch: {
      files: '<config:lint.files>',
      tasks: 'lint'
    },

    jshint: {
      options: {
        bitwise: true,
        boss: true,
        browser: true,
        curly: true,
        devel: true,
        eqeqeq: true,
        eqnull: true,
        es5: true,
        immed: true,
        indent: 2,
        latedef: true,
        maxdepth: 9,
        maxerr: 20
        maxparams: 6,
        newcap: true,
        noarg: true,
        noempty: true,
        nonew: true,
        onecase: true,
        quotmark: 'single',
        regexp: true,
        strict: true,
        sub: true,
        trailing: true,
        undef: true,
        unused: true,
        white: false
      }
    }
  });

  // Default task
  grunt.registerTask('default', 'lint watch');

  // Travis-CI task
  grunt.registerTask('travis', 'lint');
};<commit_msg>Fix syntax error in grunt.js<commit_after>module.exports = function (grunt) {
  'use strict';

  grunt.initConfig({
    lint: {
      files: ['grunt.js', 'shield.js']
    },

    watch: {
      files: '<config:lint.files>',
      tasks: 'lint'
    },

    jshint: {
      options: {
        bitwise: true,
        boss: true,
        browser: true,
        curly: true,
        devel: true,
        eqeqeq: true,
        eqnull: true,
        es5: true,
        immed: true,
        indent: 2,
        latedef: true,
        maxdepth: 9,
        maxerr: 20,
        maxparams: 6,
        newcap: true,
        noarg: true,
        noempty: true,
        nonew: true,
        onecase: true,
        quotmark: 'single',
        regexp: true,
        strict: true,
        sub: true,
        trailing: true,
        undef: true,
        unused: true,
        white: false
      }
    }
  });

  // Default task
  grunt.registerTask('default', 'lint watch');

  // Travis-CI task
  grunt.registerTask('travis', 'lint');
};<|endoftext|>


<commit_before>import { expect }    from 'chai';
import * as DateTime from '../date-time.js';
import moment        from 'moment';

describe('toMoment', () => {
    it('return utc epoch value date based on client epoch value passed', () => {
        const epoch = 1544756041;

        expect(DateTime.toMoment(1544756041)).to.deep.equal(moment.unix(epoch).utc());
    });
});

describe('convertToUnix', () => {
    const setTime = (moment_obj, time) => {
        const [hour, minute, second] = time.split(':');
        moment_obj.hour(hour).minute(minute || 0).second(second || 0);

        return moment_obj;
    };

    it('return correct unix value when date and time passed', () => {
        const date_epoch = 1544745600;
        const time = '12:30';

        expect(DateTime.convertToUnix(date_epoch, time)).to.deep.equal(setTime(DateTime.toMoment(date_epoch), time).unix());
    });
});

describe('toGMTFormat', () => {
    it('return correct GMT value when no argument passed', () => {
        expect(DateTime.toGMTFormat()).to.deep.equal(moment().utc().format('YYYY-MM-DD HH:mm:ss [GMT]'));
    });

    it('return correct GMT value when argument passed', () => {
        const time_epoch = 1544757884620;
        expect(DateTime.toGMTFormat(time_epoch)).to.deep.equal(moment(time_epoch).utc().format('YYYY-MM-DD HH:mm:ss [GMT]'));
    });
});

describe('formatDate', () => {
    const date_format = 'YYYY-MM-DD'
    it('return correct response when no argument passed', () => {
        expect(DateTime.formatDate()).to.eql(moment().utc().format(date_format));
    });

    it('return correct date value when argument passed', () => {
        // get today date
        const date = moment().utc();
        expect(DateTime.formatDate(date, date_format)).to.deep.equal(moment(date).format(date_format));
    });
});

describe('daysFromTodayTo', () => {
    it('return empty string when there is no argument passed', () => {
        expect(DateTime.daysFromTodayTo()).to.be.empty;
    });

    it('return empty string if the user selected previous day', () => {
        //get previous day
        const date = moment().utc().startOf('day').subtract(1, 'days').format('YYYY-MM-DD');
        expect(DateTime.daysFromTodayTo(date)).to.be.empty;
    });

    it('return difference value between selected date and today', () => {
        //get date three days from now
        const date = moment().utc().startOf('day').add('3', 'days').format('YYYY-MM-DD');
        expect(DateTime.daysFromTodayTo(date)).to.deep.equal(3);
    });
});

describe('convertDuration', () => {
    const start_time = moment().unix();
    const end_time = moment.unix(start_time).add(3, 'minutes').unix();

    describe('getDiffDuration', () => {
        it('return correct value when argument passed', () => {
            expect(DateTime.getDiffDuration(start_time, end_time)).to.eql(moment.duration(180000));
        });
    });

    describe('formatDuration', () => {
        it('return correct value when argument passed', () => {
            const duration = moment.duration(moment.unix(end_time).diff(moment.unix(start_time)));// three minutes
            expect(DateTime.formatDuration(duration)).to.eql('00:03:00');
        });
    });
});
<commit_msg>add testing<commit_after>import { expect }    from 'chai';
import * as DateTime from '../date-time.js';
import moment        from 'moment';

describe('toMoment', () => {
    it('return utc epoch value date based on client epoch value passed', () => {
        const epoch = 1544756041;

        expect(DateTime.toMoment(epoch)).to.deep.equal(moment.unix(epoch).utc());
    });
    it('return correct date when plain string date passed', () => {
        const date = '12 Mar 2019'
        const format = 'DD MMM YYYY'

        expect(DateTime.toMoment(date).format(format)).to.equal(date)
    });
});

describe('convertToUnix', () => {
    const setTime = (moment_obj, time) => {
        const [hour, minute, second] = time.split(':');
        moment_obj.hour(hour).minute(minute || 0).second(second || 0);

        return moment_obj;
    };

    it('return correct unix value when date and time passed', () => {
        const date_epoch = 1544745600;
        const time = '12:30';

        expect(DateTime.convertToUnix(date_epoch, time)).to.deep.equal(setTime(DateTime.toMoment(date_epoch), time).unix());
    });
});

describe('toGMTFormat', () => {
    it('return correct GMT value when no argument passed', () => {
        expect(DateTime.toGMTFormat()).to.deep.equal(moment().utc().format('YYYY-MM-DD HH:mm:ss [GMT]'));
    });

    it('return correct GMT value when argument passed', () => {
        const time_epoch = 1544757884620;
        expect(DateTime.toGMTFormat(time_epoch)).to.deep.equal(moment(time_epoch).utc().format('YYYY-MM-DD HH:mm:ss [GMT]'));
    });
});

describe('formatDate', () => {
    const date_format = 'YYYY-MM-DD'
    it('return correct response when no argument passed', () => {
        expect(DateTime.formatDate()).to.eql(moment().utc().format(date_format));
    });

    it('return correct date value when argument passed', () => {
        // get today date
        const date = moment().utc();
        expect(DateTime.formatDate(date, date_format)).to.deep.equal(moment(date).format(date_format));
    });
});

describe('daysFromTodayTo', () => {
    it('return empty string when there is no argument passed', () => {
        expect(DateTime.daysFromTodayTo()).to.be.empty;
    });

    it('return empty string if the user selected previous day', () => {
        //get previous day
        const date = moment().utc().startOf('day').subtract(1, 'days').format('YYYY-MM-DD');
        expect(DateTime.daysFromTodayTo(date)).to.be.empty;
    });

    it('return difference value between selected date and today', () => {
        //get date three days from now
        const date = moment().utc().startOf('day').add('3', 'days').format('YYYY-MM-DD');
        expect(DateTime.daysFromTodayTo(date)).to.deep.equal(3);
    });
});

describe('convertDuration', () => {
    const start_time = moment().unix();
    const end_time = moment.unix(start_time).add(3, 'minutes').unix();

    describe('getDiffDuration', () => {
        it('return correct value when argument passed', () => {
            expect(DateTime.getDiffDuration(start_time, end_time)).to.eql(moment.duration(180000));
        });
    });

    describe('formatDuration', () => {
        it('return correct value when argument passed', () => {
            const duration = moment.duration(moment.unix(end_time).diff(moment.unix(start_time)));// three minutes
            expect(DateTime.formatDuration(duration)).to.eql('00:03:00');
        });
    });
});
<|endoftext|>


<commit_before>import { clone } from 'lodash';
import debug from 'debug';
import nodemiral from 'nodemiral';

const log = debug('mup:module:proxy');
const PROXY_CONTAINER_NAME = 'mup-nginx-proxy';

export function logs(api) {
  log('exec => mup proxy logs');
  const config = api.getConfig().proxy;

  if (!config) {
    console.error('error: no configs found for proxy');
    process.exit(1);
  }

  const args = api.getArgs().slice(1);
  const sessions = api.getSessions(['app']);
  return api.getDockerLogs(PROXY_CONTAINER_NAME, sessions, args);
}

export function setup(api) {
  log('exec => mup proxy setup');
  const config = api.getConfig().proxy;
  const appName = api.getConfig().app.name;

  if (!config) {
    console.error('error: no configs found for proxy');
    process.exit(1);
  }

  const list = nodemiral.taskList('Setup proxy');

  list.executeScript('Setup Environment', {
    script: api.resolvePath(__dirname, 'assets/proxy-setup.sh'),
    vars: {
      name: PROXY_CONTAINER_NAME
    }
  });

  list.copy('Pushing the Startup Script', {
    src: api.resolvePath(__dirname, 'assets/templates/start.sh'),
    dest: '/opt/' + PROXY_CONTAINER_NAME + '/config/start.sh',
    vars: {
      appName: PROXY_CONTAINER_NAME,
      letsEncryptEmail: config.ssl ? config.ssl.letsEncryptEmail : null
    }
  });

  list.executeScript('Cleaning Up SSL Certificates', {
    script: api.resolvePath(__dirname, 'assets/ssl-cleanup.sh'),
    vars: {
      name: appName,
      proxyName: PROXY_CONTAINER_NAME
    }
  });

  if (
    config.ssl &&
    !config.ssl.letsEncryptEmail &&
    config.ssl.upload !== false &&
    config.ssl.crt
  ) {
    list.copy('Copying SSL Certificate Bundle', {
      src: api.resolvePath(api.getBasePath(), config.ssl.crt),
      dest: `/opt/${appName}/config/bundle.crt`
    });
    list.copy('Copying SSL Private Key', {
      src: api.resolvePath(api.getBasePath(), config.ssl.key),
      dest: `/opt/${appName}/config/private.key`
    });
    list.executeScript('Setup SSL Certificates for Domains', {
      script: api.resolvePath(__dirname, 'assets/ssl-setup.sh'),
      vars: {
        appName,
        proxyName: PROXY_CONTAINER_NAME,
        domains: config.domains.split(',')
      }
    });
  }

  const sessions = api.getSessions(['app']);

  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.getVerbose()
  }).then(() => api.runCommand('proxy.start'));
}

export function reconfigShared(api) {
  const config = api.getConfig().proxy;
  const shared = config.shared || {};

  if (!config) {
    console.error('error: no configs found for proxy');
    process.exit(1);
  }

  console.log('The shared settings affect all apps using this reverse proxy.');

  if (Object.keys(shared).length === 0) {
    console.log('No shared config properties are set. Resetting proxy to defaults.');
  }

  const list = nodemiral.taskList('Configuring Proxy\'s Shared Settings');

  list.copy('Sending shared variables', {
    src: api.resolvePath(__dirname, 'assets/templates/shared-config.sh'),
    dest: '/opt/' + PROXY_CONTAINER_NAME + '/config/shared-config.sh',
    vars: {
      httpPort: shared.httpPort,
      httpsPort: shared.httpsPort,
      clientUploadLimit: shared.clientUploadLimit
    }
  });

  const env = clone(shared.env);

  list.copy('Sending proxy environment variables', {
    src: api.resolvePath(__dirname, 'assets/templates/env.list'),
    dest: '/opt/' + PROXY_CONTAINER_NAME + '/config/env.list',
    vars: {
      env: env || {}
    }
  });

  const envLetsEncrypt = clone(shared.envLetsEncrypt);

  list.copy('Sending let\'s encrypt environment variables', {
    src: api.resolvePath(__dirname, 'assets/templates/env.list'),
    dest: '/opt/' + PROXY_CONTAINER_NAME + '/config/env_letsencrypt.list',
    vars: {
      env: envLetsEncrypt || {}
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.verbose
  }).then(() => api.runCommand('proxy.start'));
}

export function start(api) {
  log('exec => mup proxy start');
  const config = api.getConfig().proxy;
  if (!config) {
    console.error('error: no configs found for proxy');
    process.exit(1);
  }

  const list = nodemiral.taskList('Start proxy');

  list.executeScript('Start proxy', {
    script: api.resolvePath(__dirname, 'assets/proxy-start.sh'),
    vars: {
      appName: PROXY_CONTAINER_NAME
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.getVerbose()
  });
}

export function stop(api) {
  log('exec => mup proxy stop');
  const config = api.getConfig().proxy;
  if (!config) {
    console.error('error: no configs found for proxy');
    process.exit(1);
  }

  const list = nodemiral.taskList('Stop proxy');

  list.executeScript('Stop proxy', {
    script: api.resolvePath(__dirname, 'assets/proxy-stop.sh'),
    vars: {
      appName: PROXY_CONTAINER_NAME
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, { verbose: api.getVerbose() });
}
<commit_msg>"mup proxy stop" doesn't need a config for the proxy<commit_after>import { clone } from 'lodash';
import debug from 'debug';
import nodemiral from 'nodemiral';

const log = debug('mup:module:proxy');
const PROXY_CONTAINER_NAME = 'mup-nginx-proxy';

export function logs(api) {
  log('exec => mup proxy logs');
  const config = api.getConfig().proxy;

  if (!config) {
    console.error('error: no configs found for proxy');
    process.exit(1);
  }

  const args = api.getArgs().slice(1);
  const sessions = api.getSessions(['app']);
  return api.getDockerLogs(PROXY_CONTAINER_NAME, sessions, args);
}

export function setup(api) {
  log('exec => mup proxy setup');
  const config = api.getConfig().proxy;
  const appName = api.getConfig().app.name;

  if (!config) {
    console.error('error: no configs found for proxy');
    process.exit(1);
  }

  const list = nodemiral.taskList('Setup proxy');

  list.executeScript('Setup Environment', {
    script: api.resolvePath(__dirname, 'assets/proxy-setup.sh'),
    vars: {
      name: PROXY_CONTAINER_NAME
    }
  });

  list.copy('Pushing the Startup Script', {
    src: api.resolvePath(__dirname, 'assets/templates/start.sh'),
    dest: '/opt/' + PROXY_CONTAINER_NAME + '/config/start.sh',
    vars: {
      appName: PROXY_CONTAINER_NAME,
      letsEncryptEmail: config.ssl ? config.ssl.letsEncryptEmail : null
    }
  });

  list.executeScript('Cleaning Up SSL Certificates', {
    script: api.resolvePath(__dirname, 'assets/ssl-cleanup.sh'),
    vars: {
      name: appName,
      proxyName: PROXY_CONTAINER_NAME
    }
  });

  if (
    config.ssl &&
    !config.ssl.letsEncryptEmail &&
    config.ssl.upload !== false &&
    config.ssl.crt
  ) {
    list.copy('Copying SSL Certificate Bundle', {
      src: api.resolvePath(api.getBasePath(), config.ssl.crt),
      dest: `/opt/${appName}/config/bundle.crt`
    });
    list.copy('Copying SSL Private Key', {
      src: api.resolvePath(api.getBasePath(), config.ssl.key),
      dest: `/opt/${appName}/config/private.key`
    });
    list.executeScript('Setup SSL Certificates for Domains', {
      script: api.resolvePath(__dirname, 'assets/ssl-setup.sh'),
      vars: {
        appName,
        proxyName: PROXY_CONTAINER_NAME,
        domains: config.domains.split(',')
      }
    });
  }

  const sessions = api.getSessions(['app']);

  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.getVerbose()
  }).then(() => api.runCommand('proxy.start'));
}

export function reconfigShared(api) {
  const config = api.getConfig().proxy;
  const shared = config.shared || {};

  if (!config) {
    console.error('error: no configs found for proxy');
    process.exit(1);
  }

  console.log('The shared settings affect all apps using this reverse proxy.');

  if (Object.keys(shared).length === 0) {
    console.log('No shared config properties are set. Resetting proxy to defaults.');
  }

  const list = nodemiral.taskList('Configuring Proxy\'s Shared Settings');

  list.copy('Sending shared variables', {
    src: api.resolvePath(__dirname, 'assets/templates/shared-config.sh'),
    dest: '/opt/' + PROXY_CONTAINER_NAME + '/config/shared-config.sh',
    vars: {
      httpPort: shared.httpPort,
      httpsPort: shared.httpsPort,
      clientUploadLimit: shared.clientUploadLimit
    }
  });

  const env = clone(shared.env);

  list.copy('Sending proxy environment variables', {
    src: api.resolvePath(__dirname, 'assets/templates/env.list'),
    dest: '/opt/' + PROXY_CONTAINER_NAME + '/config/env.list',
    vars: {
      env: env || {}
    }
  });

  const envLetsEncrypt = clone(shared.envLetsEncrypt);

  list.copy('Sending let\'s encrypt environment variables', {
    src: api.resolvePath(__dirname, 'assets/templates/env.list'),
    dest: '/opt/' + PROXY_CONTAINER_NAME + '/config/env_letsencrypt.list',
    vars: {
      env: envLetsEncrypt || {}
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.verbose
  }).then(() => api.runCommand('proxy.start'));
}

export function start(api) {
  log('exec => mup proxy start');
  const config = api.getConfig().proxy;
  if (!config) {
    console.error('error: no configs found for proxy');
    process.exit(1);
  }

  const list = nodemiral.taskList('Start proxy');

  list.executeScript('Start proxy', {
    script: api.resolvePath(__dirname, 'assets/proxy-start.sh'),
    vars: {
      appName: PROXY_CONTAINER_NAME
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.getVerbose()
  });
}

export function stop(api) {
  log('exec => mup proxy stop');

  const list = nodemiral.taskList('Stop proxy');

  list.executeScript('Stop proxy', {
    script: api.resolvePath(__dirname, 'assets/proxy-stop.sh'),
    vars: {
      appName: PROXY_CONTAINER_NAME
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, { verbose: api.getVerbose() });
}
<|endoftext|>


<commit_before>(function () {
    'use strict';

    var config = require('./config');
    var google = require('googleapis');
    var OAuth2 = google.auth.OAuth2;
    var r = require('rethinkdb');
    var fs = require('fs');
    var path = require('path');
    var q = require('q');
    var request = require('request').defaults({json: true});
    var mkdirp = require('mkdirp');

    function saveImage(url, filepath) {
        var deferred = q.defer();

        config.logger.info('Starting to save image: ' + url + '. filepath: ' + filepath);
        config.logger.info('');

        mkdirp(path.dirname(filepath), function (err) {
            if (err) {
                config.logger.err(err);
                return;
            }

            config.logger.info('Created directory for pictures');

            var ws = fs.createWriteStream(filepath);
            ws.on('error', function (err) {
                config.logger.error(err);
                deferred.reject(err);
            });
            ws.on('finish', function () {
                deferred.resolve();
            });

            config.logger('Requesting url to write file: ' + url);
            request(url).pipe(ws);
        });

        return deferred.promise;
    }

    function submitPrintJob(url, imageId) {
        var filepath = config.printFolder + imageId + '.jpg';

        var requestOptions = {
            url: 'https://www.google.com/cloudprint/submit',
            formData: {
                printerid: config.printerId,
                ticket: '{ "version": "1.0", "print": {} }',
                contentType: 'image/jpeg',
                title: path.basename(filepath),
                content: fs.createReadStream(filepath),
                tag: config.printTag
            }
        };

        return saveImage(url, filepath)
            .then(function () {
                return gcp(requestOptions);
            })
            .finally(function () {
                fs.unlink(filepath);
            });
    }

    function gcp(requestOptions) {
        var deferred = q.defer();

        if (!requestOptions.method) {
            requestOptions.method = 'POST';
        }

        requestOptions.headers = requestOptions.headers || {};
        requestOptions.headers.Authorization = 'OAuth ' + config.tokens.access_token;

        request(requestOptions, function (err, response, body) {
            if (err) throw Error(err);

            if (response.statusCode === 401 || response.statusCode === 403) {
                var oauth2Client = new OAuth2(config.google.client, config.google.secret, config.google.redirect);
                oauth2Client.setCredentials(config.tokens);

                oauth2Client.refreshAccessToken(function (err, tokens) {
                    if (err) throw Error(err);

                    config.tokens = tokens;

                    requestOptions.headers.Authorization = 'OAuth ' + tokens.access_token;

                    request(requestOptions, function (err, response, body) {
                        if (err) throw Error(err);

                        if (response.statusCode >= 200 && response.statusCode < 400) {
                            deferred.resolve(body);
                        } else {
                            deferred.reject(response);
                        }
                    });
                });

            } else if (response.statusCode >= 200 && response.statusCode < 400) {
                deferred.resolve(body);
            } else {
                deferred.reject(response);
            }
        });

        return deferred.promise;
    }

    module.exports = {
        submitPrintJob: submitPrintJob,
        gcp: gcp
    };
})();
<commit_msg>adding logging statements.<commit_after>(function () {
    'use strict';

    var config = require('./config');
    var google = require('googleapis');
    var OAuth2 = google.auth.OAuth2;
    var r = require('rethinkdb');
    var fs = require('fs');
    var path = require('path');
    var q = require('q');
    var request = require('request').defaults({json: true});
    var mkdirp = require('mkdirp');

    function saveImage(url, filepath) {
        var deferred = q.defer();

        config.logger.info('Starting to save image: ' + url + '. filepath: ' + filepath);
        config.logger.info('');

        mkdirp(path.dirname(filepath), function (err) {
            if (err) {
                config.logger('error while creating path');
                config.logger.error(err);
                return;
            }

            config.logger.info('Created directory for pictures');

            var ws = fs.createWriteStream(filepath);
            ws.on('error', function (err) {
                config.logger.error(err);
                deferred.reject(err);
            });
            ws.on('finish', function () {
                deferred.resolve();
            });

            config.logger('Requesting url to write file: ' + url);
            request(url).pipe(ws);
        });

        return deferred.promise;
    }

    function submitPrintJob(url, imageId) {
        var filepath = config.printFolder + imageId + '.jpg';

        var requestOptions = {
            url: 'https://www.google.com/cloudprint/submit',
            formData: {
                printerid: config.printerId,
                ticket: '{ "version": "1.0", "print": {} }',
                contentType: 'image/jpeg',
                title: path.basename(filepath),
                content: fs.createReadStream(filepath),
                tag: config.printTag
            }
        };

        return saveImage(url, filepath)
            .then(function () {
                return gcp(requestOptions);
            })
            .finally(function () {
                fs.unlink(filepath);
            });
    }

    function gcp(requestOptions) {
        var deferred = q.defer();

        if (!requestOptions.method) {
            requestOptions.method = 'POST';
        }

        requestOptions.headers = requestOptions.headers || {};
        requestOptions.headers.Authorization = 'OAuth ' + config.tokens.access_token;

        request(requestOptions, function (err, response, body) {
            if (err) throw Error(err);

            if (response.statusCode === 401 || response.statusCode === 403) {
                var oauth2Client = new OAuth2(config.google.client, config.google.secret, config.google.redirect);
                oauth2Client.setCredentials(config.tokens);

                oauth2Client.refreshAccessToken(function (err, tokens) {
                    if (err) throw Error(err);

                    config.tokens = tokens;

                    requestOptions.headers.Authorization = 'OAuth ' + tokens.access_token;

                    request(requestOptions, function (err, response, body) {
                        if (err) throw Error(err);

                        if (response.statusCode >= 200 && response.statusCode < 400) {
                            deferred.resolve(body);
                        } else {
                            deferred.reject(response);
                        }
                    });
                });

            } else if (response.statusCode >= 200 && response.statusCode < 400) {
                deferred.resolve(body);
            } else {
                deferred.reject(response);
            }
        });

        return deferred.promise;
    }

    module.exports = {
        submitPrintJob: submitPrintJob,
        gcp: gcp
    };
})();
<|endoftext|>


<commit_before>/*@ngInject*/
module.exports = function ($scope, $mdDialog, $state, $stateParams, toastr, Project, Rule, User) {
  var projectId = $scope.projectId = $stateParams.id;
  var allUsers = [];

  $scope.loadData = function () {

    // get project
    Project.get({
        id: $stateParams.id
      }).$promise
      .then(function (res) {
        $scope.project = res;
      });

    // get rules of project
    Project.getRulesByProjectId({
        id: projectId
      }).$promise
      .then(function (res) {
        $scope.rules = res;
      });

    // get users of project
    Project.getUsersByProjectId({
        id: projectId
      }).$promise
      .then(function (res) {
        $scope.users = res;
      });

    // get all users
    User.getAllUsers().$promise
      .then(function (res) {
        allUsers = res;
      });
  };

  $scope.edit = function() {
    Project.edit($scope.project).$promise
      .then(function() {
        toastr.success('Save Success');
      })
      .catch(function(err) {
        toastr.error(err.msg);
      });
  };

  $scope.deleteRule = function (event, ruleId, index) {
    var confirm = $mdDialog.confirm()
      .title('Delete Rule')
      .textContent('Would you like to delete this rule? Id: ' + ruleId)
      .ariaLabel('Delete Rule')
      .targetEvent(event)
      .ok('Yes')
      .cancel('No');
    $mdDialog.show(confirm).then(function () {
      Rule.delete({
          id: ruleId
        }).$promise
        .then(function () {
          $scope.rules.splice(index, 1);
          toastr.success('Rule Deleted!');
        })
        .catch(function (err) {
          toastr.error(err.msg);
        });
    });
  };

  $scope.deleteUser = function (event, userId, index) {
    var confirm = $mdDialog.confirm()
      .title('Remove User')
      .textContent('Would you like to remove this user from project?')
      .ariaLabel('Remove User')
      .targetEvent(event)
      .ok('Yes')
      .cancel('No');
    $mdDialog.show(confirm).then(function () {
      Project.deleteUserFromProject({
          id: projectId,
          userId: userId
        }).$promise
        .then(function () {
          $scope.users.splice(index, 1);
          toastr.success('User Deleted!');
        })
        .catch(function (err) {
          toastr.error(err.msg);
        });
    });
  };

  $scope.deleteProject = function (event) {
    var confirm = $mdDialog.confirm()
      .title('Delete Project')
      .textContent('This will delete this project with all its rules, do you want to proceed?')
      .ariaLabel('Remove Project')
      .targetEvent(event)
      .ok('Yes')
      .cancel('No');

    $mdDialog.show(confirm).then(function () {
      Project.delete({id: $scope.project.id}).$promise
        .then(function () {
          toastr.success('Project Deleted!');
          $state.go('banshee.admin.project');
        })
        .catch(function (err) {
          toastr.error(err.msg);
        });
    });

  };

  $scope.editRule = function (event, rule){
    $mdDialog.show({
        controller: 'RuleModalCtrl',
        templateUrl: 'modules/admin/project/ruleModal.html',
        parent: angular.element(document.body),
        targetEvent: event,
        clickOutsideToClose: true,
        fullscreen: true,
        bindToController: true,
        locals: {
          rule: rule,
        }
      });
  };

  $scope.openModal = function (event, opt, project) {
    var ctrl, template, users;

    if (opt === 'addRule') {
      ctrl = 'RuleModalCtrl';
      template = 'modules/admin/project/ruleModal.html';
    }

    if (opt === 'editProject') {
      ctrl = 'ProjectModalCtrl';
      template = 'modules/admin/project/projectModal.html';
    }

    if (opt === 'addUserToProject') {
      ctrl = 'UserModalCtrl';
      template = 'modules/admin/project/userModal.html';
      users = filterUsers();
    }

    $mdDialog.show({
        controller: ctrl,
        templateUrl: template,
        parent: angular.element(document.body),
        targetEvent: event,
        clickOutsideToClose: true,
        fullscreen: true,
        locals: {
          params: {
            opt: opt,
            obj: angular.copy(project) || '',
            users: users
          }
        }
      })
      .then(function (res) {
        if (opt === 'addRule') {
          $scope.rules.push(res);
        }
        if (opt === 'addUserToProject') {
          $scope.users.push(res);
        }
      });
  };

  $scope.loadData();

  /**
   * filter user:
   *  1.user.universal = true;
   *  2.user is not the existing user list;
   * @param
   */
  function filterUsers() {
    var usersIds = getUsersId();
    return allUsers.map(function(el) {
      if (!el.universal && usersIds.indexOf(el.id) < 0) {
        return el;
      }
    });
  }

  function getUsersId() {
    return $scope.users.map(function(el) {return el.id;});
  }

  $scope.buildRepr = function (rule) {
    var parts = [];

    if (rule.trendUp && rule.thresholdMax == 0) {
      parts.push('trend ↑');
    }

    if (rule.trendUp && rule.thresholdMax != 0) {
      parts.push('(trend ↑ && value >= ' + parseFloat(rule.thresholdMax.toFixed(3)) + ')');
    }

    if (!rule.trendUp && rule.thresholdMax != 0) {
      parts.push('value >= ' + parseFloat(rule.thresholdMax.toFixed(3)));
    }

    if (rule.trendDown && rule.thresholdMin == 0) {
      parts.push('trend ↓');
    }

    if (rule.trendDown && rule.thresholdMin != 0) {
      parts.push('(trend ↓ && value <= ' + parseFloat(rule.thresholdMin.toFixed(3)) + ')');
    }

    if (!rule.trendDown && rule.thresholdMin != 0) {
      parts.push('value <= ' + parseFloat(rule.thresholdMin.toFixed(3)));
    }

    return parts.join(' || ');
  };
};
<commit_msg>Fix js lint errors<commit_after>/*@ngInject*/
module.exports = function ($scope, $mdDialog, $state, $stateParams, toastr, Project, Rule, User) {
  var projectId = $scope.projectId = $stateParams.id;
  var allUsers = [];

  $scope.loadData = function () {

    // get project
    Project.get({
        id: $stateParams.id
      }).$promise
      .then(function (res) {
        $scope.project = res;
      });

    // get rules of project
    Project.getRulesByProjectId({
        id: projectId
      }).$promise
      .then(function (res) {
        $scope.rules = res;
      });

    // get users of project
    Project.getUsersByProjectId({
        id: projectId
      }).$promise
      .then(function (res) {
        $scope.users = res;
      });

    // get all users
    User.getAllUsers().$promise
      .then(function (res) {
        allUsers = res;
      });
  };

  $scope.edit = function() {
    Project.edit($scope.project).$promise
      .then(function() {
        toastr.success('Save Success');
      })
      .catch(function(err) {
        toastr.error(err.msg);
      });
  };

  $scope.deleteRule = function (event, ruleId, index) {
    var confirm = $mdDialog.confirm()
      .title('Delete Rule')
      .textContent('Would you like to delete this rule? Id: ' + ruleId)
      .ariaLabel('Delete Rule')
      .targetEvent(event)
      .ok('Yes')
      .cancel('No');
    $mdDialog.show(confirm).then(function () {
      Rule.delete({
          id: ruleId
        }).$promise
        .then(function () {
          $scope.rules.splice(index, 1);
          toastr.success('Rule Deleted!');
        })
        .catch(function (err) {
          toastr.error(err.msg);
        });
    });
  };

  $scope.deleteUser = function (event, userId, index) {
    var confirm = $mdDialog.confirm()
      .title('Remove User')
      .textContent('Would you like to remove this user from project?')
      .ariaLabel('Remove User')
      .targetEvent(event)
      .ok('Yes')
      .cancel('No');
    $mdDialog.show(confirm).then(function () {
      Project.deleteUserFromProject({
          id: projectId,
          userId: userId
        }).$promise
        .then(function () {
          $scope.users.splice(index, 1);
          toastr.success('User Deleted!');
        })
        .catch(function (err) {
          toastr.error(err.msg);
        });
    });
  };

  $scope.deleteProject = function (event) {
    var confirm = $mdDialog.confirm()
      .title('Delete Project')
      .textContent('This will delete this project with all its rules, do you want to proceed?')
      .ariaLabel('Remove Project')
      .targetEvent(event)
      .ok('Yes')
      .cancel('No');

    $mdDialog.show(confirm).then(function () {
      Project.delete({id: $scope.project.id}).$promise
        .then(function () {
          toastr.success('Project Deleted!');
          $state.go('banshee.admin.project');
        })
        .catch(function (err) {
          toastr.error(err.msg);
        });
    });

  };

  $scope.editRule = function (event, rule){
    $mdDialog.show({
        controller: 'RuleModalCtrl',
        templateUrl: 'modules/admin/project/ruleModal.html',
        parent: angular.element(document.body),
        targetEvent: event,
        clickOutsideToClose: true,
        fullscreen: true,
        bindToController: true,
        locals: {
          rule: rule,
        }
      });
  };

  $scope.openModal = function (event, opt, project) {
    var ctrl, template, users;

    if (opt === 'addRule') {
      ctrl = 'RuleModalCtrl';
      template = 'modules/admin/project/ruleModal.html';
    }

    if (opt === 'editProject') {
      ctrl = 'ProjectModalCtrl';
      template = 'modules/admin/project/projectModal.html';
    }

    if (opt === 'addUserToProject') {
      ctrl = 'UserModalCtrl';
      template = 'modules/admin/project/userModal.html';
      users = filterUsers();
    }

    $mdDialog.show({
        controller: ctrl,
        templateUrl: template,
        parent: angular.element(document.body),
        targetEvent: event,
        clickOutsideToClose: true,
        fullscreen: true,
        locals: {
          params: {
            opt: opt,
            obj: angular.copy(project) || '',
            users: users
          }
        }
      })
      .then(function (res) {
        if (opt === 'addRule') {
          $scope.rules.push(res);
        }
        if (opt === 'addUserToProject') {
          $scope.users.push(res);
        }
      });
  };

  $scope.loadData();

  /**
   * filter user:
   *  1.user.universal = true;
   *  2.user is not the existing user list;
   * @param
   */
  function filterUsers() {
    var usersIds = getUsersId();
    return allUsers.map(function(el) {
      if (!el.universal && usersIds.indexOf(el.id) < 0) {
        return el;
      }
    });
  }

  function getUsersId() {
    return $scope.users.map(function(el) {return el.id;});
  }

  $scope.buildRepr = function (rule) {
    var parts = [];

    if (rule.trendUp && rule.thresholdMax === 0) {
      parts.push('trend ↑');
    }

    if (rule.trendUp && rule.thresholdMax !== 0) {
      parts.push('(trend ↑ && value >= ' + parseFloat(rule.thresholdMax.toFixed(3)) + ')');
    }

    if (!rule.trendUp && rule.thresholdMax !== 0) {
      parts.push('value >= ' + parseFloat(rule.thresholdMax.toFixed(3)));
    }

    if (rule.trendDown && rule.thresholdMin === 0) {
      parts.push('trend ↓');
    }

    if (rule.trendDown && rule.thresholdMin !== 0) {
      parts.push('(trend ↓ && value <= ' + parseFloat(rule.thresholdMin.toFixed(3)) + ')');
    }

    if (!rule.trendDown && rule.thresholdMin !== 0) {
      parts.push('value <= ' + parseFloat(rule.thresholdMin.toFixed(3)));
    }

    return parts.join(' || ');
  };
};
<|endoftext|>


<commit_before>var
  moment = require('moment'),
  fsr = require('file-stream-rotator');

/**
 * Neatly abstracts out the creation of file-stream-rotator configs
 *
 * @param {string} name
 * @param {string} frequency
 * @param {boolean} verbosity
 * @returns {{}}
 */
function create_fsr_config (name, frequency, verbosity) {
  var config = {}
  config.filename = name || './log/activity.log';
  config.frequency = frequency || 'daily';
  config.verbose = verbosity || false;
  return config;
}

/**
 * Creates a logger function based on the config
 *
 * Default config is:
 *
 * filename: ./log/activity.log
 * frequency: daily
 * verbose: false
 *
 * Returns a function that can be used to add messages to the logger
 *
 * @param {{filename: string, frequency: string, verbose: boolean}} streamConfig Config to create the file stream
 * @returns {function(string)}
 */
function create_logger (streamConfig) {
  var conf;

  if (! streamConfig) {
    conf = create_fsr_config();
  } else if (typeof streamConfig == 'string') {
    conf = create_fsr_config(streamConfig);
  } else {
    conf = streamConfig;
  }

  var stream = fsr.getStream(conf);

  return function(msg) {
    stream.write(moment().toISOString() + ' ' + msg + "\n");
  };
}

function create_noop_logger() {
  return function(){};
}

var loggers = {
  default: create_logger,
  noop: create_noop_logger
};

/**
 * Factory for returning the appropriate logger creator... factory.
 *
 * Yes, it's a factory factory.
 *
 * @param {string} type
 * @returns {create_logger}
 */
function get_logger_creator(type) {
  return loggers[type] ? loggers[type] : loggers.default;
}

module.exports = {
  create_logger: create_logger,
  create_fsr_config: create_fsr_config,
  get_logger_creator: get_logger_creator
};<commit_msg>Added docblock to create_noop logger<commit_after>var
  moment = require('moment'),
  fsr = require('file-stream-rotator');

/**
 * Neatly abstracts out the creation of file-stream-rotator configs
 *
 * @param {string} name
 * @param {string} frequency
 * @param {boolean} verbosity
 * @returns {{}}
 */
function create_fsr_config (name, frequency, verbosity) {
  var config = {}
  config.filename = name || './log/activity.log';
  config.frequency = frequency || 'daily';
  config.verbose = verbosity || false;
  return config;
}

/**
 * Creates a logger function based on the config
 *
 * Default config is:
 *
 * filename: ./log/activity.log
 * frequency: daily
 * verbose: false
 *
 * Returns a function that can be used to add messages to the logger
 *
 * @param {{filename: string, frequency: string, verbose: boolean}} streamConfig Config to create the file stream
 * @returns {function(string)}
 */
function create_logger (streamConfig) {
  var conf;

  if (! streamConfig) {
    conf = create_fsr_config();
  } else if (typeof streamConfig == 'string') {
    conf = create_fsr_config(streamConfig);
  } else {
    conf = streamConfig;
  }

  var stream = fsr.getStream(conf);

  return function(msg) {
    stream.write(moment().toISOString() + ' ' + msg + "\n");
  };
}

/**
 * Creates a logger function that does nothing
 *
 * This is allows you to have debug() functions in your code that work in development, but do nothing in production.  Also avoids needing to do if
 * checks before every log function.
 *
 * @returns {function()}
 */
function create_noop_logger() {
  return function(){};
}

var loggers = {
  default: create_logger,
  noop: create_noop_logger
};

/**
 * Factory for returning the appropriate logger creator... factory.
 *
 * Yes, it's a factory factory.
 *
 * @param {string} type
 * @returns {create_logger}
 */
function get_logger_creator(type) {
  return loggers[type] ? loggers[type] : loggers.default;
}

module.exports = {
  create_logger: create_logger,
  create_fsr_config: create_fsr_config,
  get_logger_creator: get_logger_creator
};<|endoftext|>


<commit_before>import {Template} from "meteor/templating";
import {Meteor} from "meteor/meteor";
import {Session} from "meteor/session";
import {FlowRouter} from "meteor/kadira:flow-router";
import Helper from "/client/imports/helper";
import {Connections} from "/lib/imports/collections";
import {connect, populateConnectionsTable} from "/client/imports/views/layouts/top_navbar/connections/connections";
import "/client/imports/views/layouts/top_navbar/connections/connections";
import "./top_navbar.html";

const toastr = require('toastr');
const Ladda = require('ladda');
const packageJson = require('/package.json');

require('datatables.net')(window, $);
require('datatables.net-buttons')(window, $);
require('datatables.net-responsive')(window, $);

require('datatables.net-bs')(window, $);
require('datatables.net-buttons-bs')(window, $);
require('datatables.net-responsive-bs')(window, $);

export const loadFile = function (currentVal, input, done, readAsString) {
    let fileInput = input.siblings('.bootstrap-filestyle').children('input');
    if (input[0].files.length == 0 && currentVal && fileInput.val()) {
        done(currentVal);
    }
    else if (input[0].files.length != 0) {
        const fileReader = new FileReader();
        fileReader.onload = function (file) {
            if (readAsString) done(file.target.result);
            else done(new Uint8Array(file.target.result));
        };

        if (readAsString) fileReader.readAsText(input[0].files[0], "UTF-8");
        else fileReader.readAsArrayBuffer(input[0].files[0]);
    } else {
        done([]);
    }
};

const init = function () {
    $(".filestyle").filestyle({});
    let selectorForSwitchDatabases = $('#tblSwitchDatabases');
    selectorForSwitchDatabases.find('tbody').on('click', 'tr', function () {
        let table = selectorForSwitchDatabases.DataTable();
        Helper.doTableRowSelectable(table, $(this));

        if (table.row(this).data()) {
            $('#inputDatabaseNameToSwitch').val(table.row(this).data().name);
        }
    });

    $('#versionText').html(packageJson.version);
};

const populateSwitchDatabaseTable = function (data) {
    let tblSwitchDatabases = $('#tblSwitchDatabases');

    tblSwitchDatabases.DataTable({
        responsive: true,
        destroy: true,
        data: data,
        columns: [
            {data: "name"}
        ],
        columnDefs: []
    }).draw();
};

Template.topNavbar.onRendered(function () {
    let connections = this.subscribe('connections');
    this.autorun(() => {
        if (connections.ready()) {
            init();
        }
    });
});

Template.topNavbar.events({
    'click #btnProceedImportExport'(e) {
        e.preventDefault();
        let laddaButton = Ladda.create(document.querySelector('#btnProceedImportExport'));
        let importInput = $('#inputImportBackupFile');

        if (importInput.val()) {
            laddaButton.start();
            loadFile(null, importInput, function (val) {
                Meteor.call('importMongoclient', val, function (err) {
                    if (err) {
                        toastr.error("Couldn't import: " + err.message);
                    } else {
                        toastr.success("Successfully imported from " + importInput.siblings('.bootstrap-filestyle').children('input').val());
                        $('#importExportMongoclientModal').modal('hide');
                    }

                    Ladda.stopAll();
                });
            }, true);
        }
    },

    'change .filestyle'(e){
        let inputSelector = $('#' + e.currentTarget.id);
        let blob = inputSelector[0].files[0];
        let fileInput = inputSelector.siblings('.bootstrap-filestyle').children('input');

        if (blob) {
            fileInput.val(blob.name);
        } else {
            fileInput.val('');
        }
    },

    'click #btnRefreshCollections2'() {
        connect(true);
    },

    'click #btnExportMongoclient' (e) {
        e.preventDefault();
        window.open('exportMongoclient');
    },

    'click #btnImportMongoclient' (e) {
        e.preventDefault();
        let icon = $('#importExportMongoclientIcon');
        $('#importExportMongoclientTitle').text('Import Mongoclient Data');
        icon.addClass('fa-download');
        icon.removeClass('fa-upload');
        $('#btnProceedImportExport').text('Import');
        $('#frmImportMongoclient').show();
        $('#frmExportMongoclient').hide();
        $('#importExportMongoclientModal').modal('show');
    },

    'click #btnAboutMongoclient' (e) {
        e.preventDefault();
        $('#aboutModal').modal('show');
    },

    'click #btnSwitchDatabase' (e) {
        e.preventDefault();
        $('#switchDatabaseModal').modal('show');

        Ladda.create(document.querySelector('#btnConnectSwitchedDatabase')).start();

        Meteor.call('listDatabases', Meteor.default_connection._lastSessionId, function (err, result) {
            if (err || result.error) {
                Helper.showMeteorFuncError(err, result, "Couldn't fetch databases");
            }
            else {
                result.result.databases.sort(function (a, b) {
                    if (a.name < b.name)
                        return -1;
                    else if (a.name > b.name)
                        return 1;
                    else
                        return 0;
                });

                populateSwitchDatabaseTable(result.result.databases);
                Ladda.stopAll();
            }
        });

    },

    'click #btnConnectionList' () {
        if (!Session.get(Helper.strSessionConnection)) {
            populateConnectionsTable();

            $('#tblConnection').DataTable().$('tr.selected').removeClass('selected');
            $('#btnConnect').prop('disabled', true);
        }
    },

    'click #btnConnectSwitchedDatabase' () {
        let selector = $('#inputDatabaseNameToSwitch');
        if (!selector.val()) {
            toastr.error('Please enter a database name or choose one from the list');
            return;
        }

        Ladda.create(document.querySelector('#btnConnectSwitchedDatabase')).start();
        let connection = Connections.findOne({_id: Session.get(Helper.strSessionConnection)});
        connection.databaseName = selector.val();
        Meteor.call('saveConnection', connection);

        connect(false);
    },

    // Toggle left navigation
    'click #navbar-minimalize' (event) {
        event.preventDefault();

        let body = $('body');
        let sideMenu = $('#side-menu');
        const nav = $('.navbar-static-side');
        const pageWrapper = $('#page-wrapper');

        // Toggle special class
        body.toggleClass("mini-navbar");

        // Enable smoothly hide/show menu
        if (!body.hasClass('mini-navbar') || body.hasClass('body-small')) {
            // Hide menu in order to smoothly turn on when maximize menu
            sideMenu.hide();
            // For smoothly turn on menu
            setTimeout(function () {
                sideMenu.fadeIn(400);
            }, 200);
        } else if (body.hasClass('fixed-sidebar')) {
            sideMenu.hide();
            setTimeout(function () {
                sideMenu.fadeIn(400);
            }, 100);
        } else {
            // Remove all inline style from jquery fadeIn  to reset menu state
            sideMenu.removeAttr('style');
        }

        setTimeout(function () {
            nav.removeAttr('style');
            if (nav.css('display') === 'block') pageWrapper.css('margin', '0 0 0 ' + nav.width() + 'px');
            if (nav.css('display') === 'none') pageWrapper.css('margin', '0');
        }, 300);
    },

    'click #btnConnect' () {
        // loading button
        Ladda.create(document.querySelector('#btnConnect')).start();
        connect(false);
    },

    'click #btnDisconnect' (e) {
        e.preventDefault();

        Meteor.call('disconnect', Meteor.default_connection._lastSessionId);
        Helper.clearSessions();

        FlowRouter.go('/databaseStats');
    },

    'click #anchorTab1'  () {
        if (!$('#anchorTab1').attr('data-toggle')) {
            toastr.warning('Disable URI connection to use this tab');
        }
    },

    'click #anchorTab2'  () {
        if (!$('#anchorTab2').attr('data-toggle')) {
            toastr.warning('Disable URI connection to use this tab');
        }
    }
});<commit_msg>removed duplicate import<commit_after>import {Template} from "meteor/templating";
import {Meteor} from "meteor/meteor";
import {Session} from "meteor/session";
import {FlowRouter} from "meteor/kadira:flow-router";
import Helper from "/client/imports/helper";
import {Connections} from "/lib/imports/collections";
import {connect, populateConnectionsTable} from "/client/imports/views/layouts/top_navbar/connections/connections";
import "./top_navbar.html";

const toastr = require('toastr');
const Ladda = require('ladda');
const packageJson = require('/package.json');

require('datatables.net')(window, $);
require('datatables.net-buttons')(window, $);
require('datatables.net-responsive')(window, $);

require('datatables.net-bs')(window, $);
require('datatables.net-buttons-bs')(window, $);
require('datatables.net-responsive-bs')(window, $);

export const loadFile = function (currentVal, input, done, readAsString) {
    let fileInput = input.siblings('.bootstrap-filestyle').children('input');
    if (input[0].files.length == 0 && currentVal && fileInput.val()) {
        done(currentVal);
    }
    else if (input[0].files.length != 0) {
        const fileReader = new FileReader();
        fileReader.onload = function (file) {
            if (readAsString) done(file.target.result);
            else done(new Uint8Array(file.target.result));
        };

        if (readAsString) fileReader.readAsText(input[0].files[0], "UTF-8");
        else fileReader.readAsArrayBuffer(input[0].files[0]);
    } else {
        done([]);
    }
};

const init = function () {
    $(".filestyle").filestyle({});
    let selectorForSwitchDatabases = $('#tblSwitchDatabases');
    selectorForSwitchDatabases.find('tbody').on('click', 'tr', function () {
        let table = selectorForSwitchDatabases.DataTable();
        Helper.doTableRowSelectable(table, $(this));

        if (table.row(this).data()) {
            $('#inputDatabaseNameToSwitch').val(table.row(this).data().name);
        }
    });

    $('#versionText').html(packageJson.version);
};

const populateSwitchDatabaseTable = function (data) {
    let tblSwitchDatabases = $('#tblSwitchDatabases');

    tblSwitchDatabases.DataTable({
        responsive: true,
        destroy: true,
        data: data,
        columns: [
            {data: "name"}
        ],
        columnDefs: []
    }).draw();
};

Template.topNavbar.onRendered(function () {
    let connections = this.subscribe('connections');
    this.autorun(() => {
        if (connections.ready()) {
            init();
        }
    });
});

Template.topNavbar.events({
    'click #btnProceedImportExport'(e) {
        e.preventDefault();
        let laddaButton = Ladda.create(document.querySelector('#btnProceedImportExport'));
        let importInput = $('#inputImportBackupFile');

        if (importInput.val()) {
            laddaButton.start();
            loadFile(null, importInput, function (val) {
                Meteor.call('importMongoclient', val, function (err) {
                    if (err) {
                        toastr.error("Couldn't import: " + err.message);
                    } else {
                        toastr.success("Successfully imported from " + importInput.siblings('.bootstrap-filestyle').children('input').val());
                        $('#importExportMongoclientModal').modal('hide');
                    }

                    Ladda.stopAll();
                });
            }, true);
        }
    },

    'change .filestyle'(e) {
        let inputSelector = $('#' + e.currentTarget.id);
        let blob = inputSelector[0].files[0];
        let fileInput = inputSelector.siblings('.bootstrap-filestyle').children('input');

        if (blob) {
            fileInput.val(blob.name);
        } else {
            fileInput.val('');
        }
    },

    'click #btnRefreshCollections2'() {
        connect(true);
    },

    'click #btnExportMongoclient'(e) {
        e.preventDefault();
        window.open('exportMongoclient');
    },

    'click #btnImportMongoclient'(e) {
        e.preventDefault();
        let icon = $('#importExportMongoclientIcon');
        $('#importExportMongoclientTitle').text('Import Mongoclient Data');
        icon.addClass('fa-download');
        icon.removeClass('fa-upload');
        $('#btnProceedImportExport').text('Import');
        $('#frmImportMongoclient').show();
        $('#frmExportMongoclient').hide();
        $('#importExportMongoclientModal').modal('show');
    },

    'click #btnAboutMongoclient'(e) {
        e.preventDefault();
        $('#aboutModal').modal('show');
    },

    'click #btnSwitchDatabase'(e) {
        e.preventDefault();
        $('#switchDatabaseModal').modal('show');

        Ladda.create(document.querySelector('#btnConnectSwitchedDatabase')).start();

        Meteor.call('listDatabases', Meteor.default_connection._lastSessionId, function (err, result) {
            if (err || result.error) {
                Helper.showMeteorFuncError(err, result, "Couldn't fetch databases");
            }
            else {
                result.result.databases.sort(function (a, b) {
                    if (a.name < b.name)
                        return -1;
                    else if (a.name > b.name)
                        return 1;
                    else
                        return 0;
                });

                populateSwitchDatabaseTable(result.result.databases);
                Ladda.stopAll();
            }
        });

    },

    'click #btnConnectionList'() {
        if (!Session.get(Helper.strSessionConnection)) {
            populateConnectionsTable();

            $('#tblConnection').DataTable().$('tr.selected').removeClass('selected');
            $('#btnConnect').prop('disabled', true);
        }
    },

    'click #btnConnectSwitchedDatabase'() {
        let selector = $('#inputDatabaseNameToSwitch');
        if (!selector.val()) {
            toastr.error('Please enter a database name or choose one from the list');
            return;
        }

        Ladda.create(document.querySelector('#btnConnectSwitchedDatabase')).start();
        let connection = Connections.findOne({_id: Session.get(Helper.strSessionConnection)});
        connection.databaseName = selector.val();
        Meteor.call('saveConnection', connection);

        connect(false);
    },

    // Toggle left navigation
    'click #navbar-minimalize'(event) {
        event.preventDefault();

        let body = $('body');
        let sideMenu = $('#side-menu');
        const nav = $('.navbar-static-side');
        const pageWrapper = $('#page-wrapper');

        // Toggle special class
        body.toggleClass("mini-navbar");

        // Enable smoothly hide/show menu
        if (!body.hasClass('mini-navbar') || body.hasClass('body-small')) {
            // Hide menu in order to smoothly turn on when maximize menu
            sideMenu.hide();
            // For smoothly turn on menu
            setTimeout(function () {
                sideMenu.fadeIn(400);
            }, 200);
        } else if (body.hasClass('fixed-sidebar')) {
            sideMenu.hide();
            setTimeout(function () {
                sideMenu.fadeIn(400);
            }, 100);
        } else {
            // Remove all inline style from jquery fadeIn  to reset menu state
            sideMenu.removeAttr('style');
        }

        setTimeout(function () {
            nav.removeAttr('style');
            if (nav.css('display') === 'block') pageWrapper.css('margin', '0 0 0 ' + nav.width() + 'px');
            if (nav.css('display') === 'none') pageWrapper.css('margin', '0');
        }, 300);
    },

    'click #btnConnect'() {
        // loading button
        Ladda.create(document.querySelector('#btnConnect')).start();
        connect(false);
    },

    'click #btnDisconnect'(e) {
        e.preventDefault();

        Meteor.call('disconnect', Meteor.default_connection._lastSessionId);
        Helper.clearSessions();

        FlowRouter.go('/databaseStats');
    },

    'click #anchorTab1'() {
        if (!$('#anchorTab1').attr('data-toggle')) {
            toastr.warning('Disable URI connection to use this tab');
        }
    },

    'click #anchorTab2'() {
        if (!$('#anchorTab2').attr('data-toggle')) {
            toastr.warning('Disable URI connection to use this tab');
        }
    }
});<|endoftext|>