<commit_before>( function( tiy, moment ) {
  'use strict';

  const HW_NO_CLIENT_TEMPLATE = 'templates/hw.html';

  let $ui = null;
  let pageData = {};

  tiy.loadModule( {
    name: 'hw',
    navIcon: 'fa-download',
    render: main
  } );

  function main( data, elem ) {
    $ui = $( elem );
    pageData = data;

    // On relevant pages add links
    if ( pageData.assignment || pageData.assignment_submission ) {
      addCloneLinksToUi();
    }

    $( $ui ).on( 'showing', function() {
      $ui.append( `<i class='newline_hw_working fa fa-spin fa-spinner'></i>` );

      detectNativeClient( function handleNativeClient( resp ) {
        addMainContent( $ui, resp );
      } );
    } );
  }

  function addMainContent( $ui, resp ) {
    $ui
      .html( "" )
      .append( `<h5>Newline HW ${resp.status === "ok" ? 'detected' : 'not found'}</h5>` );

    if ( resp.status === "ok" ) {
      $ui.append( `Last Heartbeat at ${moment(resp.message_at).fromNow()}` );
      $ui.append( `<dl>` );

      Object.keys(resp.data).forEach(function showData(key) {
        $ui.append( `<dt>${key}</dt><dd>${resp.data[key]}</dd>` );
      });

      $ui.append( `</dl>` );
    } else {
      $.get( chrome.extension.getURL( HW_NO_CLIENT_TEMPLATE ) ).then( function( html ) {
        $ui.append( html );
      } );
    }
  }

  function addCloneLinksToUi() {
    detectNativeClient( function handleNativeClient( resp ) {
      if ( resp.status === "ok" ) {
        if ( pageData.assignment_submission ) {
          updateUIOnSubmissionPage();
        }
        if ( pageData.assignment ) {
          updateUIOnAssignmentPage();
        }
      }
    } );
  }

  function updateUIOnAssignmentPage() {
    const idFromUrl = uri => Number( uri.substr( uri.lastIndexOf( '/' ) + 1 ) );
    $( "#submissions a[href^='/admin/assignment_submissions']" ).closest( "td" ).each( function addLinks() {
      const $el = $( this );
      addCloneLinkForSubmissionTo(
        $el,
        idFromUrl( $el.find( "a[href^='/admin/assignment_submissions']" )[ 0 ].href ), {
          success_class: "label label-complete-and-satisfactory",
          fail_class: "label label-external-link"
        }
      );
    } );
  }

  function updateUIOnSubmissionPage() {
    addCloneLinkForSubmissionTo(
      $( '.edit_assignment_submission:eq(0)' ),
      pageData.assignment_submission.id, {
        success_class: "btn btn-primary btn-sm",
        fail_class: "btn btn-info btn-sm"
      }
    );
  }

  /**
   * Adds a link to an $el that will trigger a triggerCloneEventForSubmissionID
   * event for a submission_id when clicked.  If a submission_id cannot be cloned
   * display a revelant message to the user.
   *
   * @param {jQuery Element} $el the element to append the relevant link
   * to
   * @param {integer} submission_id the submission_id that is to be passed to
   * NewlineHW
   * @param {object} options configuration options for the link (currently
   * on success class and fail class)
   */
  function addCloneLinkForSubmissionTo( $el, submission_id, options = {} ) {
    isSubmissionCloneable( submission_id, function handleIsSubmissionCloneable( resp ) {
      if ( resp.data.cloneable ) {
        const clone_link = $el.append(
          `

            Clone Assignment Locally

          `
        );

        clone_link
          .find( '.clone_and_open_submission' )
          .click( function getSubmissionIDandCall( e ) {
            e.preventDefault();
            const self = $( this );

            self.append( `

            ` );

            triggerCloneEventForSubmissionID( submission_id, function() {
              self.find( ".newline_hw_working" ).remove();
            } );
          } );
      } else {
        $el.append(
          `

            Go To

          `
        );
      }
    } );
  }

  function detectNativeClient( callback ) {
    sendMessageToBackgroundWorker( {
      event: "heartbeat",
      data: {}
    }, callback );
  }

  function isSubmissionCloneable( submission_id, callback ) {
    sendMessageToBackgroundWorker( {
      event: "check_if_cloneable",
      data: {
        id: submission_id
      }
    }, callback );
  }

  function triggerCloneEventForSubmissionID( submission_id, callback ) {
    sendMessageToBackgroundWorker( {
      event: "clone_and_open_submission",
      data: {
        id: submission_id
      }
    }, callback );
  }

  /**
   * send json objects to the backgroup process for privledge esclation.
   *
   * @param  {object}   msg      event data to be sent to native client
   * @param  {Function} callback optional callback with response for native client
   */
  function sendMessageToBackgroundWorker( msg, callback ) {
    callback = ( typeof( callback ) === "function" && callback ) || function() {};
    chrome.runtime.sendMessage( msg, function( resp ) {
      console.log( "From Background page", resp );

      // Handle native client error message / timeout
      if ( resp && resp.status === "fail" ) {
        console.error( resp.message );
        tiy.showMessage( resp.message );
      }

      // Handle failure to commuicate with background page
      if ( typeof resp === "undefined" ) {
        console.error( chrome.runtime.lastError );
        tiy.showMessage( chrome.runtime.lastError );
      }

      callback( resp );
    } );
  }

} )( window.tiy || {}, window.moment );
<commit_msg>Switch to delegated event handler for clone and open submission event.<commit_after>( function( tiy, moment ) {
  'use strict';

  const HW_NO_CLIENT_TEMPLATE = 'templates/hw.html';

  let $ui = null;
  let pageData = {};

  tiy.loadModule( {
    name: 'hw',
    navIcon: 'fa-download',
    render: main
  } );

  function main( data, elem ) {
    $ui = $( elem );
    pageData = data;

    // On relevant pages add links
    if ( pageData.assignment || pageData.assignment_submission ) {
      addCloneLinksToUi();
    }

    $( $ui ).on( 'showing', function() {
      $ui.append( `<i class='newline_hw_working fa fa-spin fa-spinner'></i>` );

      detectNativeClient( function handleNativeClient( resp ) {
        addMainContent( $ui, resp );
      } );
    } );
  }

  function addMainContent( $ui, resp ) {
    $ui
      .html( "" )
      .append( `<h5>Newline HW ${resp.status === "ok" ? 'detected' : 'not found'}</h5>` );

    if ( resp.status === "ok" ) {
      $ui.append( `Last Heartbeat at ${moment(resp.message_at).fromNow()}` );
      $ui.append( `<dl>` );

      Object.keys(resp.data).forEach(function showData(key) {
        $ui.append( `<dt>${key}</dt><dd>${resp.data[key]}</dd>` );
      });

      $ui.append( `</dl>` );
    } else {
      $.get( chrome.extension.getURL( HW_NO_CLIENT_TEMPLATE ) ).then( function( html ) {
        $ui.append( html );
      } );
    }
  }

  function addCloneLinksToUi() {
    detectNativeClient( function handleNativeClient( resp ) {
      if ( resp.status === "ok" ) {
        if ( pageData.assignment_submission ) {
          updateUIOnSubmissionPage();
        }
        if ( pageData.assignment ) {
          updateUIOnAssignmentPage();
        }
      }
    } );
  }

  function updateUIOnAssignmentPage() {
    const idFromUrl = uri => Number( uri.substr( uri.lastIndexOf( '/' ) + 1 ) );
    $( "#submissions a[href^='/admin/assignment_submissions']" ).closest( "td" ).each( function addLinks() {
      const $el = $( this );
      addCloneLinkForSubmissionTo(
        $el,
        idFromUrl( $el.find( "a[href^='/admin/assignment_submissions']" )[ 0 ].href ), {
          success_class: "label label-complete-and-satisfactory",
          fail_class: "label label-external-link"
        }
      );
    } );
  }

  function updateUIOnSubmissionPage() {
    addCloneLinkForSubmissionTo(
      $( '.edit_assignment_submission:eq(0)' ),
      pageData.assignment_submission.id, {
        success_class: "btn btn-primary btn-sm",
        fail_class: "btn btn-info btn-sm"
      }
    );
  }

  /**
   * Adds a link to an $el that will trigger a triggerCloneEventForSubmissionID
   * event for a submission_id when clicked.  If a submission_id cannot be cloned
   * display a revelant message to the user.
   *
   * @param {jQuery Element} $el the element to append the relevant link
   * to
   * @param {integer} submission_id the submission_id that is to be passed to
   * NewlineHW
   * @param {object} options configuration options for the link (currently
   * on success class and fail class)
   */
  function addCloneLinkForSubmissionTo( $el, submission_id, options = {} ) {
    isSubmissionCloneable( submission_id, function handleIsSubmissionCloneable( resp ) {
      if ( resp.data.cloneable ) {
        $el.append(
          `

            Clone Assignment Locally

          `
        );

        $el.on( "click", ".clone_and_open_submission", function getSubmissionIDandCall( e ) {
          e.preventDefault();
          const self = $( this );

          self.append( `

            ` );

          triggerCloneEventForSubmissionID( submission_id, function() {
            self.find( ".newline_hw_working" ).remove();
          } );
        } );
      } else {
        $el.append(
          `

            Go To

          `
        );
      }
    } );
  }

  function detectNativeClient( callback ) {
    sendMessageToBackgroundWorker( {
      event: "heartbeat",
      data: {}
    }, callback );
  }

  function isSubmissionCloneable( submission_id, callback ) {
    sendMessageToBackgroundWorker( {
      event: "check_if_cloneable",
      data: {
        id: submission_id
      }
    }, callback );
  }

  function triggerCloneEventForSubmissionID( submission_id, callback ) {
    sendMessageToBackgroundWorker( {
      event: "clone_and_open_submission",
      data: {
        id: submission_id
      }
    }, callback );
  }

  /**
   * send json objects to the backgroup process for privledge esclation.
   *
   * @param  {object}   msg      event data to be sent to native client
   * @param  {Function} callback optional callback with response for native client
   */
  function sendMessageToBackgroundWorker( msg, callback ) {
    callback = ( typeof( callback ) === "function" && callback ) || function() {};
    chrome.runtime.sendMessage( msg, function( resp ) {
      console.log( "From Background page", resp );

      // Handle native client error message / timeout
      if ( resp && resp.status === "fail" ) {
        console.error( resp.message );
        tiy.showMessage( resp.message );
      }

      // Handle failure to commuicate with background page
      if ( typeof resp === "undefined" ) {
        console.error( chrome.runtime.lastError );
        tiy.showMessage( chrome.runtime.lastError );
      }

      callback( resp );
    } );
  }

} )( window.tiy || {}, window.moment );
<|endoftext|>


<commit_before>import React from 'react';
import moment from 'moment';
import { createMuiTheme } from 'material-ui/styles';
import yellow from 'material-ui/colors/yellow';
import Slide from 'material-ui/transitions/Slide';
import $ from 'jquery';

// = = = = B A C K E N D = = = = =

// for local testing against staging backend
const ajaxTarget = window.location.href.indexOf('rablabla.mybluemix.net') !== -1 ? '' : 'https://rablabla-staging.mybluemix.net';

const getParams = (args) => {
  const params = {};
  const pStrings = args.split('&');
  Object.keys(pStrings).forEach((param) => {
    const kvStrings = pStrings[param].split('=');
    params[kvStrings[0]] = kvStrings[1];
  });
  return params;
};

const getICSLink = (url, success, error) => {
  const deSuffix = '.de/rapla?';
  const baseURL = url.substring(0, url.indexOf(deSuffix) + deSuffix.length);
  const params = getParams(url.substring(url.indexOf(deSuffix) + deSuffix.length));
  if (params.key) {
    $.ajax({
      url: `${ajaxTarget}/Rablabla?url=${url}`,
      type: 'POST',
      success,
      error,
    });
    return 'Accessing calendar file...';
  } else if (params.user && params.file) {
    console.log(baseURL);
    success(`${baseURL}page=ical&user=${params.user}&file=${params.file}`);
  } else {
    console.error(`Yearly calendar not supported for url: ${url}`);
  }
  return 'Request denied.';
};

