<commit_before>module.exports = {
  'rules': {
    // Prevent missing displayName in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md
    'react/display-name': 2,
    // Forbid certain propTypes (any, array, object)
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md
    'react/forbid-prop-types': [2, { 'forbid': ['any', 'array', 'object'] }],
    // Enforce or disallow spaces inside of curly braces in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md
    'react/jsx-curly-spacing': [2, 'never', { 'allowMultiline': true }],
    // Enforce or disallow spaces around equal signs in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-equals-spacing.md
    'react/jsx-equals-spacing': [2, 'never'],
    // Validate JSX indentation
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent.md
    'react/jsx-indent': [2, 2],
    // Validate JSX has key prop when in array or iterator
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md
    'react/jsx-key': 2,
    // Prevent duplicate props in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md
    'react/jsx-no-duplicate-props': 2,
    // Enforce PascalCase for user-defined JSX components
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md
    'react/jsx-pascal-case': 2,
    // Enforce props alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md
    'react/jsx-sort-props': [2, {
      'callbacksLast': true,
      'shorthandFirst': true
    }],
    // Validate spacing before closing bracket in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-space-before-closing.md
    'react/jsx-space-before-closing': [2, 'always'],
    // Prevent usage of dangerous JSX properties
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger.md
    'react/no-danger': 2,
    // Prevent direct mutation of this.state
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md
    'react/no-direct-mutation-state': 2,
    // Prevent usage of setState
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-set-state.md
    'react/no-set-state': 1,
    // Prevent using string references
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md
    'react/no-string-refs': 2,
    // Enforce propTypes declarations alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-prop-types.md
    'react/sort-prop-types': [2, {
      'requiredFirst': true
    }]
  }
};
<commit_msg>Remove `jsx-pascal-case` rule (in airbnb now)<commit_after>module.exports = {
  'rules': {
    // Prevent missing displayName in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md
    'react/display-name': 2,
    // Forbid certain propTypes (any, array, object)
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md
    'react/forbid-prop-types': [2, { 'forbid': ['any', 'array', 'object'] }],
    // Enforce or disallow spaces inside of curly braces in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md
    'react/jsx-curly-spacing': [2, 'never', { 'allowMultiline': true }],
    // Enforce or disallow spaces around equal signs in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-equals-spacing.md
    'react/jsx-equals-spacing': [2, 'never'],
    // Validate JSX indentation
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent.md
    'react/jsx-indent': [2, 2],
    // Validate JSX has key prop when in array or iterator
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md
    'react/jsx-key': 2,
    // Prevent duplicate props in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md
    'react/jsx-no-duplicate-props': 2,
    // Enforce props alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md
    'react/jsx-sort-props': [2, {
      'callbacksLast': true,
      'shorthandFirst': true
    }],
    // Validate spacing before closing bracket in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-space-before-closing.md
    'react/jsx-space-before-closing': [2, 'always'],
    // Prevent usage of dangerous JSX properties
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger.md
    'react/no-danger': 2,
    // Prevent direct mutation of this.state
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md
    'react/no-direct-mutation-state': 2,
    // Prevent usage of setState
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-set-state.md
    'react/no-set-state': 1,
    // Prevent using string references
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md
    'react/no-string-refs': 2,
    // Enforce propTypes declarations alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-prop-types.md
    'react/sort-prop-types': [2, {
      'requiredFirst': true
    }]
  }
};
<|endoftext|>


<commit_before>var JsonDB          = require('node-json-db');

var DbHelper        = require('./DbHelper.js'),
    Help            = require('./Help.js'),
    Urban           = require('./Urban.js'),
    Lastfm          = require('./Lastfm.js'),
    NowPlaying      = require('./NowPlaying.js'),
    Poll            = require('./Poll.js'),
    Roll            = require('./Roll.js'),
    DadJoke         = require('./DadJoke.js'),
    OnyxiaReset     = require('./OnyxiaReset.js'),
    CustomCmd       = require('./CustomCmd.js'),
    WarcraftLogs    = require('./WarcraftLogs.js');

var HxBot = function() {
    this.config     = require('../config.json');
    this.DbHelper   = new DbHelper;
    this.Help       = new Help;
    this.Urban      = new Urban;
    this.Lastfm     = new Lastfm;
    this.NowPlaying = new NowPlaying;
    this.Poll       = new Poll;
    this.Roll       = new Roll;
    this.DadJoke    = new DadJoke;
    this.OnyxiaReset= new OnyxiaReset;
    this.CustomCmd  = new CustomCmd;
    this.Logs       = new WarcraftLogs;
}

HxBot.prototype.guildMemberAdd = function (member) {
    let guild = member.guild;
    //guild.defaultChannel.sendMessage(`${member.user} joined ${member.guild} :ok_hand: Welcome!`).catch(console.error);
}

HxBot.prototype.guildMemberRemove = function(member) {
    let guild = member.guild;
    //guild.defaultChannel.sendMessage(`${member.user} left ${member.guild} :cry:`).catch(console.error);
};

HxBot.prototype.getCommand  = function(message,callback)
{
    if (typeof this.config.commands !== 'undefined' && this.config.commands.length > 0){
        if(message.content.substring(0,1) != this.config.commandPrefix){
            return false;
        }
        for(var i = 0; i != this.config.commands.length; i++) {
            var command = this.config.commands[i];
            if (message.content.substring(1,command.cmd.length+1) == command.cmd) {
                return command.callback;
                break;
            }
        }
        return false;
    }else{
        console.log('Error reading commands from config.json');
        return false;
    }
}

HxBot.prototype.runCommand = function(message, command, callback)
{
    if (command != 0) {
        this[command].Message(command, message, callback);
    }
}