const getAppointments = (url, mmt, success, error, pre) => {
  pre(mmt);
  // backend uses monday as first day of the week
  // we use en locale so we make an exception for sundays
  $.ajax({
    url: `${ajaxTarget}/Rablabla?url=${encodeURIComponent(url)}&day=${mmt.day() > 0 ? mmt.date() : mmt.day(1).date()}&month=${mmt.month() + 1}&year=${mmt.year()}`,
    type: 'GET',
    success,
    error,
  });
  return 'Accessing appointments...';
};

const parseDates = (events) => {
  events.forEach((el) => {
    const dateElements = el.date.split('.');
    el.Date = moment().date(dateElements[0]).month(dateElements[1] - 1).year(dateElements[2]);
  });
  return events;
};

// check if there's a collision between the events a and b
const intersects = (a, b) => {
  const startTimeWrapperA = a.startTime.split(':');
  const endTimeWrapperA = a.endTime.split(':');
  const startMinA = startTimeWrapperA[0] * 60 + startTimeWrapperA[1];
  const endMinA = endTimeWrapperA[0] * 60 + endTimeWrapperA[1];

  const startTimeWrapperB = b.startTime.split(':');
  const endTimeWrapperB = b.endTime.split(':');
  const startMinB = startTimeWrapperB[0] * 60 + startTimeWrapperB[1];
  const endMinB = endTimeWrapperB[0] * 60 + endTimeWrapperB[1];

  return (startMinA <= startMinB && endMinA >= endMinB) // a contains(equals) b
    || (startMinA >= startMinB && endMinA <= endMinB) // b contains(equals) a
    || (startMinA < startMinB && endMinA < endMinB && endMinA > startMinB) // a intersects b
    || (startMinA > startMinB && endMinA > endMinB && startMinA < endMinB) // b intersects a
  ;
};

const makeDays = (events) => {
  const dailyEvents = [[], [], [], [], [], [], []];

  events.forEach((el) => {
    dailyEvents[el.Date.day()].push(el);
  });
  // XXX MAKE THINGS RUN!!!
  /* const resolveCollisions = (dayWrapper, el1) => {
    const collisions = dayWrapper[dayWrapper.length - 1].filter(el2 => intersects(el1, el2));
    if (collisions.length > 0) {
      const newLevel = [];
      collisions.forEach((elToShift) => {
        newLevel.push(elToShift);
      });
      dayWrapper.push(newLevel);
    }
  };

  dailyEvents.forEach((day) => {
    const dayWrapper = [day];
    day.forEach(el1 => resolveCollisions(dayWrapper, el1));
  }); */

  return dailyEvents;
};

// = = = = T H E M E = = = = =

const dhbwtimetablepalette = {
  50: '#f7e7e7',
  100: '#eac3c3',
  200: '#dd9c9c',
  300: '#cf7474',
  400: '#c45656',
  500: '#ba3838',
  600: '#b33232',
  700: '#ab2b2b',
  800: '#a32424',
  900: '#941717',
  A100: '#ffc9c9',
  A200: '#ff9696',
  A400: '#ff6363',
  A700: '#ff4a4a',
  contrastDefaultColor: 'light',
};

const slidingTransition = props => <Slide direction="up" {...props} />;

const theme = createMuiTheme({
  palette: {
    primary: dhbwtimetablepalette,
    secondary: {
      ...dhbwtimetablepalette,
      A400: 'white', // Accent color
    },
    error: yellow,
  },
});

// = = = = = = D A T E - U T I L S = = = = = = =

module.exports = {
  getParams,
  slidingTransition,
  theme,
  parseDates,
  makeDays,
  getAppointments,
  getICSLink,
};
<commit_msg>Implement untested preimplementation<commit_after>import React from 'react';
import moment from 'moment';
import { createMuiTheme } from 'material-ui/styles';
import yellow from 'material-ui/colors/yellow';
import Slide from 'material-ui/transitions/Slide';
import $ from 'jquery';

// = = = = B A C K E N D = = = = =

// for local testing against staging backend
const ajaxTarget = window.location.href.indexOf('rablabla.mybluemix.net') !== -1 ? '' : 'https://rablabla-staging.mybluemix.net';

const getParams = (args) => {
  const params = {};
  const pStrings = args.split('&');
  Object.keys(pStrings).forEach((param) => {
    const kvStrings = pStrings[param].split('=');
    params[kvStrings[0]] = kvStrings[1];
  });
  return params;
};

const getICSLink = (url, success, error) => {
  const deSuffix = '.de/rapla?';
  const baseURL = url.substring(0, url.indexOf(deSuffix) + deSuffix.length);
  const params = getParams(url.substring(url.indexOf(deSuffix) + deSuffix.length));
  if (params.key) {
    $.ajax({
      url: `${ajaxTarget}/Rablabla?url=${url}`,
      type: 'POST',
      success,
      error,
    });
    return 'Accessing calendar file...';
  } else if (params.user && params.file) {
    console.log(baseURL);
    success(`${baseURL}page=ical&user=${params.user}&file=${params.file}`);
  } else {
    console.error(`Yearly calendar not supported for url: ${url}`);
  }
  return 'Request denied.';
};

const getAppointments = (url, mmt, success, error, pre) => {
  pre(mmt);
  // backend uses monday as first day of the week
  // we use en locale so we make an exception for sundays
  $.ajax({
    url: `${ajaxTarget}/Rablabla?url=${encodeURIComponent(url)}&day=${mmt.day() > 0 ? mmt.date() : mmt.day(1).date()}&month=${mmt.month() + 1}&year=${mmt.year()}`,
    type: 'GET',
    success,
    error,
  });
  return 'Accessing appointments...';
};

const parseDates = (events) => {
  events.forEach((el) => {
    const dateElements = el.date.split('.');
    el.Date = moment().date(dateElements[0]).month(dateElements[1] - 1).year(dateElements[2]);
  });
  return events;
};

// check if there's a collision between the events a and b
const intersects = (a, b) => {
  const startTimeWrapperA = a.startTime.split(':');
  const endTimeWrapperA = a.endTime.split(':');
  const startMinA = startTimeWrapperA[0] * 60 + startTimeWrapperA[1];
  const endMinA = endTimeWrapperA[0] * 60 + endTimeWrapperA[1];

  const startTimeWrapperB = b.startTime.split(':');
  const endTimeWrapperB = b.endTime.split(':');
  const startMinB = startTimeWrapperB[0] * 60 + startTimeWrapperB[1];
  const endMinB = endTimeWrapperB[0] * 60 + endTimeWrapperB[1];

  return (startMinA <= startMinB && endMinA >= endMinB) // a contains(equals) b
    || (startMinA >= startMinB && endMinA <= endMinB) // b contains(equals) a
    || (startMinA < startMinB && endMinA < endMinB && endMinA > startMinB) // a intersects b
    || (startMinA > startMinB && endMinA > endMinB && startMinA < endMinB) // b intersects a
  ;
};

// divides a list of events into the maximum-non-colliding list of events and the rest
const splitGreedy = (eventStack) => {
  const filterFalse = [];
  let done = false;
  do {
    // count the intersections of each event
    eventStack.forEach((ev) => {
      ev.intersectionCount = 0;
      eventStack.filter(otherEvent => ev !== otherEvent).forEach((otherEvent) => {
        if (intersects(ev, otherEvent)) {
          ev.intersectionCount++;
        }
      });
    });

    // sort for intersection count
    eventStack.sort((a, b) => a.intersectionCount - b.intersectionCount);

    // if collisions remaining -> repeat without the max intersects element
    if (eventStack.filter(ev => ev.intersectionCount > 0).length > 0) {
      filterFalse.push(eventStack.pop());
    } else {
      done = true;
    }
  } while (!done);

  return { filterTrue: eventStack, filterFalse };
};

const splitterSearch = (possibleSolutions, todo, current) => {
  // get every event without collision to current
  todo.filter((testEv) => {
    return current.filter(safeEv => intersects(safeEv, testEv)).length === 0;
  }).forEach((semiSafeEv) => {
    const newSolution = current.concat([semiSafeEv]);
    const remaining = todo.filter(el => el !== semiSafeEv);
    splitterSearch(possibleSolutions, remaining, newSolution);
  });
};

// same as splitGreedy() but more intelligent
const splitter = (eventStack) => {
  const safe = [], todo = [];
  // count the intersections of each event
  eventStack.forEach((ev) => {
    ev.intersectionCount = 0;
    eventStack.filter(otherEvent => ev !== otherEvent).forEach((otherEvent) => {
      if (intersects(ev, otherEvent)) {
        ev.intersectionCount++;
      }
    });
  });

  // divide into safe and colliding
  eventStack.forEach((ev) => {
    (ev.intersectionCount > 0 ? todo : safe).push(ev);
  });

  const possibleSolutions = [];
  // if there are colliding elements
  if (todo.length > 0) {
    splitterSearch(possibleSolutions, todo, []);
    // search for biggest solution
    possibleSolutions.sort((arr1, arr2) => arr2.length - arr1.length);
    safe.concat(possibleSolutions[0]);
  }
  // merge with safe ones
  return {
    filterTrue: safe,
    filterFalse: eventStack.filter(ev => safe.indexOf(ev) === -1),
  };
};

const makeDays = (events) => {
  const dailyEvents = [[], [], [], [], [], [], []];

  // structure related to days
  events.forEach((el) => {
    dailyEvents[el.Date.day()].push(el);
  });

  dailyEvents.forEach((day) => {
    // init
    day.forEach((el) => {
      el.col = 0;
    });
    const todoStack = [day];
    const doneStack = [];

    // execute algorithm until no collisions remaining
    while (todoStack.length > 0) {
      const divison = splitter(todoStack.pop());
      // divison.filterFalse.forEach((collidingEvent) => {
      //   collidingEvent.col++;
      // });
      if (divison.filterFalse.length > 0) todoStack.push(divison.filterFalse);
      doneStack.push(divison.filterTrue);
    }

    // assign the col values
    doneStack.forEach((colLevel, i) => {
      colLevel.forEach((el) => {
        el.col = i;
      });
    });
  });

  console.log(dailyEvents);

  return dailyEvents;
};

// = = = = T H E M E = = = = =

const dhbwtimetablepalette = {
  50: '#f7e7e7',
  100: '#eac3c3',
  200: '#dd9c9c',
  300: '#cf7474',
  400: '#c45656',
  500: '#ba3838',
  600: '#b33232',
  700: '#ab2b2b',
  800: '#a32424',
  900: '#941717',
  A100: '#ffc9c9',
  A200: '#ff9696',
  A400: '#ff6363',
  A700: '#ff4a4a',
  contrastDefaultColor: 'light',
};

const slidingTransition = props => <Slide direction="up" {...props} />;

const theme = createMuiTheme({
  palette: {
    primary: dhbwtimetablepalette,
    secondary: {
      ...dhbwtimetablepalette,
      A400: 'white', // Accent color
    },
    error: yellow,
  },
});

// = = = = = = D A T E - U T I L S = = = = = = =

module.exports = {
  getParams,
  slidingTransition,
  theme,
  parseDates,
  makeDays,
  getAppointments,
  getICSLink,
};
<|endoftext|>


<commit_before>const GithubStrategy = require('passport-github2').Strategy;
const passport = require('passport');
const gitApi = require('../../config').GITHUB;
const User = require('../../server/db/dbmodel').Users;