HxBot.prototype.checkMessageForEasterEggs = function(message)
{
    var easterEggs = [
        {
            pattern:/^a+yy+$/i,
            response: 'lmao'
        },
        {
            pattern: /^g+oo+n+\!*$/i,
            response: 'SQUA'+'A'.repeat(message.content.length-4)+'D'
        },
        {
            pattern: /i+['´`]?m+ g+a+y+/i,
            response: `${message.author.username} has officially come out of the closet! Rejoice!`
        }
    ];
    for (var i = easterEggs.length - 1; i >= 0; i--) {
        var regex = new RegExp(easterEggs[i].pattern);
        if(regex.test(message.content))
        {
            message.channel.send(easterEggs[i].response);
        }
    }
    // Debug command to check ping
    if(message.content == this.config.commandPrefix+'ping')
    {
        message.channel.send('pong..').then(sent => {
            sent.edit(`Ping is **${sent.createdTimestamp - message.createdTimestamp}ms**`);
        });
    } else {
        if (message.content[0] == this.config.commandPrefix) {
            var db = new JsonDB('database', true, true);
            var cmd = message.content.substring(1).trim();
            switch (message.channel.type) {
                case 'text':
                    var id = message.guild.id;
                    break;
                case 'dm':
                case 'group':
                    var id = message.channel.id;
                    break;
            }
            try {
                var res = db.getData(`/cmds/${id}/${cmd}`);
                message.channel.send(res);
            } catch(e) {
                console.log(`/cmds/${id}/${cmd} - Invalid command..`);
            }
        }
    }
}

module.exports = HxBot;
<commit_msg>fixed a bug where sometimes we call string.repeat(0)<commit_after>var JsonDB          = require('node-json-db');

var DbHelper        = require('./DbHelper.js'),
    Help            = require('./Help.js'),
    Urban           = require('./Urban.js'),
    Lastfm          = require('./Lastfm.js'),
    NowPlaying      = require('./NowPlaying.js'),
    Poll            = require('./Poll.js'),
    Roll            = require('./Roll.js'),
    DadJoke         = require('./DadJoke.js'),
    OnyxiaReset     = require('./OnyxiaReset.js'),
    CustomCmd       = require('./CustomCmd.js'),
    WarcraftLogs    = require('./WarcraftLogs.js');
    SongFlower    = require('./SongFlower.js');

var HxBot = function() {
    this.config     = require('../config.json');
    this.DbHelper   = new DbHelper;
    this.Help       = new Help;
    this.Urban      = new Urban;
    this.Lastfm     = new Lastfm;
    this.NowPlaying = new NowPlaying;
    this.Poll       = new Poll;
    this.Roll       = new Roll;
    this.DadJoke    = new DadJoke;
    this.OnyxiaReset= new OnyxiaReset;
    this.CustomCmd  = new CustomCmd;
    this.Logs       = new WarcraftLogs;
    this.SongFlower = new SongFlower;
}

HxBot.prototype.guildMemberAdd = function (member) {
    let guild = member.guild;
    //guild.defaultChannel.sendMessage(`${member.user} joined ${member.guild} :ok_hand: Welcome!`).catch(console.error);
}

HxBot.prototype.guildMemberRemove = function(member) {
    let guild = member.guild;
    //guild.defaultChannel.sendMessage(`${member.user} left ${member.guild} :cry:`).catch(console.error);
};

HxBot.prototype.getCommand  = function(message,callback)
{
    if (typeof this.config.commands !== 'undefined' && this.config.commands.length > 0){
        if(message.content.substring(0,1) != this.config.commandPrefix){
            return false;
        }
        for(var i = 0; i != this.config.commands.length; i++) {
            var command = this.config.commands[i];
            if (message.content.substring(1,command.cmd.length+1) == command.cmd) {
                return command.callback;
                break;
            }
        }
        return false;
    }else{
        console.log('Error reading commands from config.json');
        return false;
    }
}

HxBot.prototype.runCommand = function(message, command, callback)
{
    if (command != 0) {
        this[command].Message(command, message, callback);
    }
}

HxBot.prototype.checkMessageForEasterEggs = function(message)
{
    var easterEggs = [
        {
            pattern:/^a+yy+$/i,
            response: 'lmao'
        },
        {
            pattern: /^g+oo+n+\!*$/i,
            response: 'SQUA'+'A'.repeat(Math.max(message.content.length-4, 1))+'D'
        },
        {
            pattern: /i+['´`]?m+ g+a+y+/i,
            response: `${message.author.username} has officially come out of the closet! Rejoice!`
        }
    ];
    for (var i = easterEggs.length - 1; i >= 0; i--) {
        var regex = new RegExp(easterEggs[i].pattern);
        if(regex.test(message.content))
        {
            message.channel.send(easterEggs[i].response);
        }
    }
    // Debug command to check ping
    if(message.content == this.config.commandPrefix+'ping')
    {
        message.channel.send('pong..').then(sent => {
            sent.edit(`Ping is **${sent.createdTimestamp - message.createdTimestamp}ms**`);
        });
    } else {
        if (message.content[0] == this.config.commandPrefix) {
            var db = new JsonDB('database', true, true);
            var cmd = message.content.substring(1).trim();
            switch (message.channel.type) {
                case 'text':
                    var id = message.guild.id;
                    break;
                case 'dm':
                case 'group':
                    var id = message.channel.id;
                    break;
            }
            try {
                var res = db.getData(`/cmds/${id}/${cmd}`);
                message.channel.send(res);
            } catch(e) {
                console.log(`/cmds/${id}/${cmd} - Invalid command..`);
            }
        }
    }
}

module.exports = HxBot;
<|endoftext|>


<commit_before>var net = require('net');

var User = require('./iBot-User.js').User;

exports.Server = function(host, port, nick, ident, pass)
{
	this.host = host;
	this.port = port;
	this.nick = nick;
	this.ident = ident;
	this.pass = pass;

	this.users = {};
	this.channels = {};

	this.user = new User(nick, ident, '', 'iBot');
	this.users[nick] = this.user;

	this.onConnect = function()
	{

	}

	this.connect = function()
	{
		this.client = new net.Socket();

		this.client.on('data', this.onData);
		this.client.on('close', this.onClose);

		this.client.setEncoding('utf8');
		this.client.setNoDelay();
		this.client.connect(port, host, this.onConnect);
	}
}
<commit_msg>Wrote Server.send() and Server.sendSilent() functions.<commit_after>var net = require('net');

var User = require('./iBot-User.js').User;

exports.Server = function(host, port, nick, ident, pass)
{
	this.host = host;
	this.port = port;
	this.nick = nick;
	this.ident = ident;
	this.pass = pass;

	this.users = {};
	this.channels = {};

	this.user = new User(nick, ident, '', 'iBot');
	this.users[nick] = this.user;

	this.onConnect = function()
	{

	}

	this.connect = function()
	{
		this.client = new net.Socket();

		this.client.on('data', this.onData);
		this.client.on('close', this.onClose);

		this.client.setEncoding('utf8');
		this.client.setNoDelay();
		this.client.connect(port, host, this.onConnect);
	}

	this.send = function(data)
	{
		this.sendSilent(data);
	}

	this.sendSilent = function(data)
	{
		this.client.write(data + '\r\n');
	}
}
<|endoftext|>


<commit_before>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import { API_HOST } from '../config'
import ApiClient from '../api/client'
import { getStore } from '../store';
import {
  addError, addMessage, removeAllMessages,
  addUser, addPost, addPostToRiver, setCurrentUser, removePost,
  setLikes, setFavourites, setPostsToLikesRiver,
  setUserTags, setSchools
} from '../actions';

const client = new ApiClient(API_HOST);

export async function likePost(current_user_id, post_id) {
  try {
    let responseBody = await client.like(post_id);

    if (responseBody.success) {
      getStore().dispatch(setLikes(current_user_id, responseBody.likes, post_id, responseBody.likers));
      syncLikedPosts(current_user_id);
    } else {
      getStore().dispatch(addError('internal server error. please try later'));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function unlikePost(current_user_id, post_id) {
  try {
    let responseBody = await client.unlike(post_id);

    if (responseBody.success) {
      getStore().dispatch(setLikes(current_user_id, responseBody.likes, post_id, responseBody.likers));
      syncLikedPosts(current_user_id);
    } else {
      getStore().dispatch(addError('internal server error. please try later'));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function syncLikedPosts() {
  try {
    let likedPosts = client.userLikedPosts();
    getStore().dispatch(setPostsToLikesRiver(await likedPosts));
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function favPost(current_user_id, post_id) {
  try {
    let responseBody = await client.fav(post_id);

    if (responseBody.success) {
      getStore().dispatch(setFavourites(current_user_id, responseBody.favourites, post_id, responseBody.favourers));
    } else {
      getStore().dispatch(addError('internal server error. please try later'));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function unfavPost(current_user_id, post_id) {
  try {
    let responseBody = await client.unfav(post_id);

    if (responseBody.success) {
      getStore().dispatch(setFavourites(current_user_id, responseBody.favourites, post_id, responseBody.favourers));
    } else {
      getStore().dispatch(addError('internal server error. please try later'));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function createPost(type, data) {
  try {
    let result = await client.createPost(type, data);
    getStore().dispatch(addPostToRiver(result));

    let userTags = client.userTags();
    getStore().dispatch(setUserTags(await userTags));
  } catch (e) {
    console.log(e)
    console.log(e.stack)

    getStore().dispatch(addError(e.message));
  }
}

export async function updateUserInfo(user) {
  try {
    let res = await client.updateUser(user);

    if ('user' in res) {
      getStore().dispatch(addMessage('Saved successfully'));
      getStore().dispatch(addUser(res.user));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function changePassword(old_password, new_password1, new_password2)
{
  if (old_password.trim() == '' || new_password1.trim() == '' || new_password2.trim() == '') {
    getStore().dispatch(addError('some of the fields are empty'));
    return;
  }

  if (new_password1 !== new_password2) {
    getStore().dispatch(addError('passwords do not match'));
    return;
  }

  try {
    let res = await client.changePassword(old_password, new_password1);

    if ('success' in res && res.success === true) {
      getStore().dispatch(addMessage('Password is changed successfully'));
    }
  } catch (e) {
    if (('body' in e.response) && ('error' in e.response.body)) {
      getStore().dispatch(addError(e.response.body.error));
    } else {
      getStore().dispatch(addError(e.message));
    }
  }
}

export async function followUser(user) {
  try {
    let res = await client.follow(user.username);

    if ('user1' in res) {
      getStore().dispatch(addUser(res.user1));
      getStore().dispatch(addUser(res.user2));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function unfollowUser(user) {
  try {
    let res = await client.unfollow(user.username);

    if ('user1' in res) {
      getStore().dispatch(addUser(res.user1));
      getStore().dispatch(addUser(res.user2));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function login(username, password) {
  getStore().dispatch(removeAllMessages());

  try {
    let result = await client.login({username, password});

    if (result.success) {
      let user = result.user;
      getStore().dispatch(setCurrentUser(user));
      getStore().dispatch(setLikes(user.id, user.liked_posts.map(like => like.post_id)));
      getStore().dispatch(setFavourites(user.id, user.favourited_posts.map(fav => fav.post_id)));
    } else {
      getStore().dispatch(setCurrentUser(null));
      getStore().dispatch(addError('Invalid username or password'));
    }
  } catch (e) {
    getStore().dispatch(setCurrentUser(null));
    getStore().dispatch(addError('Invalid username or password'));
  }
}

export async function registerUser(username, password, email, firstName, lastName) {
  getStore().dispatch(removeAllMessages());

  // FIXME: disable form
  try {
    let result = await client.registerUser({username, password, email, firstName, lastName});

    if ('error' in result) {
      // FIXME: enable form again
      getStore().dispatch(addError(result.error));
      return;
    }
  } catch (e) {
    // FIXME: enable form again

    if (e.response && ('error' in e.response.body)) {
      // FIXME: enable form again
      getStore().dispatch(addError(e.response.body.error));
      return;
    } else {
      console.log(e)
      console.log(e.stack)
      getStore().dispatch(addError('Server seems to have problems. Retry later, please'));
      return;
    }
  }

  getStore().dispatch(addMessage('User is registered successfully'));
}

export async function deletePost(post_uuid) {
  await client.deletePost(post_uuid);
  getStore().dispatch(removePost(post_uuid));
}

export async function updatePost(post_uuid, post_fields) {
  try {
    let result = await client.updatePost(post_uuid, post_fields);
    getStore().dispatch(addPost(result));

    return result;
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function loadSchools() {
  try {
    let result = await client.schools();
    getStore().dispatch(setSchools(result));

    return result;
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}
<commit_msg>fix clientside auth<commit_after>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import { API_HOST } from '../config'
import ApiClient from '../api/client'
import { getStore } from '../store';
import {
  addError, addMessage, removeAllMessages,
  addUser, addPost, addPostToRiver, setCurrentUser, removePost,
  setLikes, setFavourites, setPostsToLikesRiver,
  setUserTags, setSchools
} from '../actions';

const client = new ApiClient(API_HOST);

export async function likePost(current_user_id, post_id) {
  try {
    let responseBody = await client.like(post_id);

    if (responseBody.success) {
      getStore().dispatch(setLikes(current_user_id, responseBody.likes, post_id, responseBody.likers));
      syncLikedPosts(current_user_id);
    } else {
      getStore().dispatch(addError('internal server error. please try later'));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function unlikePost(current_user_id, post_id) {
  try {
    let responseBody = await client.unlike(post_id);

    if (responseBody.success) {
      getStore().dispatch(setLikes(current_user_id, responseBody.likes, post_id, responseBody.likers));
      syncLikedPosts(current_user_id);
    } else {
      getStore().dispatch(addError('internal server error. please try later'));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function syncLikedPosts() {
  try {
    let likedPosts = client.userLikedPosts();
    getStore().dispatch(setPostsToLikesRiver(await likedPosts));
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function favPost(current_user_id, post_id) {
  try {
    let responseBody = await client.fav(post_id);

    if (responseBody.success) {
      getStore().dispatch(setFavourites(current_user_id, responseBody.favourites, post_id, responseBody.favourers));
    } else {
      getStore().dispatch(addError('internal server error. please try later'));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function unfavPost(current_user_id, post_id) {
  try {
    let responseBody = await client.unfav(post_id);

    if (responseBody.success) {
      getStore().dispatch(setFavourites(current_user_id, responseBody.favourites, post_id, responseBody.favourers));
    } else {
      getStore().dispatch(addError('internal server error. please try later'));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function createPost(type, data) {
  try {
    let result = await client.createPost(type, data);
    getStore().dispatch(addPostToRiver(result));

    let userTags = client.userTags();
    getStore().dispatch(setUserTags(await userTags));
  } catch (e) {
    console.log(e)
    console.log(e.stack)

    getStore().dispatch(addError(e.message));
  }
}

export async function updateUserInfo(user) {
  try {
    let res = await client.updateUser(user);

    if ('user' in res) {
      getStore().dispatch(addMessage('Saved successfully'));
      getStore().dispatch(addUser(res.user));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function changePassword(old_password, new_password1, new_password2)
{
  if (old_password.trim() == '' || new_password1.trim() == '' || new_password2.trim() == '') {
    getStore().dispatch(addError('some of the fields are empty'));
    return;
  }

  if (new_password1 !== new_password2) {
    getStore().dispatch(addError('passwords do not match'));
    return;
  }

  try {
    let res = await client.changePassword(old_password, new_password1);

    if ('success' in res && res.success === true) {
      getStore().dispatch(addMessage('Password is changed successfully'));
    }
  } catch (e) {
    if (('body' in e.response) && ('error' in e.response.body)) {
      getStore().dispatch(addError(e.response.body.error));
    } else {
      getStore().dispatch(addError(e.message));
    }
  }
}

export async function followUser(user) {
  try {
    let res = await client.follow(user.username);

    if ('user1' in res) {
      getStore().dispatch(addUser(res.user1));
      getStore().dispatch(addUser(res.user2));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function unfollowUser(user) {
  try {
    let res = await client.unfollow(user.username);

    if ('user1' in res) {
      getStore().dispatch(addUser(res.user1));
      getStore().dispatch(addUser(res.user2));
    }
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function login(username, password) {
  getStore().dispatch(removeAllMessages());

  try {
    let result = await client.login({username, password});

    if (result.success) {
      let user = result.user;
      getStore().dispatch(setCurrentUser(user));
      getStore().dispatch(setLikes(user.id, user.liked_posts.map(like => like.id)));
      getStore().dispatch(setFavourites(user.id, user.favourited_posts.map(fav => fav.id)));
    } else {
      getStore().dispatch(setCurrentUser(null));
      getStore().dispatch(addError('Invalid username or password'));
    }
  } catch (e) {
    getStore().dispatch(setCurrentUser(null));
    getStore().dispatch(addError('Invalid username or password'));
  }
}

export async function registerUser(username, password, email, firstName, lastName) {
  getStore().dispatch(removeAllMessages());

  // FIXME: disable form
  try {
    let result = await client.registerUser({username, password, email, firstName, lastName});

    if ('error' in result) {
      // FIXME: enable form again
      getStore().dispatch(addError(result.error));
      return;
    }
  } catch (e) {
    // FIXME: enable form again

    if (e.response && ('error' in e.response.body)) {
      // FIXME: enable form again
      getStore().dispatch(addError(e.response.body.error));
      return;
    } else {
      console.log(e)
      console.log(e.stack)
      getStore().dispatch(addError('Server seems to have problems. Retry later, please'));
      return;
    }
  }

  getStore().dispatch(addMessage('User is registered successfully'));
}

export async function deletePost(post_uuid) {
  await client.deletePost(post_uuid);
  getStore().dispatch(removePost(post_uuid));
}

export async function updatePost(post_uuid, post_fields) {
  try {
    let result = await client.updatePost(post_uuid, post_fields);
    getStore().dispatch(addPost(result));

    return result;
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}

export async function loadSchools() {
  try {
    let result = await client.schools();
    getStore().dispatch(setSchools(result));

    return result;
  } catch (e) {
    getStore().dispatch(addError(e.message));
  }
}
<|endoftext|>


<commit_before>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var NativeModule = require('native_module'),
	assets = kroll.binding('assets'),
	path = require('path'),
	Script = kroll.binding('evals').Script,
	runInThisContext = require('vm').runInThisContext,
	bootstrap = require('bootstrap'),
	invoker = require('invoker');

var TAG = "Module";

function Module(id, parent, context) {
	this.id = id;
	this.exports = {};
	this.parent = parent;
	this.context = context;

	this.filename = null;
	this.loaded = false;
	this.exited = false;
	this.children = [];
	this.wrapperCache = {};
}
kroll.Module = module.exports = Module;

Module.cache = [];
Module.main = null;
Module.paths = [ 'Resources/' ];
Module.wrap = NativeModule.wrap;

Module.runModule = function (source, filename, activityOrService) {
	var id = filename;
	if (!Module.main) {
		id = ".";
	}

	var module;
	var isService = (activityOrService instanceof Titanium.Service);

	if (isService) {
		module = new Module(id, null, {
			currentService: activityOrService,
			currentActivity: null,
			currentWindow: null
		});
	} else {
		module = new Module(id, null, {
			currentService: null,
			currentActivity: activityOrService,
			currentWindow: activityOrService ? activityOrService.window : null
		});
	}

	if (!Module.main) {
		Module.main = module;
	}

	module.load(filename, source)
	return module;
}

// Run a module as the main entry point.
Module.runMainModule = function (source, filename) {
	var mainModule = Module.main = new Module('.');
	mainModule.load(filename, source);
	return true;
}

// Attempts to load the module. If no file is found
// with the provided name an exception will be thrown.
// Once the contents of the file are read, it is ran
// in the current context. A sandbox is created by
// executing the code inside a wrapper function.
// This provides a speed boost vs creating a new context.
//
// Returns the exports object of the loaded module if successful.
Module.prototype.load = function (filename, source) {
	if (this.loaded) {
		throw new Error("Module already loaded.");
	}

	this.filename = filename;
	this.paths = [path.dirname(filename)];

	if (!source) {
		source = assets.readAsset(filename);
	}

	this._runScript(source, filename.replace("Resources/", ""));

	this.loaded = true;
}

// Generates a context-specific module wrapper, and wraps
// each invocation API in an external (3rd party) module
// See invoker.js for more info
Module.prototype.createModuleWrapper = function(externalModule, sourceUrl) {

	// The module wrapper forwards on using the original as a prototype
	function ModuleWrapper() {}
	ModuleWrapper.prototype = externalModule;

	var wrapper = new ModuleWrapper();
	var invocationAPIs = externalModule.invocationAPIs;
	var invocationsLen = invocationAPIs.length;

	for (var j = 0; j < invocationsLen; ++j) {
		var api = invocationAPIs[j].api;
		var delegate = externalModule[api];
		if (!delegate) {
			continue;
		}

		wrapper[api] = invoker.createInvoker(externalModule, delegate, new kroll.ScopeVars({
			sourceUrl: sourceUrl,
			module: this
		}));
	}

	return wrapper;
}

// Loads a native / external (3rd party) module
Module.prototype.loadExternalModule = function(id, externalBinding, context) {

	var sourceUrl = context === undefined ? "app://app.js" : context.sourceUrl;
	var externalModule;

	if (kroll.runtime === "rhino") {
		// TODO -- add support for context specific invokers in Rhino
		var bindingKey = Object.keys(externalBinding)[0];
		if (bindingKey) {
			externalModule = externalBinding[bindingKey];
		}

		return externalModule;

	} else {
		externalModule = Module.cache[id];

		if (!externalModule) {
			// Get the compiled bootstrap JS
			var source = externalBinding.bootstrap;

			// Load the native module's bootstrap JS
			var module = new Module(id, this, context);
			module.load(id + "/bootstrap.js", source);

			// Bootstrap and load the module using the native bindings
			var result = module.exports.bootstrap(externalBinding);

			// Cache the external module instance
			externalModule = Module.cache[id] = result;
		}

		if (externalModule) {
			// We cache each context-specific module wrapper
			// on the parent module, rather than in the Module.cache
			var wrapper = this.wrapperCache[id];
			if (wrapper) {
				return wrapper;
			}

			wrapper = this.createModuleWrapper(externalModule, sourceUrl);
			this.wrapperCache[id] = wrapper;

			return wrapper;
		}
	}

	kroll.log(TAG, "Unable to load external module: " + id);

}

// Require another module as a child of this module.
// This parent module's path is appended to the search paths
// when loading the child. Returns the exports object
// of the child module.
Module.prototype.require = function (request, context, useCache) {
	useCache = useCache === undefined ? true : useCache;

	// Delegate native module requests.
	if (NativeModule.exists(request)) {
		if (kroll.DBG) {
			kroll.log(TAG, 'Found native module: "' + request + '"');
		}
		return NativeModule.require(request);
	}

	// get external binding (for external / 3rd party modules)
	var externalBinding = kroll.externalBinding(request);

	if (externalBinding) {
		return this.loadExternalModule(request, externalBinding, context);
	}

	var resolved = resolveFilename(request, this);
	var id = resolved[0];
	var filename = resolved[1];

	if (kroll.DBG) {
		kroll.log(TAG, 'Loading module: ' + request + ' -> ' + filename);
	}

	if (useCache) {
		var cachedModule = Module.cache[filename];
		if (cachedModule) {
			return cachedModule.exports;
		}
	}

	// Create and attempt to load the module.
	var module = new Module(id, this, context);
	module.load(filename);

	if (useCache) {
		// Cache the module for future requests.
		Module.cache[filename] = module;
	}

	return module.exports;
}

// Setup a sandbox and run the module's script inside it.
// Returns the result of the executed script.
Module.prototype._runScript = function (source, filename) {
	var self = this;
	var url = "app://" + filename;

	function require(path, context) {
		return self.require(path, context);
	}
	require.main = Module.main;

	if (self.id == '.') {
		global.require = require;
		Titanium.Android.currentActivity = self.context.currentActivity;

		return runInThisContext(source, filename, true);
	}

	// Create context-bound modules.
	var context = self.context || {};
	context.sourceUrl = url;
	context.module = this;

	// Create a "context global" that's specific to each module
	var contextGlobal = context.global = {
		exports: this.exports,
		require: require,
		module: this,
		__filename: filename,
		__dirname: path.dirname(filename),
		kroll: kroll
	};
	contextGlobal.global = contextGlobal;

	var ti = new Titanium.Wrapper(context);
	contextGlobal.Ti = contextGlobal.Titanium = ti;

	// This function is called by the context when it is finished initializing
	// the builtin Javascript APIs
	function initContext(ctx, contextGlobal) {
		// Bootstrap Titanium global APIs onto the new context global
		bootstrap.bootstrapGlobals(contextGlobal, Titanium);
	}

	// We initialize the context with the standard Javascript APIs and globals first before running the script
	var newContext = context.global = ti.global = Script.createContext(contextGlobal, initContext);

	if (kroll.runtime == "rhino") {
		// The Rhino version of this API takes a custom global object but uses the same Rhino "Context".
		// It's not possible to create more than 1 Context per thread in Rhino, so contextGlobal
		// is essentially a detached global object that mimics a new context.
		return runInThisContext(source, filename, true, newContext);

	} else {
		// The V8 version of this API creates a brand new V8 top-level context that's associated
		// with a new global object. Script.createContext copies all of our context-specific data
		// into a new ContextWrapper that doubles as the global object for the context itself.
		kroll.moduleContexts.push(newContext);
		return Script.runInContext(source, newContext, filename, true);
	}
}

// Determine the paths where the requested module could live.
// Returns [id, paths]  where id is the module ID and paths
// is the list of path names.
function resolveLookupPaths(request, parentModule) {

	// "absolute" in Titanium is relative to the Resources folder
	if (request.charAt(0) === '/') {
		request = request.substring(1);
	}

	var start = request.substring(0, 2);
	if (start !== './' && start !== '..') {
		var paths = Module.paths;
		if (parentModule) {
			if (!parentModule.paths) {
				parentModule.paths = [];
			}
			paths = parentModule.paths.concat(paths);
		}
		return [request, paths];
	}

	// Get the path to the parent module. If the parent
	// is an index file, its ID is already the directory path.
	// Ex: path.id = "a/" if index
	//     path.id = "a/b" if non-index
	var isIndex = /^index\.\w+?$/.test(path.basename(parentModule.filename));
	var parentIdPath = isIndex ? parentModule.id : path.dirname(parentModule.id);

	var id = path.resolve(parentIdPath, request);

	// make sure require('./path') and require('path') get distinct ids, even
	// when called from the toplevel js file
	if (parentIdPath === '.' && id.indexOf('/') === -1) {
		id = './' + id;
	}

	// The module ID is resolved now, so we use the root "Module.paths" as the lookup base
	return [id, Module.paths];
}

// Determine the filename that contains the request
// module's source code. If no file is found an exception
// will be thrown.
function resolveFilename(request, parentModule) {

	var resolvedModule = resolveLookupPaths(request, parentModule);
	var id = resolvedModule[0];
	var paths = resolvedModule[1];

	// Try each possible path where the module's source file
	// could be located.
	for (var i = 0, pathCount = paths.length; i < pathCount; ++i) {
		var filename = path.resolve(paths[i], id) + '.js';
		if (filenameExists(filename)) {
			return [id, filename];
		}
	}

	throw new Error("Requested module not found: " + request);
}

var fileIndex;

function filenameExists(filename) {
	if (!fileIndex) {
		var json = assets.readAsset("index.json");
		fileIndex = JSON.parse(json);
	}

	return filename in fileIndex;
}

<commit_msg>[TIMOB-6550] Do not check native module from require.<commit_after>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var NativeModule = require('native_module'),
	assets = kroll.binding('assets'),
	path = require('path'),
	Script = kroll.binding('evals').Script,
	runInThisContext = require('vm').runInThisContext,
	bootstrap = require('bootstrap'),
	invoker = require('invoker');

var TAG = "Module";

function Module(id, parent, context) {
	this.id = id;
	this.exports = {};
	this.parent = parent;
	this.context = context;

	this.filename = null;
	this.loaded = false;
	this.exited = false;
	this.children = [];
	this.wrapperCache = {};
}
kroll.Module = module.exports = Module;

Module.cache = [];
Module.main = null;
Module.paths = [ 'Resources/' ];
Module.wrap = NativeModule.wrap;

Module.runModule = function (source, filename, activityOrService) {
	var id = filename;
	if (!Module.main) {
		id = ".";
	}

	var module;
	var isService = (activityOrService instanceof Titanium.Service);

	if (isService) {
		module = new Module(id, null, {
			currentService: activityOrService,
			currentActivity: null,
			currentWindow: null
		});
	} else {
		module = new Module(id, null, {
			currentService: null,
			currentActivity: activityOrService,
			currentWindow: activityOrService ? activityOrService.window : null
		});
	}

	if (!Module.main) {
		Module.main = module;
	}

	module.load(filename, source)
	return module;
}

// Run a module as the main entry point.
Module.runMainModule = function (source, filename) {
	var mainModule = Module.main = new Module('.');
	mainModule.load(filename, source);
	return true;
}

// Attempts to load the module. If no file is found
// with the provided name an exception will be thrown.
// Once the contents of the file are read, it is ran
// in the current context. A sandbox is created by
// executing the code inside a wrapper function.
// This provides a speed boost vs creating a new context.
//
// Returns the exports object of the loaded module if successful.
Module.prototype.load = function (filename, source) {
	if (this.loaded) {
		throw new Error("Module already loaded.");
	}

	this.filename = filename;
	this.paths = [path.dirname(filename)];

	if (!source) {
		source = assets.readAsset(filename);
	}

	this._runScript(source, filename.replace("Resources/", ""));

	this.loaded = true;
}

// Generates a context-specific module wrapper, and wraps
// each invocation API in an external (3rd party) module
// See invoker.js for more info
Module.prototype.createModuleWrapper = function(externalModule, sourceUrl) {

	// The module wrapper forwards on using the original as a prototype
	function ModuleWrapper() {}
	ModuleWrapper.prototype = externalModule;

	var wrapper = new ModuleWrapper();
	var invocationAPIs = externalModule.invocationAPIs;
	var invocationsLen = invocationAPIs.length;

	for (var j = 0; j < invocationsLen; ++j) {
		var api = invocationAPIs[j].api;
		var delegate = externalModule[api];
		if (!delegate) {
			continue;
		}

		wrapper[api] = invoker.createInvoker(externalModule, delegate, new kroll.ScopeVars({
			sourceUrl: sourceUrl,
			module: this
		}));
	}

	return wrapper;
}

// Loads a native / external (3rd party) module
Module.prototype.loadExternalModule = function(id, externalBinding, context) {

	var sourceUrl = context === undefined ? "app://app.js" : context.sourceUrl;
	var externalModule;

	if (kroll.runtime === "rhino") {
		// TODO -- add support for context specific invokers in Rhino
		var bindingKey = Object.keys(externalBinding)[0];
		if (bindingKey) {
			externalModule = externalBinding[bindingKey];
		}

		return externalModule;

	} else {
		externalModule = Module.cache[id];

		if (!externalModule) {
			// Get the compiled bootstrap JS
			var source = externalBinding.bootstrap;

			// Load the native module's bootstrap JS
			var module = new Module(id, this, context);
			module.load(id + "/bootstrap.js", source);

			// Bootstrap and load the module using the native bindings
			var result = module.exports.bootstrap(externalBinding);

			// Cache the external module instance
			externalModule = Module.cache[id] = result;
		}

		if (externalModule) {
			// We cache each context-specific module wrapper
			// on the parent module, rather than in the Module.cache
			var wrapper = this.wrapperCache[id];
			if (wrapper) {
				return wrapper;
			}

			wrapper = this.createModuleWrapper(externalModule, sourceUrl);
			this.wrapperCache[id] = wrapper;

			return wrapper;
		}
	}

	kroll.log(TAG, "Unable to load external module: " + id);

}

// Require another module as a child of this module.
// This parent module's path is appended to the search paths
// when loading the child. Returns the exports object
// of the child module.
Module.prototype.require = function (request, context, useCache) {
	useCache = useCache === undefined ? true : useCache;

	// get external binding (for external / 3rd party modules)
	var externalBinding = kroll.externalBinding(request);

	if (externalBinding) {
		return this.loadExternalModule(request, externalBinding, context);
	}

	var resolved = resolveFilename(request, this);
	var id = resolved[0];
	var filename = resolved[1];

	if (kroll.DBG) {
		kroll.log(TAG, 'Loading module: ' + request + ' -> ' + filename);
	}

	if (useCache) {
		var cachedModule = Module.cache[filename];
		if (cachedModule) {
			return cachedModule.exports;
		}
	}

	// Create and attempt to load the module.
	var module = new Module(id, this, context);
	module.load(filename);

	if (useCache) {
		// Cache the module for future requests.
		Module.cache[filename] = module;
	}

	return module.exports;
}

// Setup a sandbox and run the module's script inside it.
// Returns the result of the executed script.
Module.prototype._runScript = function (source, filename) {
	var self = this;
	var url = "app://" + filename;

	function require(path, context) {
		return self.require(path, context);
	}
	require.main = Module.main;

	if (self.id == '.') {
		global.require = require;
		Titanium.Android.currentActivity = self.context.currentActivity;

		return runInThisContext(source, filename, true);
	}

	// Create context-bound modules.
	var context = self.context || {};
	context.sourceUrl = url;
	context.module = this;

	// Create a "context global" that's specific to each module
	var contextGlobal = context.global = {
		exports: this.exports,
		require: require,
		module: this,
		__filename: filename,
		__dirname: path.dirname(filename),
		kroll: kroll
	};
	contextGlobal.global = contextGlobal;

	var ti = new Titanium.Wrapper(context);
	contextGlobal.Ti = contextGlobal.Titanium = ti;

	// This function is called by the context when it is finished initializing
	// the builtin Javascript APIs
	function initContext(ctx, contextGlobal) {
		// Bootstrap Titanium global APIs onto the new context global
		bootstrap.bootstrapGlobals(contextGlobal, Titanium);
	}

	// We initialize the context with the standard Javascript APIs and globals first before running the script
	var newContext = context.global = ti.global = Script.createContext(contextGlobal, initContext);

	if (kroll.runtime == "rhino") {
		// The Rhino version of this API takes a custom global object but uses the same Rhino "Context".
		// It's not possible to create more than 1 Context per thread in Rhino, so contextGlobal
		// is essentially a detached global object that mimics a new context.
		return runInThisContext(source, filename, true, newContext);

	} else {
		// The V8 version of this API creates a brand new V8 top-level context that's associated
		// with a new global object. Script.createContext copies all of our context-specific data
		// into a new ContextWrapper that doubles as the global object for the context itself.
		kroll.moduleContexts.push(newContext);
		return Script.runInContext(source, newContext, filename, true);
	}
}

// Determine the paths where the requested module could live.
// Returns [id, paths]  where id is the module ID and paths
// is the list of path names.
function resolveLookupPaths(request, parentModule) {

	// "absolute" in Titanium is relative to the Resources folder
	if (request.charAt(0) === '/') {
		request = request.substring(1);
	}

	var start = request.substring(0, 2);
	if (start !== './' && start !== '..') {
		var paths = Module.paths;
		if (parentModule) {
			if (!parentModule.paths) {
				parentModule.paths = [];
			}
			paths = parentModule.paths.concat(paths);
		}
		return [request, paths];
	}

	// Get the path to the parent module. If the parent
	// is an index file, its ID is already the directory path.
	// Ex: path.id = "a/" if index
	//     path.id = "a/b" if non-index
	var isIndex = /^index\.\w+?$/.test(path.basename(parentModule.filename));
	var parentIdPath = isIndex ? parentModule.id : path.dirname(parentModule.id);

	var id = path.resolve(parentIdPath, request);

	// make sure require('./path') and require('path') get distinct ids, even
	// when called from the toplevel js file
	if (parentIdPath === '.' && id.indexOf('/') === -1) {
		id = './' + id;
	}

	// The module ID is resolved now, so we use the root "Module.paths" as the lookup base
	return [id, Module.paths];
}

// Determine the filename that contains the request
// module's source code. If no file is found an exception
// will be thrown.
function resolveFilename(request, parentModule) {

	var resolvedModule = resolveLookupPaths(request, parentModule);
	var id = resolvedModule[0];
	var paths = resolvedModule[1];

	// Try each possible path where the module's source file
	// could be located.
	for (var i = 0, pathCount = paths.length; i < pathCount; ++i) {
		var filename = path.resolve(paths[i], id) + '.js';
		if (filenameExists(filename)) {
			return [id, filename];
		}
	}

	throw new Error("Requested module not found: " + request);
}

var fileIndex;

function filenameExists(filename) {
	if (!fileIndex) {
		var json = assets.readAsset("index.json");
		fileIndex = JSON.parse(json);
	}

	return filename in fileIndex;
}

<|endoftext|>


<commit_before>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var NativeModule = require('native_module'),
	assets = kroll.binding('assets'),
	path = require('path'),
	Script = kroll.binding('evals').Script,
	runInThisContext = require('vm').runInThisContext,
	bootstrap = require('bootstrap');

var TAG = "Module";

function Module(id, parent, context) {
	this.id = id;
	this.exports = {};
	this.parent = parent;
	this.context = context;

	this.filename = null;
	this.loaded = false;
	this.exited = false;
	this.children = [];
}
kroll.Module = module.exports = Module;

Module.cache = [];
Module.main = null;
Module.paths = [ 'Resources/' ];
Module.wrap = NativeModule.wrap;

Module.runModule = function (source, filename, activity) {

	var id = filename;
	if (!Module.main) {
		id = ".";
	}

	var module = new Module(id, null, {
		currentActivity: activity,
		currentWindow: activity ? activity.window : null
	});

	if (!Module.main) {
		Module.main = module;
	}

	module.load(filename, source, activity);
	return module;
}

// Run a module as the main entry point.
Module.runMainModule = function (source, filename) {
	var mainModule = Module.main = new Module('.');
	mainModule.load(filename, source);
	return true;
}

// Attempts to load the module. If no file is found
// with the provided name an exception will be thrown.
// Once the contents of the file are read, it is ran
// in the current context. A sandbox is created by
// executing the code inside a wrapper function.
// This provides a speed boost vs creating a new context.
//
// Returns the exports object of the loaded module if successful.
Module.prototype.load = function (filename, source) {
	if (this.loaded) {
		throw new Error("Module already loaded.");
	}

	this.filename = filename;
	this.paths = [path.dirname(filename)];

	if (!source) {
		source = assets.readAsset(filename);
	}

	this._runScript(source, filename);

	this.loaded = true;
}

// Require another module as a child of this module.
// This parent module's path is appended to the search paths
// when loading the child. Returns the exports object
// of the child module.
Module.prototype.require = function (request, context, useCache) {
	useCache = useCache === undefined ? true : useCache;

	// Delegate native module requests.
	if (NativeModule.exists(request)) {
		kroll.log(TAG, 'Found native module: "' + request + '"');
		return NativeModule.require(request);
	}

	var resolved = resolveFilename(request, this);
	var id = resolved[0];
	var filename = resolved[1];

	kroll.log(TAG, 'Loading module: ' + request + ' -> ' + filename);

	if (useCache) {
		var cachedModule = Module.cache[filename];
		if (cachedModule) {
			return cachedModule.exports;
		}
	}

	// Create and attempt to load the module.
	var module = new Module(id, this, context);
	module.load(filename);

	if (useCache) {
		// Cache the module for future requests.
		Module.cache[filename] = module;
	}

	return module.exports;
}

// Setup a sandbox and run the module's script inside it.
// Returns the result of the executed script.
Module.prototype._runScript = function (source, filename) {
	var self = this;
	var url = "app://" + filename.replace("Resources/", "");

	try {
		function require(path, context) {
			return self.require(path, context);
		}
		require.main = Module.main;

		if (self.id == '.') {
			global.require = require;
			Titanium.Android.currentActivity = self.context.currentActivity;

			return runInThisContext(source, filename, true);
		}

		// Create context-bound modules.
		var context = self.context || {};
		context.sourceUrl = url;
		context.module = this;

		// Create a "context global" that's specific to each module
		var contextGlobal = context.global = {
			exports: this.exports,
			require: require,
			module: this,
			__filename: filename,
			__dirname: path.dirname(filename),
			kroll: kroll
		};
		contextGlobal.global = contextGlobal;

		var ti = new Titanium.Wrapper(context);
		contextGlobal.Ti = contextGlobal.Titanium = ti;

		// This function is called by the context when it is finished initializing
		// the builtin Javascript APIs
		function initContext(ctx, contextGlobal) {
			// Bootstrap Titanium global APIs onto the new context global
			bootstrap.bootstrapGlobals(contextGlobal, Titanium);
		}

		// We initialize the context with the standard Javascript APIs and globals first before running the script
		var newContext = context.global = ti.global = Script.createContext(contextGlobal, initContext);

		if (kroll.runtime == "rhino") {
			// The Rhino version of this API takes a custom global object but uses the same Rhino "Context".
			// It's not possible to create more than 1 Context per thread in Rhino, so contextGlobal
			// is essentially a detached global object that mimics a new context.
			return runInThisContext(source, filename, true, newContext);

		} else {
			// The V8 version of this API creates a brand new V8 top-level context that's associated
			// with a new global object. Script.createContext copies all of our context-specific data
			// into a new ContextWrapper that doubles as the global object for the context itself.
			kroll.moduleContexts.push(newContext);
			return Script.runInContext(source, newContext, filename, true);
		}
	} catch (e) {
		kroll.log(TAG, "got error running module: " + e);
	}
}

// Determine the paths where the requested module could live.
// Returns [id, paths]  where id is the module ID and paths
// is the list of path names.
function resolveLookupPaths(request, parentModule) {

	// "absolute" in Titanium is relative to the Resources folder
	if (request.charAt(0) === '/') {
		request = request.substring(1);
	}

	var start = request.substring(0, 2);
	if (start !== './' && start !== '..') {
		var paths = Module.paths;
		if (parentModule) {
			if (!parentModule.paths) {
				parentModule.paths = [];
			}
			paths = parentModule.paths.concat(paths);
		}
		return [request, paths];
	}

	// Get the path to the parent module. If the parent
	// is an index file, its ID is already the directory path.
	// Ex: path.id = "a/" if index
	//     path.id = "a/b" if non-index
	var isIndex = /^index\.\w+?$/.test(path.basename(parentModule.filename));
	var parentIdPath = isIndex ? parentModule.id : path.dirname(parentModule.id);

	var id = path.resolve(parentIdPath, request);

	// make sure require('./path') and require('path') get distinct ids, even
	// when called from the toplevel js file
	if (parentIdPath === '.' && id.indexOf('/') === -1) {
		id = './' + id;
	}

	// The module ID is resolved now, so we use the root "Module.paths" as the lookup base
	return [id, Module.paths];
}

// Determine the filename that contains the request
// module's source code. If no file is found an exception
// will be thrown.
function resolveFilename(request, parentModule) {

	var resolvedModule = resolveLookupPaths(request, parentModule);
	var id = resolvedModule[0];
	var paths = resolvedModule[1];

	// Try each possible path where the module's source file
	// could be located.
	for (var i = 0, pathCount = paths.length; i < pathCount; ++i) {
		var filename = path.resolve(paths[i], id) + '.js';
		if (filenameExists(filename)) {
			return [id, filename];
		}
	}

	throw new Error("Requested module not found: " + request);
}

var fileIndex;

function filenameExists(filename) {
	if (!fileIndex) {
		var json = assets.readAsset("index.json");
		fileIndex = JSON.parse(json);
	}

	return filename in fileIndex;
}

<commit_msg>remove extra try/catch added while debugging<commit_after>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var NativeModule = require('native_module'),
	assets = kroll.binding('assets'),
	path = require('path'),
	Script = kroll.binding('evals').Script,
	runInThisContext = require('vm').runInThisContext,
	bootstrap = require('bootstrap');

var TAG = "Module";

function Module(id, parent, context) {
	this.id = id;
	this.exports = {};
	this.parent = parent;
	this.context = context;

	this.filename = null;
	this.loaded = false;
	this.exited = false;
	this.children = [];
}
kroll.Module = module.exports = Module;

Module.cache = [];
Module.main = null;
Module.paths = [ 'Resources/' ];
Module.wrap = NativeModule.wrap;

Module.runModule = function (source, filename, activity) {

	var id = filename;
	if (!Module.main) {
		id = ".";
	}

	var module = new Module(id, null, {
		currentActivity: activity,
		currentWindow: activity ? activity.window : null
	});

	if (!Module.main) {
		Module.main = module;
	}

	module.load(filename, source, activity);
	return module;
}

// Run a module as the main entry point.
Module.runMainModule = function (source, filename) {
	var mainModule = Module.main = new Module('.');
	mainModule.load(filename, source);
	return true;
}

// Attempts to load the module. If no file is found
// with the provided name an exception will be thrown.
// Once the contents of the file are read, it is ran
// in the current context. A sandbox is created by
// executing the code inside a wrapper function.
// This provides a speed boost vs creating a new context.
//
// Returns the exports object of the loaded module if successful.
Module.prototype.load = function (filename, source) {
	if (this.loaded) {
		throw new Error("Module already loaded.");
	}

	this.filename = filename;
	this.paths = [path.dirname(filename)];

	if (!source) {
		source = assets.readAsset(filename);
	}

	this._runScript(source, filename);

	this.loaded = true;
}

// Require another module as a child of this module.
// This parent module's path is appended to the search paths
// when loading the child. Returns the exports object
// of the child module.
Module.prototype.require = function (request, context, useCache) {
	useCache = useCache === undefined ? true : useCache;

	// Delegate native module requests.
	if (NativeModule.exists(request)) {
		kroll.log(TAG, 'Found native module: "' + request + '"');
		return NativeModule.require(request);
	}

	var resolved = resolveFilename(request, this);
	var id = resolved[0];
	var filename = resolved[1];

	kroll.log(TAG, 'Loading module: ' + request + ' -> ' + filename);

	if (useCache) {
		var cachedModule = Module.cache[filename];
		if (cachedModule) {
			return cachedModule.exports;
		}
	}

	// Create and attempt to load the module.
	var module = new Module(id, this, context);
	module.load(filename);

	if (useCache) {
		// Cache the module for future requests.
		Module.cache[filename] = module;
	}

	return module.exports;
}

// Setup a sandbox and run the module's script inside it.
// Returns the result of the executed script.
Module.prototype._runScript = function (source, filename) {
	var self = this;
	var url = "app://" + filename.replace("Resources/", "");

	function require(path, context) {
		return self.require(path, context);
	}
	require.main = Module.main;

	if (self.id == '.') {
		global.require = require;
		Titanium.Android.currentActivity = self.context.currentActivity;

		return runInThisContext(source, filename, true);
	}

	// Create context-bound modules.
	var context = self.context || {};
	context.sourceUrl = url;
	context.module = this;

	// Create a "context global" that's specific to each module
	var contextGlobal = context.global = {
		exports: this.exports,
		require: require,
		module: this,
		__filename: filename,
		__dirname: path.dirname(filename),
		kroll: kroll
	};
	contextGlobal.global = contextGlobal;

	var ti = new Titanium.Wrapper(context);
	contextGlobal.Ti = contextGlobal.Titanium = ti;

	// This function is called by the context when it is finished initializing
	// the builtin Javascript APIs
	function initContext(ctx, contextGlobal) {
		// Bootstrap Titanium global APIs onto the new context global
		bootstrap.bootstrapGlobals(contextGlobal, Titanium);
	}

	// We initialize the context with the standard Javascript APIs and globals first before running the script
	var newContext = context.global = ti.global = Script.createContext(contextGlobal, initContext);

	if (kroll.runtime == "rhino") {
		// The Rhino version of this API takes a custom global object but uses the same Rhino "Context".
		// It's not possible to create more than 1 Context per thread in Rhino, so contextGlobal
		// is essentially a detached global object that mimics a new context.
		return runInThisContext(source, filename, true, newContext);

	} else {
		// The V8 version of this API creates a brand new V8 top-level context that's associated
		// with a new global object. Script.createContext copies all of our context-specific data
		// into a new ContextWrapper that doubles as the global object for the context itself.
		kroll.moduleContexts.push(newContext);
		return Script.runInContext(source, newContext, filename, true);
	}
}

// Determine the paths where the requested module could live.
// Returns [id, paths]  where id is the module ID and paths
// is the list of path names.
function resolveLookupPaths(request, parentModule) {

	// "absolute" in Titanium is relative to the Resources folder
	if (request.charAt(0) === '/') {
		request = request.substring(1);
	}

	var start = request.substring(0, 2);
	if (start !== './' && start !== '..') {
		var paths = Module.paths;
		if (parentModule) {
			if (!parentModule.paths) {
				parentModule.paths = [];
			}
			paths = parentModule.paths.concat(paths);
		}
		return [request, paths];
	}

	// Get the path to the parent module. If the parent
	// is an index file, its ID is already the directory path.
	// Ex: path.id = "a/" if index
	//     path.id = "a/b" if non-index
	var isIndex = /^index\.\w+?$/.test(path.basename(parentModule.filename));
	var parentIdPath = isIndex ? parentModule.id : path.dirname(parentModule.id);

	var id = path.resolve(parentIdPath, request);

	// make sure require('./path') and require('path') get distinct ids, even
	// when called from the toplevel js file
	if (parentIdPath === '.' && id.indexOf('/') === -1) {
		id = './' + id;
	}

	// The module ID is resolved now, so we use the root "Module.paths" as the lookup base
	return [id, Module.paths];
}

// Determine the filename that contains the request
// module's source code. If no file is found an exception
// will be thrown.
function resolveFilename(request, parentModule) {

	var resolvedModule = resolveLookupPaths(request, parentModule);
	var id = resolvedModule[0];
	var paths = resolvedModule[1];

	// Try each possible path where the module's source file
	// could be located.
	for (var i = 0, pathCount = paths.length; i < pathCount; ++i) {
		var filename = path.resolve(paths[i], id) + '.js';
		if (filenameExists(filename)) {
			return [id, filename];
		}
	}

	throw new Error("Requested module not found: " + request);
}

var fileIndex;

function filenameExists(filename) {
	if (!fileIndex) {
		var json = assets.readAsset("index.json");
		fileIndex = JSON.parse(json);
	}

	return filename in fileIndex;
}

<|endoftext|>


<commit_before>/**
 * DestroyAllController
 *
 * @description :: Server-side logic for managing destroyalls
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
 rundestroy: function (req, res) {
        Test.destroy({}).exec(function (err){
                  if (err) {
                    return res.negotiate(err);
                  }
                  sails.log('Any tests have now been deleted!');
                 return res.ok();
        });
        Question.destroy({}).exec(function (err){
                  if (err) {
                    return res.negotiate(err);
                  }
                  sails.log('Any questions have now been deleted!');
                 return res.ok();
        });
        Answer.destroy({}).exec(function (err){
                  if (err) {
                    return res.negotiate(err);
                  }
                  sails.log('Any answers have now been deleted!');
                 return res.ok();
        });
        Picture.destroy({}).exec(function (err){
                  if (err) {
                    return res.negotiate(err);
                  }
                  sails.log('Any pictures have now been deleted!');
                 return res.ok();
        });
        CorrectAnswer.destroy({}).exec(function (err){
                  if (err) {
                    return res.negotiate(err);
                  }
                  sails.log('Any correct answer have now been deleted!');
                 return res.ok();
        });

  }
}
<commit_msg>destroy passed test<commit_after>/**
 * DestroyAllController
 *
 * @description :: Server-side logic for managing destroyalls
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
 rundestroy: function (req, res) {
        Test.destroy({}).exec(function (err){
                  if (err) {
                    return res.negotiate(err);
                  }
                  sails.log('Any tests have now been deleted!');
                 return res.ok();
        });
        Question.destroy({}).exec(function (err){
                  if (err) {
                    return res.negotiate(err);
                  }
                  sails.log('Any questions have now been deleted!');
                 return res.ok();
        });
        Answer.destroy({}).exec(function (err){
                  if (err) {
                    return res.negotiate(err);
                  }
                  sails.log('Any answers have now been deleted!');
                 return res.ok();
        });
        Picture.destroy({}).exec(function (err){
                  if (err) {
                    return res.negotiate(err);
                  }
                  sails.log('Any pictures have now been deleted!');
                 return res.ok();
        });
        CorrectAnswer.destroy({}).exec(function (err){
                  if (err) {
                    return res.negotiate(err);
                  }
                  sails.log('Any correct answer have now been deleted!');
                 return res.ok();
        });

  },

 destroyTable: function(req,res) {
	table = req.param('table');
	eval(table + ".destroy({}).exec(function (err){ if (err) { return res.negotiate(err);} sails.log('Any "+ table +" have now been deleted!'); return res.ok();}); ");
	}

}
<|endoftext|>


<commit_before>import { fetchAndPresentFollowed } from '../services/TagPresenter'
import { get } from 'lodash/fp'

module.exports = {
  show: function (req, res) {
    if (!req.session.userId) return res.ok({})
    const communityId = req.param('communityId')

    return Promise.join(
      User.find(req.session.userId, {withRelated: ['memberships']}),
      communityId && Community.find(communityId),
      (user, com) =>
        fetchAndPresentFollowed(get('id', com), user.id)
        .then(left_nav_tags => res.ok({
          new_notification_count: user.get('new_notification_count'),
          left_nav_tags,
          memberships: user.relations.memberships.map(m => ({
            id: m.id,
            new_notification_count: m.get('new_notification_count')
          }))
        })))
  }
}
<commit_msg>remove memberships from fetchLiveStatus<commit_after>import { fetchAndPresentFollowed } from '../services/TagPresenter'
import { get } from 'lodash/fp'

module.exports = {
  show: function (req, res) {
    if (!req.session.userId) return res.ok({})
    const communityId = req.param('communityId')

    return Promise.join(
      User.find(req.session.userId),
      communityId && Community.find(communityId),
      (user, com) =>
        fetchAndPresentFollowed(get('id', com), user.id)
        .then(left_nav_tags => res.ok({
          new_notification_count: user.get('new_notification_count'),
          left_nav_tags
        })))
  }
}
<|endoftext|>


<commit_before>/**
 * @param options.autohideTabBar
 *            Whether to autohide the tab bar when only 1 tab showing
 * @param options.landingPage Landing page to show when all tabs are closed
 */
morpheus.TabManager = function (options) {
  this.options = $.extend({}, {
    autohideTabBar: false,
    rename: true
  }, options);
  var _this = this;
  this.activeTabObject = null;
  this.activeTabId = null;
  this.idToTabObject = new morpheus.Map();
  this.$nav = $('

');
  this.$nav.on('click', 'li > a', function (e) {
    var tabId = $(this).data('link');
    e.preventDefault();
    if (_this.activeTabId !== tabId) {
      $(this).tab('show');
    }
  });

  function rename($a) {

    var builder = new morpheus.FormBuilder();
    builder.append({
      name: 'name',
      type: 'text',
      value: $.trim($a.contents().first().text())
    });
    morpheus.FormBuilder.showOkCancel({
      title: 'Rename Tab',
      content: builder.$form,
      okCallback: function () {
        var name = $.trim(builder.getValue('name'));
        if (name !== '') {
          if (_this.activeTabObject != null) {
            _this.activeTabObject.setName(name);
          }
          $a.contents().first().replaceWith(name + ' ');
        }
      }
    });
    // edit tab name
  }

  // rename

  this.$nav.on('dblclick', 'li > a', function (e) {
    e.preventDefault();
    if ($(this).data('morpheus-rename') && _this.options.rename) {
      rename($(this));
    }

  });
  this.$nav.on('contextmenu.morpheus', 'li > a', function (e) {
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
    var $a = $(this);
    if ($a.data('morpheus-rename') && _this.options.rename) {
      morpheus.Popup.showPopup([{
        name: 'Rename'
      }], {
        x: e.pageX,
        y: e.pageY
      }, e.target, function (event, item) {
        rename($a);
      });
    }
    return false;

  });

  this.$nav.on('click', 'button', function (e) { // close a tab
    // remove the link and tab content
    e.preventDefault();
    var target = $(this).attr('data-target');

    if (target != null) {
      target = target.substring(1); // remove #
      _this.remove(target);
    }
  });

  this.$tabContent = $('

');
  this.$nav.on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    if (_this.adding) {
      return;
    }
    // triggered when clicking tab
    var previous = _this.activeTabObject;
    _this.activeTabId = $(e.target).data('link');
    _this.activeTabObject = _this.idToTabObject.get(_this.activeTabId);
    _this.trigger('change', {
      tab: _this.activeTabObject,
      previous: previous
    });
  });

};
morpheus.TabManager.prototype = {
  getTabCount: function () {
    return this.idToTabObject.size();
  },
  setTabText: function (id, text) {
    this.$nav.find('a').filter('[data-link=' + id + ']').contents().first()
    .replaceWith(text + ' ');
    this.idToTabObject.get(id).setName(name);
  },
  /**
   * @param id
   *            Tab id
   * @param task
   * @param task.worker
   *            Optional worker that the task is run in.
   * @param task.name
   * @param task.tabId
   *            Tab id for task
   */
  addTask: function (task) {
    var $a = this.$nav.find('[data-link=' + task.tabId + ']');
    if ($a.length === 0) {
      console.log(task.tabId + ' not found.');
      return;

    }
    var $i = $a.find('i');
    var tasks = $i.data('tasks');
    if (!tasks) {
      tasks = [];
    }
    task.id = _.uniqueId('task');
    tasks.push(task);
    $i.data('tasks', tasks);
    $a
    .removeClass('animated flash')
    .addClass('animated flash')
    .one(
      'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend',
      function () {
        $(this).removeClass('animated flash');
      });

    $i.addClass('fa fa-spinner fa-spin');
  },
  removeTask: function (task) {
    var $a = this.$nav.find('[data-link=' + task.tabId + ']');
    var $i = $a.find('i');
    var tasks = $i.data('tasks');
    if (!tasks) {
      tasks = [];
    }
    var index = -1;
    for (var i = 0; i < tasks.length; i++) {
      if (tasks[i].id === task.id) {
        index = i;
        break;
      }
    }
    if (index !== -1) {
      tasks.splice(index, 1);
      $i.data('tasks', tasks);
      if (tasks.length === 0) {
        $i.removeClass('fa fa-spinner fa-spin');
      }
    }
  },
  getWidth: function () {
    return this.$tabContent.outerWidth() || $(window).width();
  },
  getActiveTab: function () {
    return this.activeTabObject;
  },
  getActiveTabId: function () {
    return this.activeTabId;
  },

  /**
   *
   * @param options.object The object that stores the tab content state and has a setName if
   * function if rename is true.
   * @param options.$el
   *            the tab element
   * @param options.title
   *            the tab title
   * @param options.closeable
   *            Whether tab can be closed
   * @param options.rename
   *            Whether tab can be renamed
   * @param options.focus
   *            Whether new tab should be focused-note the change event is not
   *            triggered when true
   * @param options.enabled
   *            Whether new tab is enabled
   *
   */
  add: function (options) {
    this.adding = true;
    var id = _.uniqueId('morpheus-tab');

    this.idToTabObject.set(id, options.object);
    var li = [];
    li.push('
');
    li.push('');
    li.push(options.title);
    li.push(' ');
    if (options.closeable) {
      li
      .push('&nbsp<button style="font-size: 18px;" type="button" class="close"' +
        ' aria-label="Close"' +
        ' data-target="#'
        + id
        + '">×</button>');

    }
    li.push('
');
    var $link = $(li.join(''));
    $link.appendTo(this.$nav);
    var $panel = $('

');
    options.$el.appendTo($panel);
    $panel.appendTo(this.$tabContent);
    if (options.enabled === false) {
      $link.addClass('disabled');
      $link.find('a').addClass('btn disabled');
    }
    if (options.focus) {
      // update active tab, but don't fire event
      this.$nav.find('a[data-toggle="tab"]:last').tab('show');
      this.activeTabId = id;
      this.activeTabObject = options.object;
      $panel.focus();
    }

    if (this.options.autohideTabBar) {
      this.$nav.css('display', this.idToTabObject.size() > 1 ? ''
        : 'none');
    }
    this.adding = false;
    return {
      $panel: $panel,
      id: id
    };
  },
  appendTo: function ($target) {
    this.$nav.appendTo($target);
    this.$tabContent.appendTo($target);
  },
  remove: function (target) {
    if (target === undefined) {
      target = this.activeTabId;
    }
    var obj = this.idToTabObject.remove(target);
    $('#' + target).remove(); // remove tab-pane
    this.activeTabObject = null;
    this.$nav.find('[data-link=' + target + ']:first').parent().remove();
    this.$tabContent.find(target).remove();
    var $a = this.$nav.find('a[data-toggle="tab"]:last');
    if ($a.length === 0) {
      // no content
      if (this.options.landingPage) {
        this.options.landingPage.show();
      }
    }

    $a.tab('show');
    if (this.options.autohideTabBar) {
      this.$nav.css('display', this.idToTabObject.size() > 1 ? ''
        : 'none');
    }
    if (this.idToTabObject.size() > 0) {
      $($a.attr('href')).focus();

    }

    if (obj != null && obj.onRemove) {
      obj.onRemove();
    }
    this.trigger('remove', {
      tab: target
    });
  },
  setOptions: function (options) {
    this.options = options;
    if (this.options.autohideTabBar) {
      this.$nav.css('display', this.idToTabObject.size() > 1 ? ''
        : 'none');
    }
  },
  getOptions: function () {
    return this.options;
  },
  setActiveTab: function (id) {
    if (id === this.activeTabId) {
      this.trigger('change', {
        tab: this.activeTabObject,
        previous: null
      });
    }
    var $a = this.$nav.find('[data-link=' + id + ']');
    // make sure it's enabled
    $a.parent().removeClass('disabled');
    $a.removeClass('btn disabled');
    $a.tab('show');

  },
  /**
   *
   * @param id
   *            The tab id
   * @param title
   *            The title (used to show tooltip)
   */
  setTabTitle: function (id, title) {
    this.$nav.find('a').filter('[data-link=' + id + ']').attr('title', title);
  },
  setTabEnabled: function (id, enabled) {
    var $a = this.$nav.find('a').filter('[data-link=' + id + ']');
    if (enabled) {
      $a.parent().removeClass('disabled');
      $a.removeClass('btn disabled');
    } else {
      $a.parent().addClass('disabled');
      $a.addClass('btn disabled');
    }

  },
  getTabObject: function (id) {
    return this.idToTabObject.get(id);
  }
};
morpheus.Util.extend(morpheus.TabManager, morpheus.Events);
<commit_msg>events<commit_after>/**
 * @param options.autohideTabBar
 *            Whether to autohide the tab bar when only 1 tab showing
 * @param options.landingPage Landing page to show when all tabs are closed
 */
morpheus.TabManager = function (options) {
  this.options = $.extend({}, {
    autohideTabBar: false,
    rename: true
  }, options);
  var _this = this;
  this.activeTabObject = null;
  this.activeTabId = null;
  this.idToTabObject = new morpheus.Map();
  this.$nav = $('

');
  this.$nav.on('click', 'li > a', function (e) {
    var tabId = $(this).data('link');
    e.preventDefault();
    if (_this.activeTabId !== tabId) {
      $(this).tab('show');
    }
  });

  function rename($a) {

    var builder = new morpheus.FormBuilder();
    builder.append({
      name: 'name',
      type: 'text',
      value: $.trim($a.contents().first().text())
    });
    morpheus.FormBuilder.showOkCancel({
      title: 'Rename Tab',
      content: builder.$form,
      okCallback: function () {
        var name = $.trim(builder.getValue('name'));
        if (name !== '') {
          if (_this.activeTabObject != null) {
            _this.activeTabObject.setName(name);
          }
          $a.contents().first().replaceWith(name + ' ');
        }
      }
    });
    // edit tab name
  }

  // rename

  this.$nav.on('dblclick', 'li > a', function (e) {
    e.preventDefault();
    if ($(this).data('morpheus-rename') && _this.options.rename) {
      rename($(this));
    }

  });
  this.$nav.on('contextmenu.morpheus', 'li > a', function (e) {
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
    var $a = $(this);
    if ($a.data('morpheus-rename') && _this.options.rename) {
      morpheus.Popup.showPopup([{
        name: 'Rename'
      }], {
        x: e.pageX,
        y: e.pageY
      }, e.target, function (event, item) {
        rename($a);
      });
    }
    return false;

  });

  this.$nav.on('click', 'button', function (e) { // close a tab
    // remove the link and tab content
    e.preventDefault();
    var target = $(this).attr('data-target');

    if (target != null) {
      target = target.substring(1); // remove #
      _this.remove(target);
    }
  });

  this.$tabContent = $('

');
  this.$nav.on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    if (_this.adding) {
      return;
    }
    // triggered when clicking tab
    var previous = _this.activeTabId;
    _this.activeTabId = $(e.target).data('link');
    _this.activeTabObject = _this.idToTabObject.get(_this.activeTabId);
    _this.trigger('change', {
      tab: _this.activeTabId,
      previous: previous
    });
  });

};
morpheus.TabManager.prototype = {
  getTabCount: function () {
    return this.idToTabObject.size();
  },
  setTabText: function (id, text) {
    this.$nav.find('a').filter('[data-link=' + id + ']').contents().first()
    .replaceWith(text + ' ');
    this.idToTabObject.get(id).setName(name);
  },
  /**
   * @param id
   *            Tab id
   * @param task
   * @param task.worker
   *            Optional worker that the task is run in.
   * @param task.name
   * @param task.tabId
   *            Tab id for task
   */
  addTask: function (task) {
    var $a = this.$nav.find('[data-link=' + task.tabId + ']');
    if ($a.length === 0) {
      console.log(task.tabId + ' not found.');
      return;

    }
    var $i = $a.find('i');
    var tasks = $i.data('tasks');
    if (!tasks) {
      tasks = [];
    }
    task.id = _.uniqueId('task');
    tasks.push(task);
    $i.data('tasks', tasks);
    $a
    .removeClass('animated flash')
    .addClass('animated flash')
    .one(
      'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend',
      function () {
        $(this).removeClass('animated flash');
      });

    $i.addClass('fa fa-spinner fa-spin');
  },
  removeTask: function (task) {
    var $a = this.$nav.find('[data-link=' + task.tabId + ']');
    var $i = $a.find('i');
    var tasks = $i.data('tasks');
    if (!tasks) {
      tasks = [];
    }
    var index = -1;
    for (var i = 0; i < tasks.length; i++) {
      if (tasks[i].id === task.id) {
        index = i;
        break;
      }
    }
    if (index !== -1) {
      tasks.splice(index, 1);
      $i.data('tasks', tasks);
      if (tasks.length === 0) {
        $i.removeClass('fa fa-spinner fa-spin');
      }
    }
  },
  getWidth: function () {
    return this.$tabContent.outerWidth() || $(window).width();
  },
  getActiveTab: function () {
    return this.activeTabObject;
  },
  getActiveTabId: function () {
    return this.activeTabId;
  },

  /**
   *
   * @param options.object The object that stores the tab content state and has a setName if
   * function if rename is true.
   * @param options.$el
   *            the tab element
   * @param options.title
   *            the tab title
   * @param options.closeable
   *            Whether tab can be closed
   * @param options.rename
   *            Whether tab can be renamed
   * @param options.focus
   *            Whether new tab should be focused-note the change event is not
   *            triggered when true
   * @param options.enabled
   *            Whether new tab is enabled
   *
   */
  add: function (options) {
    this.adding = true;
    var id = _.uniqueId('morpheus-tab');

    this.idToTabObject.set(id, options.object);
    var li = [];
    li.push('
');
    li.push('');
    li.push(options.title);
    li.push(' ');
    if (options.closeable) {
      li
      .push('&nbsp<button style="font-size: 18px;" type="button" class="close"' +
        ' aria-label="Close"' +
        ' data-target="#'
        + id
        + '">×</button>');

    }
    li.push('
');
    var $link = $(li.join(''));
    $link.appendTo(this.$nav);
    var $panel = $('

');
    options.$el.appendTo($panel);
    $panel.appendTo(this.$tabContent);
    if (options.enabled === false) {
      $link.addClass('disabled');
      $link.find('a').addClass('btn disabled');
    }
    if (options.focus) {
      // update active tab, but don't fire event
      this.$nav.find('a[data-toggle="tab"]:last').tab('show');
      this.activeTabId = id;
      this.activeTabObject = options.object;
      $panel.focus();
    }

    if (this.options.autohideTabBar) {
      this.$nav.css('display', this.idToTabObject.size() > 1 ? ''
        : 'none');
    }
    this.adding = false;
    return {
      $panel: $panel,
      id: id
    };
  },
  appendTo: function ($target) {
    this.$nav.appendTo($target);
    this.$tabContent.appendTo($target);
  },
  remove: function (target) {
    if (target === undefined) {
      target = this.activeTabId;
    }
    var obj = this.idToTabObject.remove(target);
    $('#' + target).remove(); // remove tab-pane
    this.activeTabObject = null;
    this.$nav.find('[data-link=' + target + ']:first').parent().remove();
    this.$tabContent.find(target).remove();
    var $a = this.$nav.find('a[data-toggle="tab"]:last');
    if ($a.length === 0) {
      // no content
      if (this.options.landingPage) {
        this.options.landingPage.show();
      }
    }

    $a.tab('show');
    if (this.options.autohideTabBar) {
      this.$nav.css('display', this.idToTabObject.size() > 1 ? ''
        : 'none');
    }
    if (this.idToTabObject.size() > 0) {
      $($a.attr('href')).focus();

    }

    if (obj != null && obj.onRemove) {
      obj.onRemove();
    }
    this.trigger('remove', {
      tab: target
    });
  },
  setOptions: function (options) {
    this.options = options;
    if (this.options.autohideTabBar) {
      this.$nav.css('display', this.idToTabObject.size() > 1 ? ''
        : 'none');
    }
  },
  getOptions: function () {
    return this.options;
  },
  setActiveTab: function (id) {
    if (id !== this.activeTabId) {
      var $a = this.$nav.find('[data-link=' + id + ']');
      // make sure it's enabled
      $a.parent().removeClass('disabled');
      $a.removeClass('btn disabled');
      $a.tab('show');
      var previous = this.activeTabId;
      this.activeTabId = id;
      this.activeTabObject = this.idToTabObject.get(this.activeTabId);
      this.trigger('change', {
        tab: this.activeTabId,
        previous: previous
      });
    }

  },
  /**
   *
   * @param id
   *            The tab id
   * @param title
   *            The title (used to show tooltip)
   */
  setTabTitle: function (id, title) {
    this.$nav.find('a').filter('[data-link=' + id + ']').attr('title', title);
  },
  setTabEnabled: function (id, enabled) {
    var $a = this.$nav.find('a').filter('[data-link=' + id + ']');
    if (enabled) {
      $a.parent().removeClass('disabled');
      $a.removeClass('btn disabled');
    } else {
      $a.parent().addClass('disabled');
      $a.addClass('btn disabled');
    }

  },
  getIdToTabObject: function () {
    return this.idToTabObject;
  },
  getTabObject: function (id) {
    return this.idToTabObject.get(id);
  }
};
morpheus.Util.extend(morpheus.TabManager, morpheus.Events);
<|endoftext|>


<commit_before>App.addChild('MixPanel', {
  el: 'body',

  activate: function(){
    this.VISIT_MIN_TIME = 10000;
    this.user = null;
    this.controller = this.$el.data('controller');
    this.action = this.$el.data('action');
    this.user = this.$el.data('user');
    if(window.mixpanel){
      this.detectLogin();
      this.startTracking();
    }
  },

  startTracking: function(){
    var self = this;
    this.trackPageVisit('projects', 'show', 'Visited project page');
    this.trackPageVisit('explore', 'index', 'Explored projects');
    this.trackPageLoad('contributions', 'edit', 'Selected reward');
    this.trackTwitterShare();
    this.trackFacebookShare();
    this.trackReminderClick();
    this.trackFollowCategory();
    try {
      this.trackOnFacebookLike();
      this.trackOnFacebookComment();
    } catch(e) {
      console.log(e);
    }
  },

  trackFollowCategory: function(){
    this.$('.category-follow .follow-btn').on('click', function(event){
      self.track('Engaged with Catarse', { ref: $(event.currentTarget).data('title'), action: 'click follow category' });
      return true;
    });
  },

  trackReminderClick: function(){
    this.$('.reminder a:not([data-method])').on('click', function(event){
      self.track('Engaged with Catarse', { ref: $(event.currentTarget).data('title'), action: 'click reminder' });
      return true;
    });
  },

  trackPageLoad: function(controller, action, text){
    var self = this;
    this.trackOnPage(controller, action, function(){
      self.track(text);
    });
  },

  trackPageVisit: function(controller, action, text){
    var self = this;
    this.trackOnPage(controller, action, function(){
      self.trackVisit(text);
    });
  },

  trackOnPage: function(controller, action, callback){
    if(this.controller == controller && this.action == action){
      callback();
    }
  },

  trackTwitterShare: function() {
    var self = this;

    this.$('#twitter_share_button').on('click', function(event){
      self.track('Engaged with Catarse', { ref: $(event.currentTarget).data('title'), action: 'share twitter' });
    });
  },

  trackFacebookShare: function() {
    var self = this;
    this.$('a#facebook_share').on('click', function(event){
      self.track('Engaged with Catarse', { ref: $(event.currentTarget).data('title'), action: 'share facebook' });
    });
  },

  trackOnFacebookComment: function() {
    var self = this;

    FB.Event.subscribe('comment.create', function(url, html_element){
      self.track('Engaged with Catarse', { ref: $(html_element).data('title'), action: 'comment facebook' });
    });
  },

  trackOnFacebookLike: function() {
    var self = this;

    FB.Event.subscribe('edge.create', function(url, html_element){
      self.track('Engaged with Catarse', { ref: $(html_element).data('title'), action: 'like facebook' });
    });
  },

  onLogin: function(){
    mixpanel.alias(this.user.id);
    if(this.user.created_today){
      this.track("Signed up");
    }
    else{
      this.track("Logged in");
    }
  },

  detectLogin: function(){
    if(this.user){
      if(this.user.id != store.get('user_id')){
        this.onLogin();
        store.set('user_id', this.user.id);
      }
    }
    else{
      store.set('user_id', null);
    }
  },

  identifyUser: function(){
    if (this.user){
      mixpanel.name_tag(this.user.email);
      mixpanel.identify(this.user.id);
      mixpanel.people.set({
        "$email": this.user.email,
        "$created": this.user.created_at,
        "$last_login": this.user.last_sign_in_at,
        "contributions": this.user.total_contributed_projects
      });
    }
  },

  track: function(text, options){
    this.identifyUser();
    var opt             = options || {};
    var obj             = $(this);
    var ref             = (obj.attr('href') != undefined) ? obj.attr('href') : (opt.ref ? opt.ref : null);
    var default_options = {
      'page name':          document.title,
      'user_id':            null,
      'created':            null,
      'last_login':         null,
      'contributions':      null,
      'has_contributions':  null,
      'projects':           null,
      'has_projects':       null,
      'project':            ref,
      'url':                window.location
    };
    if(this.user){
      default_options.user_id = this.user.id;
      default_options.created = this.user.created_at;
      default_options.last_login = this.user.last_sign_in_at;
      default_options.contributions = this.user.total_contributed_projects;
      default_options.has_contributions = (this.user.total_contributed_projects > 0);
      default_options.projects = this.user.total_created_projects;
      default_options.has_projects = (this.user.total_created_projects > 0);
    }
    var opt     = $.fn.extend(default_options, opt);

    mixpanel.track(text, opt);
  },

  mixPanelEvent: function(target, event, text, options){
    var self = this;
    this.$(target).on(event, function(){
      self.track(text, options);
    });
  },

  trackVisit: function(eventName){
    var self = this;
    window.setTimeout(function(){
      self.track(eventName);
    }, this.VISIT_MIN_TIME);
  }
});
<commit_msg>adds trcking code to home page<commit_after>App.addChild('MixPanel', {
  el: 'body',

  activate: function(){
    this.VISIT_MIN_TIME = 10000;
    this.user = null;
    this.controller = this.$el.data('controller');
    this.action = this.$el.data('action');
    this.user = this.$el.data('user');
    if(window.mixpanel){
      this.detectLogin();
      this.startTracking();
    }
  },

  startTracking: function(){
    var self = this;
    this.trackPageVisit('projects', 'show', 'Visited project page');
    this.trackPageVisit('projects', 'index', 'Visited home');
    this.trackPageVisit('explore', 'index', 'Explored projects');
    this.trackPageLoad('contributions', 'edit', 'Selected reward');
    this.trackTwitterShare();
    this.trackFacebookShare();
    this.trackReminderClick();
    this.trackFollowCategory();
    try {
      this.trackOnFacebookLike();
      this.trackOnFacebookComment();
    } catch(e) {
      console.log(e);
    }
  },

  trackFollowCategory: function(){
    this.$('.category-follow .follow-btn').on('click', function(event){
      self.track('Engaged with Catarse', { ref: $(event.currentTarget).data('title'), action: 'click follow category' });
      return true;
    });
  },

  trackReminderClick: function(){
    this.$('.reminder a:not([data-method])').on('click', function(event){
      self.track('Engaged with Catarse', { ref: $(event.currentTarget).data('title'), action: 'click reminder' });
      return true;
    });
  },

  trackPageLoad: function(controller, action, text){
    var self = this;
    this.trackOnPage(controller, action, function(){
      self.track(text);
    });
  },

  trackPageVisit: function(controller, action, text){
    var self = this;
    this.trackOnPage(controller, action, function(){
      self.trackVisit(text);
    });
  },

  trackOnPage: function(controller, action, callback){
    if(this.controller == controller && this.action == action){
      callback();
    }
  },

  trackTwitterShare: function() {
    var self = this;

    this.$('#twitter_share_button').on('click', function(event){
      self.track('Engaged with Catarse', { ref: $(event.currentTarget).data('title'), action: 'share twitter' });
    });
  },

  trackFacebookShare: function() {
    var self = this;
    this.$('a#facebook_share').on('click', function(event){
      self.track('Engaged with Catarse', { ref: $(event.currentTarget).data('title'), action: 'share facebook' });
    });
  },

  trackOnFacebookComment: function() {
    var self = this;

    FB.Event.subscribe('comment.create', function(url, html_element){
      self.track('Engaged with Catarse', { ref: $(html_element).data('title'), action: 'comment facebook' });
    });
  },

  trackOnFacebookLike: function() {
    var self = this;

    FB.Event.subscribe('edge.create', function(url, html_element){
      self.track('Engaged with Catarse', { ref: $(html_element).data('title'), action: 'like facebook' });
    });
  },

  onLogin: function(){
    mixpanel.alias(this.user.id);
    if(this.user.created_today){
      this.track("Signed up");
    }
    else{
      this.track("Logged in");
    }
  },

  detectLogin: function(){
    if(this.user){
      if(this.user.id != store.get('user_id')){
        this.onLogin();
        store.set('user_id', this.user.id);
      }
    }
    else{
      store.set('user_id', null);
    }
  },

  identifyUser: function(){
    if (this.user){
      mixpanel.name_tag(this.user.email);
      mixpanel.identify(this.user.id);
      mixpanel.people.set({
        "$email": this.user.email,
        "$created": this.user.created_at,
        "$last_login": this.user.last_sign_in_at,
        "contributions": this.user.total_contributed_projects
      });
    }
  },

  track: function(text, options){
    this.identifyUser();
    var opt             = options || {};
    var obj             = $(this);
    var ref             = (obj.attr('href') != undefined) ? obj.attr('href') : (opt.ref ? opt.ref : null);
    var default_options = {
      'page name':          document.title,
      'user_id':            null,
      'created':            null,
      'last_login':         null,
      'contributions':      null,
      'has_contributions':  null,
      'projects':           null,
      'has_projects':       null,
      'project':            ref,
      'url':                window.location
    };
    if(this.user){
      default_options.user_id = this.user.id;
      default_options.created = this.user.created_at;
      default_options.last_login = this.user.last_sign_in_at;
      default_options.contributions = this.user.total_contributed_projects;
      default_options.has_contributions = (this.user.total_contributed_projects > 0);
      default_options.projects = this.user.total_created_projects;
      default_options.has_projects = (this.user.total_created_projects > 0);
    }
    var opt     = $.fn.extend(default_options, opt);

    mixpanel.track(text, opt);
  },

  mixPanelEvent: function(target, event, text, options){
    var self = this;
    this.$(target).on(event, function(){
      self.track(text, options);
    });
  },

  trackVisit: function(eventName){
    var self = this;
    window.setTimeout(function(){
      self.track(eventName);
    }, this.VISIT_MIN_TIME);
  }
});
<|endoftext|>