passport.use(new GithubStrategy({
  clientID: gitApi.github.clientID || process.env.GITHUBSECRECT,
  clientSecret: gitApi.github.clientSecret || process.env.GITHUBID,
  callbackURL: gitApi.github.callbackURL,
}, (accessToken, refreshToken, profile, cb) => {
    User.findOne({ githubId: profile.id }, (err, user) => {
      if (err) {
        console.log(err);  // handle errors!
      } else if (!user) {
        user = new User({
          accessToken,
          refreshToken,
          githubId: profile.id,
          name: profile.displayName,
          created: Date.now(),
          company: profile._json.company,
          blog: profile._json.blog,
          location: profile._json.location,
          bio: profile._json.bio,
          html_url: profile._json.html_url,
          avatar_url: profile._json.avatar_url,
        });
        user.save((err) => {
          if (err) {
            console.log(err);  // handle errors!
          } else {
            console.log('INSIDE USER SAVE!', user);
            cb(null, user);
          }
        });
      } else {
        console.log('CCCCBBBB', cb, 'USER:', user);
        cb(null, user);
      }
    });
  }
));
<commit_msg>[ BUGFIX ] Add process env for URL<commit_after>const GithubStrategy = require('passport-github2').Strategy;
const passport = require('passport');
const gitApi = require('../../config').GITHUB;
const User = require('../../server/db/dbmodel').Users;

passport.use(new GithubStrategy({
  clientID: gitApi.github.clientID || process.env.GITHUBSECRECT,
  clientSecret: gitApi.github.clientSecret || process.env.GITHUBID,
  callbackURL: gitApi.github.callbackURL || process.env.URL,
}, (accessToken, refreshToken, profile, cb) => {
    User.findOne({ githubId: profile.id }, (err, user) => {
      if (err) {
        console.log(err);  // handle errors!
      } else if (!user) {
        user = new User({
          accessToken,
          refreshToken,
          githubId: profile.id,
          name: profile.displayName,
          created: Date.now(),
          company: profile._json.company,
          blog: profile._json.blog,
          location: profile._json.location,
          bio: profile._json.bio,
          html_url: profile._json.html_url,
          avatar_url: profile._json.avatar_url,
        });
        user.save((err) => {
          if (err) {
            console.log(err);  // handle errors!
          } else {
            console.log('INSIDE USER SAVE!', user);
            cb(null, user);
          }
        });
      } else {
        console.log('CCCCBBBB', cb, 'USER:', user);
        cb(null, user);
      }
    });
  }
));
<|endoftext|>


<commit_before>var async = require('async'),
    campfire = require('./campfire'),
    childProcess = require('child_process'),
    config = require('./config'),
    express = require('express'),
    staticShim = require('./static-shim');

var log = '',
    error = '';

var repo = require('./git-repo')(config.appDir, process.env.MOCK_REPO);
repo.init(function(err) {
  build(function(){});
});

function build(callback) {
  var target = config.buildTarget;
  if (!target || !target['build-command']) {
    return callback();
  }

  staticShim.init();
  var command = target['build-command'].replace(/\bjake\b/g, 'node ' + __dirname + '/../node_modules/jake/bin/cli.js');
  console.log('Building', command);
  childProcess.exec(command, {cwd: config.appDir + '/'}, function(err, stdout, stderr) {
    console.log('Build response', stdout, stderr);
    log += 'Build:\n' + stdout;
    error += 'Build:\n' + stderr;
    callback(err);
  });
}

module.exports = function(app) {
  var branches = [],
      currentBranch;

  app.get('/ms_admin', function(req, res, next) {
    async.parallel([
      function(callback) {
        repo.remoteBranches(function(err, data) {
          branches = data;
          callback(err);
        });
      },
      function(callback) {
        repo.currentBranch(function(err, data) {
          currentBranch = data;
          callback(err);
        });
      }
    ], function(err) {
      res.render('index', {
        gitPath: config.appDir,
        mocksEnabled: !!config.mocksEnabled,
        buildTarget: config.buildTarget || {},
        buildTargets: config.projectConfig['build-targets'] || [],
        servers: config.projectConfig.servers || [],
        proxyServer: config.proxyServer,
        branches: branches || [],
        currentBranch: currentBranch,
        log: log, error: error
      });
    });
  });

  app.all('/ms_admin/proxy-server', express.bodyParser(), function(req, res, next) {
    log = '';
    error = '';

    // Filter the user input
    var proxy = req.param('proxy');
    if ((config.projectConfig.servers || []).indexOf(proxy) < 0) {
      res.redirect('/ms_admin');
      return;
    }

    config.proxyServer = proxy;
    campfire.speak('proxy changed to ' + config.proxyServer);
    res.redirect('/ms_admin');
  });
  app.all('/ms_admin/mocks', express.bodyParser(), function(req, res, next) {
    log = '';
    error = '';

    config.mocksEnabled = req.param('enable-mocks');
    if (config.mocksEnabled === 'false') {
      config.mocksEnabled = false;
    }
    config.mocksEnabled = !!config.mocksEnabled;

    campfire.speak('mocksEnabled changed to ' + config.mocksEnabled);
    res.redirect('/ms_admin');
  });
  app.all('/ms_admin/build-target', express.bodyParser(), function(req, res, next) {
    log = '';
    error = '';

    // Filter the input
    var target = req.param('target');
    if ((config.projectConfig['build-targets'] || []).indexOf(target) < 0) {
      res.redirect('/ms_admin');
      return;
    }

    config.buildTarget = target;
    build(function() {
      campfire.speak('build target changed to ' + config.buildTarget.name);
      res.redirect('/ms_admin');
    });
  });
  app.all('/ms_admin/branch', express.bodyParser(), function(req, res, next) {
    log = '';
    error = '';

    // Filter the input
    var branch = req.param('branch'),
        sameBranch = currentBranch === branch;
    console.log('branch', branch, branches, branches.indexOf(branch));
    if (branches.indexOf(branch) < 0) {
      res.redirect('/ms_admin');
      return;
    }

    console.log('Switching to branch', branch);
    async.series([
      function(callback) {
        // Skip checkout if we are already on this branch
        if (sameBranch) {
          callback();
        } else {
          repo.checkout(branch, callback);
        }
      },
      function(callback) {
        repo.pull(!sameBranch, function(err) {
          callback(err);
        });
      },
      function(callback) {
        build(callback);
      }
    ],
    function(err) {
      err || campfire.speak('branch changed to ' + branch);
      res.redirect('/ms_admin');
    });
  });
  app.all('/ms_admin/pull', express.bodyParser(), function(req, res, next) {
    log = '';
    error = '';

    async.series([
      function(callback) {
        repo.pull(callback);
      },
      function(callback) {
        build(callback);
      }
    ],
    function(err) {
      if (err) {
        error = err + error;
      }

      err || campfire.speak('pulled from ' + currentBranch);
      res.redirect('/ms_admin');
    });
  });
};

module.exports.build = build;
<commit_msg>admin.pull impl<commit_after>var async = require('async'),
    campfire = require('./campfire'),
    childProcess = require('child_process'),
    config = require('./config'),
    express = require('express'),
    staticShim = require('./static-shim');

var log = '',
    error = '';

var repo = require('./git-repo')(config.appDir, process.env.MOCK_REPO);
repo.init(function(err) {
  build(function(){});
});

function build(callback) {
  var target = config.buildTarget;
  if (!target || !target['build-command']) {
    return callback();
  }

  staticShim.init();
  var command = target['build-command'].replace(/\bjake\b/g, 'node ' + __dirname + '/../node_modules/jake/bin/cli.js');
  console.log('Building', command);
  childProcess.exec(command, {cwd: config.appDir + '/'}, function(err, stdout, stderr) {
    console.log('Build response', stdout, stderr);
    log += 'Build:\n' + stdout;
    error += 'Build:\n' + stderr;
    callback(err);
  });
}

module.exports = function(app) {
  var branches = [],
      currentBranch;

  app.get('/ms_admin', function(req, res, next) {
    async.parallel([
      function(callback) {
        repo.remoteBranches(function(err, data) {
          branches = data;
          callback(err);
        });
      },
      function(callback) {
        repo.currentBranch(function(err, data) {
          currentBranch = data;
          callback(err);
        });
      }
    ], function(err) {
      res.render('index', {
        gitPath: config.appDir,
        mocksEnabled: !!config.mocksEnabled,
        buildTarget: config.buildTarget || {},
        buildTargets: config.projectConfig['build-targets'] || [],
        servers: config.projectConfig.servers || [],
        proxyServer: config.proxyServer,
        branches: branches || [],
        currentBranch: currentBranch,
        log: log, error: error
      });
    });
  });

  app.all('/ms_admin/proxy-server', express.bodyParser(), function(req, res, next) {
    log = '';
    error = '';

    // Filter the user input
    var proxy = req.param('proxy');
    if ((config.projectConfig.servers || []).indexOf(proxy) < 0) {
      res.redirect('/ms_admin');
      return;
    }

    config.proxyServer = proxy;
    campfire.speak('proxy changed to ' + config.proxyServer);
    res.redirect('/ms_admin');
  });
  app.all('/ms_admin/mocks', express.bodyParser(), function(req, res, next) {
    log = '';
    error = '';

    config.mocksEnabled = req.param('enable-mocks');
    if (config.mocksEnabled === 'false') {
      config.mocksEnabled = false;
    }
    config.mocksEnabled = !!config.mocksEnabled;

    campfire.speak('mocksEnabled changed to ' + config.mocksEnabled);
    res.redirect('/ms_admin');
  });
  app.all('/ms_admin/build-target', express.bodyParser(), function(req, res, next) {
    log = '';
    error = '';

    // Filter the input
    var target = req.param('target');
    if ((config.projectConfig['build-targets'] || []).indexOf(target) < 0) {
      res.redirect('/ms_admin');
      return;
    }

    config.buildTarget = target;
    build(function() {
      campfire.speak('build target changed to ' + config.buildTarget.name);
      res.redirect('/ms_admin');
    });
  });
  app.all('/ms_admin/branch', express.bodyParser(), function(req, res, next) {
    log = '';
    error = '';

    // Filter the input
    var branch = req.param('branch'),
        sameBranch = currentBranch === branch;
    console.log('branch', branch, branches, branches.indexOf(branch));
    if (branches.indexOf(branch) < 0) {
      res.redirect('/ms_admin');
      return;
    }

    console.log('Switching to branch', branch);
    async.series([
      function(callback) {
        // Skip checkout if we are already on this branch
        if (sameBranch) {
          callback();
        } else {
          repo.checkout(branch, callback);
        }
      },
      function(callback) {
        repo.pull(!sameBranch, function(err) {
          callback(err);
        });
      },
      function(callback) {
        build(callback);
      }
    ],
    function(err) {
      err || campfire.speak('branch changed to ' + branch);
      res.redirect('/ms_admin');
    });
  });
  app.all('/ms_admin/pull', express.bodyParser(), function(req, res, next) {
    log = '';
    error = '';

    module.exports.pull(function(err) {
      res.redirect('/ms_admin');
    });
  });
};

module.exports.pull = function(callback) {
  log = '';
  error = '';

  async.series([
    function(callback) {
      repo.pull(callback);
    },
    function(callback) {
      build(callback);
    }
  ],
  function(err) {
    if (err) {
      error = err + error;
    }

    err || campfire.speak('pulled from ' + currentBranch);
    callback && callback(err);
  });
};
module.exports.build = build;
<|endoftext|>


<commit_before>var i18n = new I18n('es', {
  colon: '#{msg}:',
  address_verified: 'Se verificó la dirección como',
  address_not_verified: 'No se pudo verificar dirección',
  no_results: 'Sin resultados',
  show_map: 'Mostrar mapa',
  update_coordinates: 'Actualizar coordinados',
  update_address: 'Actualizar dirección',
  address: 'Dirección',
  more_choices: 'Más opciones...',
  unresolved_conflicts: 'Favor de resolver todo conflicto antes de guardar.',
  undefined: 'Indefinido/a(s)',
  form_changed: 'Se han cambiado los contenidos anteriores del formulario sin guardar los cambios.'
});
<commit_msg>Unsupported browser message is not translated to Spanish<commit_after>var i18n = new I18n('es', {
  colon: '#{msg}:',
  address_verified: 'Se verificó la dirección como',
  address_not_verified: 'No se pudo verificar dirección',
  no_results: 'Sin resultados',
  show_map: 'Mostrar mapa',
  update_coordinates: 'Actualizar coordinados',
  update_address: 'Actualizar dirección',
  address: 'Dirección',
  more_choices: 'Más opciones...',
  unresolved_conflicts: 'Favor de resolver todo conflicto antes de guardar.',
  undefined: 'Indefinido/a(s)',
  form_changed: 'Se han cambiado los contenidos anteriores del formulario sin guardar los cambios.',
  unsupported_browser: 'You are using an unsupported browser(EN):',
  please_switch_to: 'Please switch to(EN)',
  or_higher: 'or higher(EN)',
  or: 'or(EN)'
});
<|endoftext|>


<commit_before>'use strict'

const ipfsd = require('../index.js')
const assert = require('assert')
const ipfsApi = require('ipfs-api')
const run = require('subcomandante')
const fs = require('fs')
const rimraf = require('rimraf')
const mkdirp = require('mkdirp')
const path = require('path')

// this comment is used by mocha, do not delete
/*global describe, before, it*/

describe('ipfs executable path', function () {
  this.timeout(2000)
  let Node

  it('has the correct path when installed with npm3', (done) => {
    process.env.testpath = '/tmp/ipfsd-ctl-test/node_modules/ipfsd-ctl/lib' // fake __dirname
    let npm3Path = '/tmp/ipfsd-ctl-test/node_modules/go-ipfs-dep/go-ipfs'

    mkdirp(npm3Path, (err) => {
      if (err) console.log(err)
      fs.writeFileSync(path.join(npm3Path, 'ipfs'))
      delete require.cache[require.resolve('../lib/node.js')]
      Node = require('../lib/node.js')
      var node = new Node()
      assert.equal(node.exec, '/tmp/ipfsd-ctl-test/node_modules/go-ipfs-dep/go-ipfs/ipfs')
      rimraf('/tmp/ipfsd-ctl-test', done)
    })
  })

  it('has the correct path when installed with npm2', (done) => {
    process.env.testpath = '/tmp/ipfsd-ctl-test/node_modules/ipfsd-ctl/lib' // fake __dirname
    let npm2Path = '/tmp/ipfsd-ctl-test/node_modules/ipfsd-ctl/node_modules/go-ipfs-dep/go-ipfs'

    mkdirp(npm2Path, (err) => {
      if (err) console.log(err)
      fs.writeFileSync(path.join(npm2Path, 'ipfs'))
      delete require.cache[require.resolve('../lib/node.js')]
      Node = require('../lib/node.js')
      var node = new Node()
      assert.equal(node.exec, '/tmp/ipfsd-ctl-test/node_modules/ipfsd-ctl/node_modules/go-ipfs-dep/go-ipfs/ipfs')
      rimraf('/tmp/ipfsd-ctl-test', done)
    })
  })
})

describe('disposable node with local api', function () {
  this.timeout(20000)
  let ipfs
  before((done) => {
    ipfsd.disposable((err, node) => {
      if (err) throw err
      node.startDaemon((err, ignore) => {
        if (err) throw err
        ipfs = ipfsApi(node.apiAddr)
        done()
      })
    })
  })

  it('should have started the daemon and returned an api', () => {
    assert(ipfs)
    assert(ipfs.id)
  })

  let store, retrieve

  before((done) => {
    const blorb = Buffer('blorb')
    ipfs.block.put(blorb, (err, res) => {
      if (err) throw err
      store = res.Key

      ipfs.block.get(res.Key, (err, res) => {
        if (err) throw err
        let buf = ''
        res
          .on('data', (data) => {
            buf += data
          })
          .on('end', () => {
            retrieve = buf
            done()
          })
      })
    })
  })
  it('should be able to store objects', () => {
    assert.equal(store, 'QmPv52ekjS75L4JmHpXVeuJ5uX2ecSfSZo88NSyxwA3rAQ')
  })
  it('should be able to retrieve objects', () => {
    assert.equal(retrieve, 'blorb')
  })
})

describe('disposableApi node', function () {
  this.timeout(20000)
  let ipfs
  before((done) => {
    ipfsd.disposableApi((err, api) => {
      if (err) throw err
      ipfs = api
      done()
    })
  })

  it('should have started the daemon and returned an api with host/port', () => {
    assert(ipfs)
    assert(ipfs.id)
    assert(ipfs.apiHost)
    assert(ipfs.apiPort)
  })

  let store, retrieve

  before((done) => {
    const blorb = Buffer('blorb')
    ipfs.block.put(blorb, (err, res) => {
      if (err) throw err
      store = res.Key

      ipfs.block.get(res.Key, (err, res) => {
        if (err) throw err
        let buf = ''
        res
          .on('data', (data) => {
            buf += data
          })
          .on('end', () => {
            retrieve = buf
            done()
          })
      })
    })
  })
  it('should be able to store objects', () => {
    assert.equal(store, 'QmPv52ekjS75L4JmHpXVeuJ5uX2ecSfSZo88NSyxwA3rAQ')
  })
  it('should be able to retrieve objects', () => {
    assert.equal(retrieve, 'blorb')
  })
})

describe('starting and stopping', function () {
  this.timeout(20000)
  let node

  describe('init', () => {
    before((done) => {
      ipfsd.disposable((err, res) => {
        if (err) throw err
        node = res
        done()
      })
    })

    it('should returned a node', () => {
      assert(node)
    })

    it('daemon should not be running', () => {
      assert(!node.daemonPid())
    })
  })

  let pid

  describe('starting', () => {
    let ipfs
    before((done) => {
      node.startDaemon((err, res) => {
        if (err) throw err

        pid = node.daemonPid()
        ipfs = res

        // actually running?
        run('kill', ['-0', pid])
          .on(err, (err) => { throw err })
          .on('end', () => { done() })
      })
    })

    it('should be running', () => {
      assert(ipfs.id)
    })
  })

  let stopped = false
  describe('stopping', () => {
    before((done) => {
      node.stopDaemon((err) => {
        if (err) throw err
        stopped = true
      })
      // make sure it's not still running
      const poll = setInterval(() => {
        run('kill', ['-0', pid])
          .on('error', () => {
            clearInterval(poll)
            done()
            done = () => {} // so it does not get called again
          })
      }, 100)
    })

    it('should be stopped', () => {
      assert(!node.daemonPid())
      assert(stopped)
    })
  })
})

describe('setting up and initializing a local node', () => {
  const testpath1 = '/tmp/ipfstestpath1'

  describe('cleanup', () => {
    before((done) => {
      rimraf(testpath1, done)
    })

    it('should not have a directory', () => {
      assert.equal(fs.existsSync('/tmp/ipfstestpath1'), false)
    })
  })

  describe('setup', () => {
    let node
    before((done) => {
      ipfsd.local(testpath1, (err, res) => {
        if (err) throw err
        node = res
        done()
      })
    })

    it('should have returned a node', () => {
      assert(node)
    })

    it('should not be initialized', () => {
      assert.equal(node.initialized, false)
    })

    describe('initialize', function () {
      this.timeout(10000)

      before((done) => {
        node.init((err) => {
          if (err) throw err
          done()
        })
      })

      it('should have made a directory', () => {
        assert.equal(fs.existsSync(testpath1), true)
      })

      it('should be initialized', () => {
        assert.equal(node.initialized, true)
      })

      it('should be initialized', () => {
        assert.equal(node.initialized, true)
      })
    })
  })
})

describe('change config values of a disposable node', function () {
  this.timeout(20000)

  let ipfsNode

  before((done) => {
    ipfsd.disposable((err, node) => {
      if (err) {
        throw err
      }
      ipfsNode = node
      done()
    })
  })

  it('Should return a config value', (done) => {
    ipfsNode.getConfig('Bootstrap', (err, config) => {
      if (err) {
        throw err
      }
      assert(config)
      done()
    })
  })

  it('Should set a config value', (done) => {
    ipfsNode.setConfig('Bootstrap', null, (err) => {
      if (err) {
        throw err
      }

      ipfsNode.getConfig('Bootstrap', (err, config) => {
        if (err) {
          throw err
        }
        assert.equal(config, 'null')
        done()
      })
    })
  })
})

describe('external ipfs binaray', () => {
  it('allows passing via $IPFS_EXEC', (done) => {
    process.env.IPFS_EXEC = '/some/path'
    ipfsd.local((err, node) => {
      if (err) throw err

      assert.equal(node.exec, '/some/path')

      process.env.IPFS_EXEC = ''
      done()
    })
  })
})

describe('version', () => {
  it('prints the version', (done) => {
    ipfsd.version((err, version) => {
      if (err) throw err

      assert(version)
      done()
    })
  })
})

describe('ipfs-api version', function () {
  this.timeout(20000)

  let ipfs

  before((done) => {
    ipfsd.disposable((err, node) => {
      if (err) throw err
      node.startDaemon((err, ignore) => {
        if (err) throw err
        ipfs = ipfsApi(node.apiAddr)
        done()
      })
    })
  })

  // NOTE: if you change ../lib/node.js, the hash will need to be changed
  it('uses the correct ipfs-api', (done) => {
    ipfs.add(path.join(__dirname, '../lib'), { recursive: true }, (err, res) => {
      if (err) throw err

      const added = res[res.length - 1]
      assert(added)
      assert.equal(added.Hash, 'QmdZt3Uiv3HZkHPsjGyWbrX1kMiRjst8cxQYsUjMqbXc7G')
      done()
    })
  })
})
<commit_msg>use squiggly brackets<commit_after>'use strict'

const ipfsd = require('../index.js')
const assert = require('assert')
const ipfsApi = require('ipfs-api')
const run = require('subcomandante')
const fs = require('fs')
const rimraf = require('rimraf')
const mkdirp = require('mkdirp')
const path = require('path')

// this comment is used by mocha, do not delete
/*global describe, before, it*/

describe('ipfs executable path', function () {
  this.timeout(2000)
  let Node

  it('has the correct path when installed with npm3', (done) => {
    process.env.testpath = '/tmp/ipfsd-ctl-test/node_modules/ipfsd-ctl/lib' // fake __dirname
    let npm3Path = '/tmp/ipfsd-ctl-test/node_modules/go-ipfs-dep/go-ipfs'

    mkdirp(npm3Path, (err) => {
      if (err) {
        console.log(err)
      }

      fs.writeFileSync(path.join(npm3Path, 'ipfs'))
      delete require.cache[require.resolve('../lib/node.js')]
      Node = require('../lib/node.js')
      var node = new Node()
      assert.equal(node.exec, '/tmp/ipfsd-ctl-test/node_modules/go-ipfs-dep/go-ipfs/ipfs')
      rimraf('/tmp/ipfsd-ctl-test', done)
    })
  })

  it('has the correct path when installed with npm2', (done) => {
    process.env.testpath = '/tmp/ipfsd-ctl-test/node_modules/ipfsd-ctl/lib' // fake __dirname
    let npm2Path = '/tmp/ipfsd-ctl-test/node_modules/ipfsd-ctl/node_modules/go-ipfs-dep/go-ipfs'

    mkdirp(npm2Path, (err) => {
      if (err) {
        console.log(err)
      }

      fs.writeFileSync(path.join(npm2Path, 'ipfs'))
      delete require.cache[require.resolve('../lib/node.js')]
      Node = require('../lib/node.js')
      var node = new Node()
      assert.equal(node.exec, '/tmp/ipfsd-ctl-test/node_modules/ipfsd-ctl/node_modules/go-ipfs-dep/go-ipfs/ipfs')
      rimraf('/tmp/ipfsd-ctl-test', done)
    })
  })
})

describe('disposable node with local api', function () {
  this.timeout(20000)
  let ipfs
  before((done) => {
    ipfsd.disposable((err, node) => {
      if (err) throw err
      node.startDaemon((err, ignore) => {
        if (err) throw err
        ipfs = ipfsApi(node.apiAddr)
        done()
      })
    })
  })

  it('should have started the daemon and returned an api', () => {
    assert(ipfs)
    assert(ipfs.id)
  })

  let store, retrieve

  before((done) => {
    const blorb = Buffer('blorb')
    ipfs.block.put(blorb, (err, res) => {
      if (err) throw err
      store = res.Key

      ipfs.block.get(res.Key, (err, res) => {
        if (err) throw err
        let buf = ''
        res
          .on('data', (data) => {
            buf += data
          })
          .on('end', () => {
            retrieve = buf
            done()
          })
      })
    })
  })
  it('should be able to store objects', () => {
    assert.equal(store, 'QmPv52ekjS75L4JmHpXVeuJ5uX2ecSfSZo88NSyxwA3rAQ')
  })
  it('should be able to retrieve objects', () => {
    assert.equal(retrieve, 'blorb')
  })
})

describe('disposableApi node', function () {
  this.timeout(20000)
  let ipfs
  before((done) => {
    ipfsd.disposableApi((err, api) => {
      if (err) throw err
      ipfs = api
      done()
    })
  })

  it('should have started the daemon and returned an api with host/port', () => {
    assert(ipfs)
    assert(ipfs.id)
    assert(ipfs.apiHost)
    assert(ipfs.apiPort)
  })

  let store, retrieve

  before((done) => {
    const blorb = Buffer('blorb')
    ipfs.block.put(blorb, (err, res) => {
      if (err) throw err
      store = res.Key

      ipfs.block.get(res.Key, (err, res) => {
        if (err) throw err
        let buf = ''
        res
          .on('data', (data) => {
            buf += data
          })
          .on('end', () => {
            retrieve = buf
            done()
          })
      })
    })
  })
  it('should be able to store objects', () => {
    assert.equal(store, 'QmPv52ekjS75L4JmHpXVeuJ5uX2ecSfSZo88NSyxwA3rAQ')
  })
  it('should be able to retrieve objects', () => {
    assert.equal(retrieve, 'blorb')
  })
})

describe('starting and stopping', function () {
  this.timeout(20000)
  let node

  describe('init', () => {
    before((done) => {
      ipfsd.disposable((err, res) => {
        if (err) throw err
        node = res
        done()
      })
    })

    it('should returned a node', () => {
      assert(node)
    })

    it('daemon should not be running', () => {
      assert(!node.daemonPid())
    })
  })

  let pid

  describe('starting', () => {
    let ipfs
    before((done) => {
      node.startDaemon((err, res) => {
        if (err) throw err

        pid = node.daemonPid()
        ipfs = res

        // actually running?
        run('kill', ['-0', pid])
          .on(err, (err) => { throw err })
          .on('end', () => { done() })
      })
    })

    it('should be running', () => {
      assert(ipfs.id)
    })
  })

  let stopped = false
  describe('stopping', () => {
    before((done) => {
      node.stopDaemon((err) => {
        if (err) throw err
        stopped = true
      })
      // make sure it's not still running
      const poll = setInterval(() => {
        run('kill', ['-0', pid])
          .on('error', () => {
            clearInterval(poll)
            done()
            done = () => {} // so it does not get called again
          })
      }, 100)
    })

    it('should be stopped', () => {
      assert(!node.daemonPid())
      assert(stopped)
    })
  })
})

describe('setting up and initializing a local node', () => {
  const testpath1 = '/tmp/ipfstestpath1'

  describe('cleanup', () => {
    before((done) => {
      rimraf(testpath1, done)
    })

    it('should not have a directory', () => {
      assert.equal(fs.existsSync('/tmp/ipfstestpath1'), false)
    })
  })

  describe('setup', () => {
    let node
    before((done) => {
      ipfsd.local(testpath1, (err, res) => {
        if (err) throw err
        node = res
        done()
      })
    })

    it('should have returned a node', () => {
      assert(node)
    })

    it('should not be initialized', () => {
      assert.equal(node.initialized, false)
    })

    describe('initialize', function () {
      this.timeout(10000)

      before((done) => {
        node.init((err) => {
          if (err) throw err
          done()
        })
      })

      it('should have made a directory', () => {
        assert.equal(fs.existsSync(testpath1), true)
      })

      it('should be initialized', () => {
        assert.equal(node.initialized, true)
      })

      it('should be initialized', () => {
        assert.equal(node.initialized, true)
      })
    })
  })
})

describe('change config values of a disposable node', function () {
  this.timeout(20000)

  let ipfsNode

  before((done) => {
    ipfsd.disposable((err, node) => {
      if (err) {
        throw err
      }
      ipfsNode = node
      done()
    })
  })

  it('Should return a config value', (done) => {
    ipfsNode.getConfig('Bootstrap', (err, config) => {
      if (err) {
        throw err
      }
      assert(config)
      done()
    })
  })

  it('Should set a config value', (done) => {
    ipfsNode.setConfig('Bootstrap', null, (err) => {
      if (err) {
        throw err
      }

      ipfsNode.getConfig('Bootstrap', (err, config) => {
        if (err) {
          throw err
        }
        assert.equal(config, 'null')
        done()
      })
    })
  })
})

describe('external ipfs binaray', () => {
  it('allows passing via $IPFS_EXEC', (done) => {
    process.env.IPFS_EXEC = '/some/path'
    ipfsd.local((err, node) => {
      if (err) throw err

      assert.equal(node.exec, '/some/path')

      process.env.IPFS_EXEC = ''
      done()
    })
  })
})

describe('version', () => {
  it('prints the version', (done) => {
    ipfsd.version((err, version) => {
      if (err) throw err

      assert(version)
      done()
    })
  })
})

describe('ipfs-api version', function () {
  this.timeout(20000)

  let ipfs

  before((done) => {
    ipfsd.disposable((err, node) => {
      if (err) throw err
      node.startDaemon((err, ignore) => {
        if (err) throw err
        ipfs = ipfsApi(node.apiAddr)
        done()
      })
    })
  })

  // NOTE: if you change ../lib/node.js, the hash will need to be changed
  it('uses the correct ipfs-api', (done) => {
    ipfs.add(path.join(__dirname, '../lib'), { recursive: true }, (err, res) => {
      if (err) throw err

      const added = res[res.length - 1]
      assert(added)
      assert.equal(added.Hash, 'QmdZt3Uiv3HZkHPsjGyWbrX1kMiRjst8cxQYsUjMqbXc7G')
      done()
    })
  })
})
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var matchesController = require('../db/dbcontrollers/matchesController.js');

module.exports = function (knex) {
  matchesController = matchesController(knex);

  router
    .param('matchId', function (req, res, next, matchId) {
      req.matchId = matchId;
      next();
    })
    .param('userId', function (req, res, next, userId) {
      req.userId = userId;
      next();
    });

  router.route('/')

  .get(function (req, res) {
    matchesController.getAllJoinableMatches(req.userId)
      .then(function (matches) {
        res.status(200).json({
          data: matches
        });
      })
      .catch(function (err) {
        res.status(404).json({
          message: err
        });
      });
  })

  .post(function (req, res) {
    var userId = req.body.userId;
    var startFunds = req.body.startFunds;
    var startDate = req.body.startdate;
    var endDate = req.body.enddate;
    var type = req.body.type;
    var title = req.body.title;

    matchesController.createMatch(userId, startFunds, type, startDate, endDate, title)
      .then(function (match) {
        return res.status(200).json({
          data: match
        });
      })
      .catch(function (err) {
        return res.status(400).json({
          message: err
        });
      });

  });

  router.route('/user/:userId')
    .get(function (req, res) {
      matchesController.getUsersMatches(req.userId)
        .then(function (matches) {
          res.status(200).json({
            data: matches
          });
        })
        .catch(function (err) {
          res.status(404).json({
            message: err
          });
        });
    });

  router.route('/:matchId')
    .put(function (req, res) {
      console.log(req.session);
      var userId = req.session.passport.user.u_id;

      matchesController.joinMatch(req.matchId, userId)
        .then(function (match) {
          if (match === null) {
            res.status(400).json({
              message: 'unable to join match. Please try another'
            });
          } else {
            res.status(200).json({
              data: match
            });
          }
        });
    })

  .get(function (req, res) {
    matchesController.getMatch(req.matchId)
      .then(function (match) {
        res.status(200).json({
          data: match
        });
      })
      .catch(function (err) {
        res.status(404).json({
          message: err
        });
      });
  });

  return router;
};
<commit_msg>fix bug with userId being passed to get list of joinable matches<commit_after>var express = require('express');
var router = express.Router();
var matchesController = require('../db/dbcontrollers/matchesController.js');

module.exports = function (knex) {
  matchesController = matchesController(knex);

  router
    .param('matchId', function (req, res, next, matchId) {
      req.matchId = matchId;
      next();
    })
    .param('userId', function (req, res, next, userId) {
      req.userId = userId;
      next();
    });

  router.route('/')

  .get(function (req, res) {
    matchesController.getAllJoinableMatches(req.user.u_id)
      .then(function (matches) {
        res.status(200).json({
          data: matches
        });
      })
      .catch(function (err) {
        res.status(404).json({
          message: err
        });
      });
  })

  .post(function (req, res) {
    var userId = req.body.userId;
    var startFunds = req.body.startFunds;
    var startDate = req.body.startdate;
    var endDate = req.body.enddate;
    var type = req.body.type;
    var title = req.body.title;

    matchesController.createMatch(userId, startFunds, type, startDate, endDate, title)
      .then(function (match) {
        return res.status(200).json({
          data: match
        });
      })
      .catch(function (err) {
        return res.status(400).json({
          message: err
        });
      });

  });

  router.route('/user/:userId')
    .get(function (req, res) {
      matchesController.getUsersMatches(req.userId)
        .then(function (matches) {
          res.status(200).json({
            data: matches
          });
        })
        .catch(function (err) {
          res.status(404).json({
            message: err
          });
        });
    });

  router.route('/:matchId')
    .put(function (req, res) {
      console.log(req.session);
      var userId = req.session.passport.user.u_id;

      matchesController.joinMatch(req.matchId, userId)
        .then(function (match) {
          if (match === null) {
            res.status(400).json({
              message: 'unable to join match. Please try another'
            });
          } else {
            res.status(200).json({
              data: match
            });
          }
        });
    })

  .get(function (req, res) {
    matchesController.getMatch(req.matchId)
      .then(function (match) {
        res.status(200).json({
          data: match
        });
      })
      .catch(function (err) {
        res.status(404).json({
          message: err
        });
      });
  });

  return router;
};
<|endoftext|>


<commit_before>module.exports = function(
  $stateProvider,
  $urlRouterProvider,
  $urlMatcherFactoryProvider
) {
  // Disable ui-router strict mode
  $urlMatcherFactoryProvider.strictMode(false);

  // Render 404 when no routes are matched
  $urlRouterProvider.otherwise('/404');

  $stateProvider
    .state('root', {
      abstract: true,
      templateUrl: 'app/templates/default.html',
      resolve: {
        loadEndpoints: function ($rootScope, API, $q) {
          $rootScope.apiLoaded = false;
          var deferred = $q.defer();
          var gapiInterval = window.setInterval(function() {
            if ($rootScope.apiLoaded) {
              window.clearInterval(gapiInterval);
              return;
            }

            gapi.client.load(API.NAME, API.VERSION, function (data) {
              $rootScope.apiLoaded = true;
              deferred.resolve();
            }, API.URL);
          }, 200);

          return deferred.promise;
        }
      }
    })
    .state('404', {
      url: '/404',
      templateUrl: 'app/templates/404.html'
    });
};
<commit_msg>[TECG-272][TECG-321] Add page title to error page<commit_after>module.exports = function(
  $stateProvider,
  $urlRouterProvider,
  $urlMatcherFactoryProvider
) {
  // Disable ui-router strict mode
  $urlMatcherFactoryProvider.strictMode(false);

  // Render 404 when no routes are matched
  $urlRouterProvider.otherwise('/404');

  $stateProvider
    .state('root', {
      abstract: true,
      templateUrl: 'app/templates/default.html',
      resolve: {
        loadEndpoints: function ($rootScope, API, $q) {
          $rootScope.apiLoaded = false;
          var deferred = $q.defer();
          var gapiInterval = window.setInterval(function() {
            if ($rootScope.apiLoaded) {
              window.clearInterval(gapiInterval);
              return;
            }

            gapi.client.load(API.NAME, API.VERSION, function (data) {
              $rootScope.apiLoaded = true;
              deferred.resolve();
            }, API.URL);
          }, 200);

          return deferred.promise;
        }
      }
    })
    .state('404', {
      url: '/404',
      controller : function (AppService) {
        AppService.setPageTitle('Página não encontrada');
      },
      templateUrl: 'app/templates/404.html'
    });
};
<|endoftext|>


<commit_before>var pg = require('pg');
var Joi = require('joi');
var DB = require('../db');
var Hapi = require('hapi');
var Util = require('util');
var _ = require('../libs/underscore.1.6.0.min');
var nodemailer = require('nodemailer');

var MOCK_DATA = [
  {
    id: 1,

    reservationTitle: "Mr. & Mrs. Robert Shaw",

    addressLineOne: "12345 Street One",
    addressLineTwo: "Apt 111",
    addressCity: "Some City",
    addressState: "IN",
    addressZipCode: "554433",

    rsvpCode: "d18cb7",
    emailAddress: "test@test.com",

    reservationNotes: "",
    dietaryRestrictions: "",
    notesForBrideGroom: "",

    isInvitedToRehearsalDinner: true,
    isAttendingBigDay: 1,
    isAttendingRehearsalDinner: 0,

    contacts: [
    {
      id: 1,
      firstName: "FirstName1",
      middleName: "MiddleName1",
      lastName: "LastName1",
      isChild: false,
      isAttendingBigDay: 1,
      isAttendingRehearsalDinner: 0,
    },
    {
      id: 4,
      firstName: "FirstName2",
      middleName: "MiddleName2",
      lastName: "LastName2",
      isChild: false,
      isAttendingBigDay: 1,
      isAttendingRehearsalDinner: 0,
    }]
  },
  {
    id: 2,

    isInvitedToRehearsalDinner: false,
    isAttendingBigDay: -1,
    isAttendingRehearsalDinner: -1,

    reservationTitle: "Mr. & Mrs. Natalie Merz",

    addressLineOne: "1 This Way",
    addressLineTwo: "",
    addressCity: "Firstly",
    addressState: "IN",
    addressZipCode: "11223",

    reservationNotes: "",
    dietaryRestrictions: "",
    notesForBrideGroom: "",

    rsvpCode: "abcde",
    emailAddress: "rabcd@rest.com",

    contacts: [
    {
      id: 6,
      firstName: "Some",
      middleName: "Middle",
      lastName: "Name",
      isChild: false,
      isAttendingBigDay: -1,
      isAttendingRehearsalDinner: -1,
    },
    {
      id: 13,
      firstName: "Fname",
      middleName: "Mname",
      lastName: "Lname",
      isChild: true,
      isAttendingBigDay: -1,
      isAttendingRehearsalDinner: -1,
    }]
  }
];

var INSERT_NEW_CONTACT_SQL = 'INSERT INTO contact (reservation_id, first_name, middle_name, last_name, '
    + ' is_child, is_attending_big_day, is_attending_rehearsal_dinner )'
    + ' VALUES '
    + ' ($1, $2, $3, $4, $5, $6, $7'
    + ' ) RETURNING id';

var INSERT_NEW_RESERVATION_SQL = 'INSERT INTO reservation (reservation_Title, rsvp_Code_Source, '
    + ' address_Line_One, address_Line_Two, '
    + 'address_City, address_State, address_Zip_Code, rsvp_Code, email_Address, reservation_Notes, '
    + 'dietary_Restrictions, notes_For_Bride_Groom, is_Invited_To_Rehearsal_Dinner, is_Attending_Big_Day, is_Attending_Rehearsal_Dinner '
    + ', create_date, modified_date) '
    + ' VALUES '
    + ' ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, '
    + ' CURRENT_TIMESTAMP, CURRENT_TIMESTAMP'
    + ' ) RETURNING id';

function handleError(err, reply) {
  var message = (err && err.message) || (err || "An unknown error occurred");
  console.error(err, message);
  if (err.stack) {
    console.error(err.stack);
  }
  reply(Hapi.error.internal(err));
}

var transporter = nodemailer.createTransport({
    service: Config.mail.provider,
    auth: {
        user: Config.mail.providerUserName,
        pass: Config.mail.providerPassword
    }
});

function sendEmailWithDetails(rsvpCode, reservationData) {
  transporter.sendMail({
      from: Config.mail.fromAddress,
      to: Config.mail.toAddress,
      subject: Util.format('Reservation Saved - %s : RSVP Code [%s]', reservationData.reservationTitle, rsvpCode),
      text: JSON.stringify(reservationData, undefined, 2)
  });
}

exports.retrieveReservation = {
  handler: function(request, reply) {
    //var reservation = MOCK_DATA.filter(function(c) { return c.rsvpCode == request.params.rsvpCode });
    DB.reservation.get(request.params.rsvpCode)
      .then(function(reservation) {
        reply({reservation: reservation});
      })
      .catch(function(err) {
        handleError(err, reply);
      });
  }
};

exports.updateReservation = {
  handler: function(request, reply) {
    var requestReservation = request.payload.reservation;

    if (!requestReservation || !requestReservation.rsvpCode) {
      reply(Hapi.error.badRequest("Invalid request"));
      return;
    }

    var rsvpCode = requestReservation.rsvpCode;

    sendEmailWithDetails(rsvpCode, requestReservation);

    DB.reservation.get(rsvpCode)
      .then(function(_) {
        return DB.reservation.update(requestReservation);
      })
      .then(function(reservation) {
        reply({ message: "OK" });
      })
      .catch(function(err) {
        handleError(err, reply);
      })
  }
}
<commit_msg>Suppress errors and include Config (#14).<commit_after>var pg = require('pg');
var Joi = require('joi');
var DB = require('../db');
var Hapi = require('hapi');
var Util = require('util');
var Config = require('../config');
var _ = require('../libs/underscore.1.6.0.min');
var nodemailer = require('nodemailer');

var MOCK_DATA = [
  {
    id: 1,

    reservationTitle: "Mr. & Mrs. Robert Shaw",

    addressLineOne: "12345 Street One",
    addressLineTwo: "Apt 111",
    addressCity: "Some City",
    addressState: "IN",
    addressZipCode: "554433",

    rsvpCode: "d18cb7",
    emailAddress: "test@test.com",

    reservationNotes: "",
    dietaryRestrictions: "",
    notesForBrideGroom: "",

    isInvitedToRehearsalDinner: true,
    isAttendingBigDay: 1,
    isAttendingRehearsalDinner: 0,

    contacts: [
    {
      id: 1,
      firstName: "FirstName1",
      middleName: "MiddleName1",
      lastName: "LastName1",
      isChild: false,
      isAttendingBigDay: 1,
      isAttendingRehearsalDinner: 0,
    },
    {
      id: 4,
      firstName: "FirstName2",
      middleName: "MiddleName2",
      lastName: "LastName2",
      isChild: false,
      isAttendingBigDay: 1,
      isAttendingRehearsalDinner: 0,
    }]
  },
  {
    id: 2,

    isInvitedToRehearsalDinner: false,
    isAttendingBigDay: -1,
    isAttendingRehearsalDinner: -1,

    reservationTitle: "Mr. & Mrs. Natalie Merz",

    addressLineOne: "1 This Way",
    addressLineTwo: "",
    addressCity: "Firstly",
    addressState: "IN",
    addressZipCode: "11223",

    reservationNotes: "",
    dietaryRestrictions: "",
    notesForBrideGroom: "",

    rsvpCode: "abcde",
    emailAddress: "rabcd@rest.com",

    contacts: [
    {
      id: 6,
      firstName: "Some",
      middleName: "Middle",
      lastName: "Name",
      isChild: false,
      isAttendingBigDay: -1,
      isAttendingRehearsalDinner: -1,
    },
    {
      id: 13,
      firstName: "Fname",
      middleName: "Mname",
      lastName: "Lname",
      isChild: true,
      isAttendingBigDay: -1,
      isAttendingRehearsalDinner: -1,
    }]
  }
];

var INSERT_NEW_CONTACT_SQL = 'INSERT INTO contact (reservation_id, first_name, middle_name, last_name, '
    + ' is_child, is_attending_big_day, is_attending_rehearsal_dinner )'
    + ' VALUES '
    + ' ($1, $2, $3, $4, $5, $6, $7'
    + ' ) RETURNING id';

var INSERT_NEW_RESERVATION_SQL = 'INSERT INTO reservation (reservation_Title, rsvp_Code_Source, '
    + ' address_Line_One, address_Line_Two, '
    + 'address_City, address_State, address_Zip_Code, rsvp_Code, email_Address, reservation_Notes, '
    + 'dietary_Restrictions, notes_For_Bride_Groom, is_Invited_To_Rehearsal_Dinner, is_Attending_Big_Day, is_Attending_Rehearsal_Dinner '
    + ', create_date, modified_date) '
    + ' VALUES '
    + ' ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, '
    + ' CURRENT_TIMESTAMP, CURRENT_TIMESTAMP'
    + ' ) RETURNING id';

function handleError(err, reply) {
  var message = (err && err.message) || (err || "An unknown error occurred");
  console.error(err, message);
  if (err.stack) {
    console.error(err.stack);
  }
  reply(Hapi.error.internal(err));
}

var transporter = nodemailer.createTransport({
    service: Config.mail.provider,
    auth: {
        user: Config.mail.providerUserName,
        pass: Config.mail.providerPassword
    }
});

function sendEmailWithDetails(rsvpCode, reservationData) {
  try
  {
    transporter.sendMail({
        from: Config.mail.fromAddress,
        to: Config.mail.toAddress,
        subject: Util.format('Reservation Saved - %s : RSVP Code [%s]', reservationData.reservationTitle, rsvpCode),
        text: JSON.stringify(reservationData, undefined, 2)
    });
  } catch (err) {}
}

exports.retrieveReservation = {
  handler: function(request, reply) {
    //var reservation = MOCK_DATA.filter(function(c) { return c.rsvpCode == request.params.rsvpCode });
    DB.reservation.get(request.params.rsvpCode)
      .then(function(reservation) {
        reply({reservation: reservation});
      })
      .catch(function(err) {
        handleError(err, reply);
      });
  }
};

exports.updateReservation = {
  handler: function(request, reply) {
    var requestReservation = request.payload.reservation;

    if (!requestReservation || !requestReservation.rsvpCode) {
      reply(Hapi.error.badRequest("Invalid request"));
      return;
    }

    var rsvpCode = requestReservation.rsvpCode;

    sendEmailWithDetails(rsvpCode, requestReservation);

    DB.reservation.get(rsvpCode)
      .then(function(_) {
        return DB.reservation.update(requestReservation);
      })
      .then(function(reservation) {
        reply({ message: "OK" });
      })
      .catch(function(err) {
        handleError(err, reply);
      })
  }
}
<|endoftext|>


<commit_before>'use strict';

var EventEmitter = require('events').EventEmitter;
var util = require('util');
var i18n = require('i18next');
var sprintf = require('i18next-sprintf-postprocessor');
var attributesHelper = require('./DynamoAttributesHelper');
var mobileAnalyticsHelper = require('./MobileAnalyticsHelper');
var responseHandlers = require('./response');
var _StateString = 'STATE';

function AlexaRequestEmitter() {
    EventEmitter.call(this);
}

util.inherits(AlexaRequestEmitter, EventEmitter);

function alexaRequestHandler(event, context, callback) {
    if (!event.session) {
        event.session = { 'attributes': {} };
    } else if (!event.session['attributes']) {
        event.session['attributes'] = {};
    }

    var handler = new AlexaRequestEmitter();
    handler.setMaxListeners(Infinity);

    Object.defineProperty(handler, '_event', {
        value: event,
        writable: false
    });

    Object.defineProperty(handler, '_context', {
        value: context,
        writable: false
    });

    Object.defineProperty(handler, '_callback', {
        value: callback,
        writable: false
    });

    Object.defineProperty(handler, 'state', {
        value: null,
        writable: true
    });

    Object.defineProperty(handler, 'appId', {
        value: null,
        writable: true
    });

    Object.defineProperty(handler, 'response', {
        value: {},
        writable: true
    });

    Object.defineProperty(handler, 'dynamoDBTableName', {
        value: null,
        writable: true
    });

    Object.defineProperty(handler, 'saveBeforeResponse', {
        value: false,
        writable: true
    });

    Object.defineProperty(handler, 'i18n', {
        value: i18n,
        writable: true
    });

    Object.defineProperty(handler, 'locale', {
        value: undefined,
        writable: true
    });

    Object.defineProperty(handler, 'resources', {
        value: undefined,
        writable: true
    });

    Object.defineProperty(handler, 'registerHandlers', {
        value: function() {
            RegisterHandlers.apply(handler, arguments);
        },
        writable: false
    });

    Object.defineProperty(handler, 'execute', {
        value: function() {
            HandleLambdaEvent.call(handler);
        },
        writable: false
    });

    Object.defineProperty(handler, 'mobileAnalyticsSettings', {
        value: null,
        writable: true
    });

    Object.defineProperty(handler, 'mobileAnalyticsHelper', {
        value: null,
        writable: true
    });

    handler.registerHandlers(responseHandlers);

    return handler;
}

function HandleLambdaEvent() {
    this.locale = this._event.request.locale;
    this.mobileAnalyticsSettings.locale = this.locale;

    if(this.resources) {
        this.i18n.use(sprintf).init({
            overloadTranslationOptionHandler: sprintf.overloadTranslationOptionHandler,
            returnObjects: true,
            lng: this.locale,
            resources: this.resources
        }, (err, t) => {
            if(err) {
                throw new Error('Error initializing i18next: ' + err);
            }
            ValidateRequest.call(this);
        });
    } else {
        ValidateRequest.call(this);
    }
}

function ValidateRequest() {
    var event = this._event;
    var context = this._context;
    var handlerAppId = this.appId;

    var requestAppId = '';
    var userId = '';

    // Long-form audio enabled skills use event.context
    if (event.context) {
        requestAppId = event.context.System.application.applicationId;
        userId = event.context.System.user.userId;
    } else if (event.session) {
        requestAppId = event.session.application.applicationId;
        userId = event.session.user.userId;
    }

    if (!this.mobileAnalyticsSettings.clientId) {
        this.mobileAnalyticsSettings.clientId = userId;
    }

    if (this.mobileAnalyticsSettings && this.mobileAnalyticsSettings.appId) {
        this.mobileAnalyticsHelper = new mobileAnalyticsHelper(this.mobileAnalyticsSettings);
    }

    if(!handlerAppId){
        console.log('Warning: Application ID is not set');
    }

    try {
        // Validate that this request originated from authorized source.
        if (handlerAppId && (requestAppId !== handlerAppId)) {
            console.log(`The applicationIds don\'t match: ${requestAppId} and ${handlerAppId}`);
            return context.fail('Invalid ApplicationId: ' + handlerAppId);
        }

        if (this.mobileAnalyticsHelper) {

            if (event.session.sessionId && event.session['new']) {
                this.mobileAnalyticsHelper.startSession(event.session.sessionId);
            }

            var maAttributes = {};

            if (event.request.intent) {
                maAttributes['IntentName'] = event.request.intent.name;

                if (event.request.intent.slots != undefined) {
                    for (var key in event.request.intent.slots) {
                        if (event.request.intent.slots.hasOwnProperty(key)) {
                            var name = event.request.intent.slots[key].name;
                            maAttributes[name] = event.request.intent.slots[key].value;
                        }
                    }
                }
            }

            this.mobileAnalyticsHelper.recordEvent(event.request.type, event.session.sessionId, maAttributes);
        }

        if(this.dynamoDBTableName && (!event.session.sessionId || event.session['new']) ) {
            attributesHelper.get(this.dynamoDBTableName, userId, (err, data) => {
                if(err) {
                    return context.fail('Error fetching user state: ' + err);
                }

                Object.assign(this._event.session.attributes, data);

                EmitEvent.call(this);
            });
        } else {
            EmitEvent.call(this);
        }
    } catch (e) {
        console.log(`Unexpected exception '${e}':\n${e.stack}`);
        context.fail(e);
    }
}

function EmitEvent() {
    this.state = this._event.session.attributes[_StateString] || '';

    var eventString = '';

    if (this._event.session['new'] && this.listenerCount('NewSession' + this.state) === 1) {
        eventString = 'NewSession';
    } else if(this._event.request.type === 'LaunchRequest') {
        eventString = 'LaunchRequest';
    } else if(this._event.request.type === 'IntentRequest') {
        eventString = this._event.request.intent.name;
    } else if (this._event.request.type === 'SessionEndedRequest'){
        eventString = 'SessionEndedRequest';
    } else if (this._event.request.type.substring(0,11) === 'AudioPlayer') {
        eventString = this._event.request.type.substring(12);
    } else if (this._event.request.type.substring(0,18) === 'PlaybackController') {
        eventString = this._event.request.type.substring(19);
    }

    eventString += this.state;

    if(this.listenerCount(eventString) < 1) {
        eventString = 'Unhandled' + this.state;
    }

    if(this.listenerCount(eventString) < 1){
        throw new Error(`No 'Unhandled' function defined for event: ${eventString}`);
    }

    this.emit(eventString);
}

function RegisterHandlers() {
    for(var arg = 0; arg < arguments.length; arg++) {
        var handlerObject = arguments[arg];

        if(!isObject(handlerObject)) {
            throw new Error(`Argument #${arg} was not an Object`);
        }

        var eventNames = Object.keys(handlerObject);

        for(var i = 0; i < eventNames.length; i++) {
            if(typeof(handlerObject[eventNames[i]]) !== 'function') {
                throw new Error(`Event handler for '${eventNames[i]}' was not a function`);
            }

            var eventName = eventNames[i];

            if(handlerObject[_StateString]) {
                eventName += handlerObject[_StateString];
            }

            var localize = function() {
                return this.i18n.t.apply(this.i18n, arguments);
            };

            var recordEvent = function() {
                return this.mobileAnalyticsHelper.recordEvent.apply(this.mobileAnalyticsHelper, arguments);
            }

            var handlerContext = {
                on: this.on.bind(this),
                emit: this.emit.bind(this),
                emitWithState: EmitWithState.bind(this),
                state: this.state,
                handler: this,
                i18n: this.i18n,
                locale: this.locale,
                t : localize,
                event: this._event,
                attributes: this._event.session.attributes,
                context: this._context,
                name: eventName,
                isOverridden:  IsOverridden.bind(this, eventName),
                response: ResponseBuilder(this),
                recordMobileAnalyticsEvent: recordEvent
            };

            this.on(eventName, handlerObject[eventNames[i]].bind(handlerContext));
        }
    }
}

function isObject(obj) {
    return (!!obj) && (obj.constructor === Object);
}

function IsOverridden(name) {
    return this.listenerCount(name) > 1;
}

function ResponseBuilder(self) {
    var responseObject = self.response;
    responseObject.version = '1.0';
    responseObject.response = {
        shouldEndSession: true
    };
    responseObject.sessionAttributes = self._event.session.attributes;

    return (function () {
        return {
            'speak': function (speechOutput) {
                responseObject.response.outputSpeech = createSSMLSpeechObject(speechOutput);
                return this;
            },
            'listen': function (repromptSpeech) {
                responseObject.response.reprompt = {
                    outputSpeech: createSSMLSpeechObject(repromptSpeech)
                };
                responseObject.response.shouldEndSession = false;
                return this;
            },
            'cardRenderer': function (cardTitle, cardContent, cardImage) {
                var card = {
                    type: 'Simple',
                    title: cardTitle,
                    content: cardContent
                };

                if(cardImage && (cardImage.smallImageUrl || cardImage.largeImageUrl)) {
                    card.type = 'Standard';
                    card['image'] = {};

                    delete card.content;
                    card.text = cardContent;

                    if(cardImage.smallImageUrl) {
                        card.image['smallImageUrl'] = cardImage.smallImageUrl;
                    }

                    if(cardImage.largeImageUrl) {
                        card.image['largeImageUrl'] = cardImage.largeImageUrl;
                    }
                }

                responseObject.response.card = card;
                return this;
            },
            'linkAccountCard': function () {
                responseObject.response.card = {
                    type: 'LinkAccount'
                };
                return this;
            },
            'audioPlayer': function (directiveType, behavior, url, token, expectedPreviousToken, offsetInMilliseconds) {
                var audioPlayerDirective;
                if (directiveType === 'play') {
                    audioPlayerDirective = {
                        "type": "AudioPlayer.Play",
                        "playBehavior": behavior,
                        "audioItem": {
                            "stream": {
                                "url": url,
                                "token": token,
                                "expectedPreviousToken": expectedPreviousToken,
                                "offsetInMilliseconds": offsetInMilliseconds
                            }
                        }
                    };
                } else if (directiveType === 'stop') {
                    audioPlayerDirective = {
                        "type": "AudioPlayer.Stop"
                    };
                } else {
                    audioPlayerDirective = {
                        "type": "AudioPlayer.Stop",
                        "clearBehavior": behavior
                    };
                }

                responseObject.response.directives = [audioPlayerDirective];
                return this;
            },
            'audioPlayerPlay': function (behavior, url, token, expectedPreviousToken, offsetInMilliseconds) {
                var audioPlayerDirective = {
                    "type": "AudioPlayer.Play",
                    "playBehavior": behavior,
                    "audioItem": {
                        "stream": {
                            "url": url,
                            "token": token,
                            "expectedPreviousToken": expectedPreviousToken,
                            "offsetInMilliseconds": offsetInMilliseconds
                        }
                    }
                };

                responseObject.response.directives = [audioPlayerDirective];
                return this;
            },
            'audioPlayerStop': function () {
                var audioPlayerDirective = {
                    "type": "AudioPlayer.Stop"
                };

                responseObject.response.directives = [audioPlayerDirective];
                return this;
            },
            'audioPlayerClearQueue': function (clearBehavior) {
                var audioPlayerDirective = {
                    "type": "AudioPlayer.ClearQueue",
                    "playBehavior": clearBehavior
                };

                responseObject.response.directives = [audioPlayerDirective];
                return this;
            }
        }
    })();
}

function createSSMLSpeechObject(message) {
    return {
        type: 'SSML',
        ssml: `<speak> ${message} </speak>`
    };
}

function createStateHandler(state, obj){
    if(!obj) {
        obj = {};
    }

    Object.defineProperty(obj, _StateString, {
        value: state || ''
    });

    return obj;
}

function EmitWithState() {
    if(arguments.length === 0) {
        throw new Error('EmitWithState called without arguments');
    }
    arguments[0] = arguments[0] + this.state;

    if (this.listenerCount(arguments[0]) < 1) {
        arguments[0] = 'Unhandled' + this.state;
    }

    if (this.listenerCount(arguments[0]) < 1) {
        throw new Error(`No 'Unhandled' function defined for event: ${arguments[0]}`);
    }

    this.emit.apply(this, arguments);
}

process.on('uncaughtException', function(err) {
    console.log(`Uncaught exception: ${err}\n${err.stack}`);
    throw err;
});

module.exports.LambdaHandler = alexaRequestHandler;
module.exports.CreateStateHandler = createStateHandler;
module.exports.StateString = _StateString;<commit_msg>Instead of eventType of IntentRequest, use event.request.intent.name<commit_after>'use strict';

var EventEmitter = require('events').EventEmitter;
var util = require('util');
var i18n = require('i18next');
var sprintf = require('i18next-sprintf-postprocessor');
var attributesHelper = require('./DynamoAttributesHelper');
var mobileAnalyticsHelper = require('./MobileAnalyticsHelper');
var responseHandlers = require('./response');
var _StateString = 'STATE';

function AlexaRequestEmitter() {
    EventEmitter.call(this);
}

util.inherits(AlexaRequestEmitter, EventEmitter);

function alexaRequestHandler(event, context, callback) {
    if (!event.session) {
        event.session = { 'attributes': {} };
    } else if (!event.session['attributes']) {
        event.session['attributes'] = {};
    }

    var handler = new AlexaRequestEmitter();
    handler.setMaxListeners(Infinity);

    Object.defineProperty(handler, '_event', {
        value: event,
        writable: false
    });

    Object.defineProperty(handler, '_context', {
        value: context,
        writable: false
    });

    Object.defineProperty(handler, '_callback', {
        value: callback,
        writable: false
    });

    Object.defineProperty(handler, 'state', {
        value: null,
        writable: true
    });

    Object.defineProperty(handler, 'appId', {
        value: null,
        writable: true
    });

    Object.defineProperty(handler, 'response', {
        value: {},
        writable: true
    });

    Object.defineProperty(handler, 'dynamoDBTableName', {
        value: null,
        writable: true
    });

    Object.defineProperty(handler, 'saveBeforeResponse', {
        value: false,
        writable: true
    });

    Object.defineProperty(handler, 'i18n', {
        value: i18n,
        writable: true
    });

    Object.defineProperty(handler, 'locale', {
        value: undefined,
        writable: true
    });

    Object.defineProperty(handler, 'resources', {
        value: undefined,
        writable: true
    });

    Object.defineProperty(handler, 'registerHandlers', {
        value: function() {
            RegisterHandlers.apply(handler, arguments);
        },
        writable: false
    });

    Object.defineProperty(handler, 'execute', {
        value: function() {
            HandleLambdaEvent.call(handler);
        },
        writable: false
    });

    Object.defineProperty(handler, 'mobileAnalyticsSettings', {
        value: null,
        writable: true
    });

    Object.defineProperty(handler, 'mobileAnalyticsHelper', {
        value: null,
        writable: true
    });

    handler.registerHandlers(responseHandlers);

    return handler;
}

function HandleLambdaEvent() {
    this.locale = this._event.request.locale;
    this.mobileAnalyticsSettings.locale = this.locale;

    if(this.resources) {
        this.i18n.use(sprintf).init({
            overloadTranslationOptionHandler: sprintf.overloadTranslationOptionHandler,
            returnObjects: true,
            lng: this.locale,
            resources: this.resources
        }, (err, t) => {
            if(err) {
                throw new Error('Error initializing i18next: ' + err);
            }
            ValidateRequest.call(this);
        });
    } else {
        ValidateRequest.call(this);
    }
}

function ValidateRequest() {
    var event = this._event;
    var context = this._context;
    var handlerAppId = this.appId;

    var requestAppId = '';
    var userId = '';

    // Long-form audio enabled skills use event.context
    if (event.context) {
        requestAppId = event.context.System.application.applicationId;
        userId = event.context.System.user.userId;
    } else if (event.session) {
        requestAppId = event.session.application.applicationId;
        userId = event.session.user.userId;
    }

    if (!this.mobileAnalyticsSettings.clientId) {
        this.mobileAnalyticsSettings.clientId = userId;
    }

    if (this.mobileAnalyticsSettings && this.mobileAnalyticsSettings.appId) {
        this.mobileAnalyticsHelper = new mobileAnalyticsHelper(this.mobileAnalyticsSettings);
    }

    if(!handlerAppId){
        console.log('Warning: Application ID is not set');
    }

    try {
        // Validate that this request originated from authorized source.
        if (handlerAppId && (requestAppId !== handlerAppId)) {
            console.log(`The applicationIds don\'t match: ${requestAppId} and ${handlerAppId}`);
            return context.fail('Invalid ApplicationId: ' + handlerAppId);
        }

        if (this.mobileAnalyticsHelper) {

            var eventType = event.request.type;

            if (event.session.sessionId && event.session['new']) {
                this.mobileAnalyticsHelper.startSession(event.session.sessionId);
            }

            var maAttributes = {};

            if (event.request.intent) {
                eventType = event.request.intent.name;

                if (event.request.intent.slots != undefined) {
                    for (var key in event.request.intent.slots) {
                        if (event.request.intent.slots.hasOwnProperty(key)) {
                            var name = event.request.intent.slots[key].name;
                            maAttributes[name] = event.request.intent.slots[key].value;
                        }
                    }
                }
            }

            this.mobileAnalyticsHelper.recordEvent(eventType, event.session.sessionId, maAttributes);
        }

        if(this.dynamoDBTableName && (!event.session.sessionId || event.session['new']) ) {
            attributesHelper.get(this.dynamoDBTableName, userId, (err, data) => {
                if(err) {
                    return context.fail('Error fetching user state: ' + err);
                }

                Object.assign(this._event.session.attributes, data);

                EmitEvent.call(this);
            });
        } else {
            EmitEvent.call(this);
        }
    } catch (e) {
        console.log(`Unexpected exception '${e}':\n${e.stack}`);
        context.fail(e);
    }
}

function EmitEvent() {
    this.state = this._event.session.attributes[_StateString] || '';

    var eventString = '';

    if (this._event.session['new'] && this.listenerCount('NewSession' + this.state) === 1) {
        eventString = 'NewSession';
    } else if(this._event.request.type === 'LaunchRequest') {
        eventString = 'LaunchRequest';
    } else if(this._event.request.type === 'IntentRequest') {
        eventString = this._event.request.intent.name;
    } else if (this._event.request.type === 'SessionEndedRequest'){
        eventString = 'SessionEndedRequest';
    } else if (this._event.request.type.substring(0,11) === 'AudioPlayer') {
        eventString = this._event.request.type.substring(12);
    } else if (this._event.request.type.substring(0,18) === 'PlaybackController') {
        eventString = this._event.request.type.substring(19);
    }

    eventString += this.state;

    if(this.listenerCount(eventString) < 1) {
        eventString = 'Unhandled' + this.state;
    }

    if(this.listenerCount(eventString) < 1){
        throw new Error(`No 'Unhandled' function defined for event: ${eventString}`);
    }

    this.emit(eventString);
}

function RegisterHandlers() {
    for(var arg = 0; arg < arguments.length; arg++) {
        var handlerObject = arguments[arg];

        if(!isObject(handlerObject)) {
            throw new Error(`Argument #${arg} was not an Object`);
        }

        var eventNames = Object.keys(handlerObject);

        for(var i = 0; i < eventNames.length; i++) {
            if(typeof(handlerObject[eventNames[i]]) !== 'function') {
                throw new Error(`Event handler for '${eventNames[i]}' was not a function`);
            }

            var eventName = eventNames[i];

            if(handlerObject[_StateString]) {
                eventName += handlerObject[_StateString];
            }

            var localize = function() {
                return this.i18n.t.apply(this.i18n, arguments);
            };

            var recordEvent = function() {
                return this.mobileAnalyticsHelper.recordEvent.apply(this.mobileAnalyticsHelper, arguments);
            }

            var handlerContext = {
                on: this.on.bind(this),
                emit: this.emit.bind(this),
                emitWithState: EmitWithState.bind(this),
                state: this.state,
                handler: this,
                i18n: this.i18n,
                locale: this.locale,
                t : localize,
                event: this._event,
                attributes: this._event.session.attributes,
                context: this._context,
                name: eventName,
                isOverridden:  IsOverridden.bind(this, eventName),
                response: ResponseBuilder(this),
                recordMobileAnalyticsEvent: recordEvent
            };

            this.on(eventName, handlerObject[eventNames[i]].bind(handlerContext));
        }
    }
}

function isObject(obj) {
    return (!!obj) && (obj.constructor === Object);
}

function IsOverridden(name) {
    return this.listenerCount(name) > 1;
}

function ResponseBuilder(self) {
    var responseObject = self.response;
    responseObject.version = '1.0';
    responseObject.response = {
        shouldEndSession: true
    };
    responseObject.sessionAttributes = self._event.session.attributes;

    return (function () {
        return {
            'speak': function (speechOutput) {
                responseObject.response.outputSpeech = createSSMLSpeechObject(speechOutput);
                return this;
            },
            'listen': function (repromptSpeech) {
                responseObject.response.reprompt = {
                    outputSpeech: createSSMLSpeechObject(repromptSpeech)
                };
                responseObject.response.shouldEndSession = false;
                return this;
            },
            'cardRenderer': function (cardTitle, cardContent, cardImage) {
                var card = {
                    type: 'Simple',
                    title: cardTitle,
                    content: cardContent
                };

                if(cardImage && (cardImage.smallImageUrl || cardImage.largeImageUrl)) {
                    card.type = 'Standard';
                    card['image'] = {};

                    delete card.content;
                    card.text = cardContent;

                    if(cardImage.smallImageUrl) {
                        card.image['smallImageUrl'] = cardImage.smallImageUrl;
                    }

                    if(cardImage.largeImageUrl) {
                        card.image['largeImageUrl'] = cardImage.largeImageUrl;
                    }
                }

                responseObject.response.card = card;
                return this;
            },
            'linkAccountCard': function () {
                responseObject.response.card = {
                    type: 'LinkAccount'
                };
                return this;
            },
            'audioPlayer': function (directiveType, behavior, url, token, expectedPreviousToken, offsetInMilliseconds) {
                var audioPlayerDirective;
                if (directiveType === 'play') {
                    audioPlayerDirective = {
                        "type": "AudioPlayer.Play",
                        "playBehavior": behavior,
                        "audioItem": {
                            "stream": {
                                "url": url,
                                "token": token,
                                "expectedPreviousToken": expectedPreviousToken,
                                "offsetInMilliseconds": offsetInMilliseconds
                            }
                        }
                    };
                } else if (directiveType === 'stop') {
                    audioPlayerDirective = {
                        "type": "AudioPlayer.Stop"
                    };
                } else {
                    audioPlayerDirective = {
                        "type": "AudioPlayer.Stop",
                        "clearBehavior": behavior
                    };
                }

                responseObject.response.directives = [audioPlayerDirective];
                return this;
            },
            'audioPlayerPlay': function (behavior, url, token, expectedPreviousToken, offsetInMilliseconds) {
                var audioPlayerDirective = {
                    "type": "AudioPlayer.Play",
                    "playBehavior": behavior,
                    "audioItem": {
                        "stream": {
                            "url": url,
                            "token": token,
                            "expectedPreviousToken": expectedPreviousToken,
                            "offsetInMilliseconds": offsetInMilliseconds
                        }
                    }
                };

                responseObject.response.directives = [audioPlayerDirective];
                return this;
            },
            'audioPlayerStop': function () {
                var audioPlayerDirective = {
                    "type": "AudioPlayer.Stop"
                };

                responseObject.response.directives = [audioPlayerDirective];
                return this;
            },
            'audioPlayerClearQueue': function (clearBehavior) {
                var audioPlayerDirective = {
                    "type": "AudioPlayer.ClearQueue",
                    "playBehavior": clearBehavior
                };

                responseObject.response.directives = [audioPlayerDirective];
                return this;
            }
        }
    })();
}

function createSSMLSpeechObject(message) {
    return {
        type: 'SSML',
        ssml: `<speak> ${message} </speak>`
    };
}

function createStateHandler(state, obj){
    if(!obj) {
        obj = {};
    }

    Object.defineProperty(obj, _StateString, {
        value: state || ''
    });

    return obj;
}

function EmitWithState() {
    if(arguments.length === 0) {
        throw new Error('EmitWithState called without arguments');
    }
    arguments[0] = arguments[0] + this.state;

    if (this.listenerCount(arguments[0]) < 1) {
        arguments[0] = 'Unhandled' + this.state;
    }

    if (this.listenerCount(arguments[0]) < 1) {
        throw new Error(`No 'Unhandled' function defined for event: ${arguments[0]}`);
    }

    this.emit.apply(this, arguments);
}

process.on('uncaughtException', function(err) {
    console.log(`Uncaught exception: ${err}\n${err.stack}`);
    throw err;
});

module.exports.LambdaHandler = alexaRequestHandler;
module.exports.CreateStateHandler = createStateHandler;
module.exports.StateString = _StateString;<|endoftext|>