<commit_before>Template.dashboard.helpers({
  'registrants': function () {
    return Registrants.find();
  }
});

Template.dashboard.events({
  'click #download-csv': function () {
    // Get current date for filename
    var dateNow = moment().format('YYYY-MM-DD');

    // Fetch all registrants
    registrantsJSON = Registrants.find().fetch();

    // Flatten registrant array fields to strings
    var arrayFields = ["foodPreference", "days"]
    _.each(arrayFields, flattenArray);

    // Convert boolean values into yes/no
    var booleanFields = ["linens", "firstTimeAttender"];
    _.each(booleanFields, booleanToYesNo);

    // Ensure that all optional fields have values for export
    var optionalFields = [
      "specialNeeds",
      "postalAddress",
      "telephone",
      "carbonTax",
      "registrantAffiliation"
    ];
    _.each(optionalFields, ensureFieldHasValue);

    var dateFields = ["createdAt"];
    _.each(dateFields, unixToISO);

    // Convert JSON to CSV
    // making sure to set field order
    var registrantsCSV = Papa.unparse({
      quotes: true,
      fields: [
        "last_name",
        "first_name",
        "age",
        "ageGroup",
        "registrantEmail",
        "postalAddress",
        "telephone",
        "registrantAffiliation",
        "firstTimeAttender",
        "registrationType",
        "accommodations",
        "days",
        "linens",
        "foodPreference",
        "specialNeeds",
        "carbonTax",
        "fee",
        "createdAt",
        "_id",
        "createdByEmail"
      ],
      data: registrantsJSON
    });

    // Add registrants to binary blob for downloading
    var registrantsBLOB = new Blob([registrantsCSV], {type: "text/csv"});

    // Download the file
    saveAs(registrantsBLOB, "pym2015-registrants-export-" + dateNow + ".csv");
  }
});

var flattenArray = function (field) {
  /*
  * Takes a registrant object
  * If value is present, flattens array to comma delimited string
  * Otherwise sets to empty string
  */
  _.each(registrantsJSON, function (registrant) {
    if (registrant[field]) {
      registrant[field] = registrant[field].join(", ");
    } else {
      registrant[field] = "";
    }
  });
};

var booleanToYesNo = function (field) {
  /*
  * Takes a registrant object
  * converts boolean field value into 'yes' 'no'
  */
  _.each(registrantsJSON, function (registrant) {
    if (registrant[field]) {
      registrant[field] = "yes";
    } else {
      registrant[field] = "no";
    }
  });
};

var ensureFieldHasValue = function (field) {
  /*
  * Takes a registrant object, looks at a given field
  * If the field is undefined, sets the value to an empty string
  */
  _.each(registrantsJSON, function (registrant) {
    // If the field is undefined
    if (!registrant[field]) {
      // Set the field to an empty string
      registrant[field] = "";
    }
  });
};

var unixToISO = function (field) {
  /*
  * Takes a registrant object
  * Converts a date field from Unix format to ISO 8601
  */
  _.each(registrantsJSON, function (registrant) {
    // Get the registration date, using moment
    var registrationDate = moment(registrant[field]);

    // Convert the registration date to ISO format
    var isoDate = registrationDate.format();

    // Update the registrant field with ISO date
    registrant[field] = isoDate;
  })
};
<commit_msg>Add template level subscription<commit_after>Template.dashboard.onCreated = function () {
  // Get reference to template instance
  const instance = this;

  instance.subscribe('registrants');
}

Template.dashboard.helpers({
  'registrants': function () {
    return Registrants.find();
  }
});

Template.dashboard.events({
  'click #download-csv': function () {
    // Get current date for filename
    var dateNow = moment().format('YYYY-MM-DD');

    // Fetch all registrants
    registrantsJSON = Registrants.find().fetch();

    // Flatten registrant array fields to strings
    var arrayFields = ["foodPreference", "days"]
    _.each(arrayFields, flattenArray);

    // Convert boolean values into yes/no
    var booleanFields = ["linens", "firstTimeAttender"];
    _.each(booleanFields, booleanToYesNo);

    // Ensure that all optional fields have values for export
    var optionalFields = [
      "specialNeeds",
      "postalAddress",
      "telephone",
      "carbonTax",
      "registrantAffiliation"
    ];
    _.each(optionalFields, ensureFieldHasValue);

    var dateFields = ["createdAt"];
    _.each(dateFields, unixToISO);

    // Convert JSON to CSV
    // making sure to set field order
    var registrantsCSV = Papa.unparse({
      quotes: true,
      fields: [
        "last_name",
        "first_name",
        "age",
        "ageGroup",
        "registrantEmail",
        "postalAddress",
        "telephone",
        "registrantAffiliation",
        "firstTimeAttender",
        "registrationType",
        "accommodations",
        "days",
        "linens",
        "foodPreference",
        "specialNeeds",
        "carbonTax",
        "fee",
        "createdAt",
        "_id",
        "createdByEmail"
      ],
      data: registrantsJSON
    });

    // Add registrants to binary blob for downloading
    var registrantsBLOB = new Blob([registrantsCSV], {type: "text/csv"});

    // Download the file
    saveAs(registrantsBLOB, "pym2015-registrants-export-" + dateNow + ".csv");
  }
});

var flattenArray = function (field) {
  /*
  * Takes a registrant object
  * If value is present, flattens array to comma delimited string
  * Otherwise sets to empty string
  */
  _.each(registrantsJSON, function (registrant) {
    if (registrant[field]) {
      registrant[field] = registrant[field].join(", ");
    } else {
      registrant[field] = "";
    }
  });
};

var booleanToYesNo = function (field) {
  /*
  * Takes a registrant object
  * converts boolean field value into 'yes' 'no'
  */
  _.each(registrantsJSON, function (registrant) {
    if (registrant[field]) {
      registrant[field] = "yes";
    } else {
      registrant[field] = "no";
    }
  });
};

var ensureFieldHasValue = function (field) {
  /*
  * Takes a registrant object, looks at a given field
  * If the field is undefined, sets the value to an empty string
  */
  _.each(registrantsJSON, function (registrant) {
    // If the field is undefined
    if (!registrant[field]) {
      // Set the field to an empty string
      registrant[field] = "";
    }
  });
};

var unixToISO = function (field) {
  /*
  * Takes a registrant object
  * Converts a date field from Unix format to ISO 8601
  */
  _.each(registrantsJSON, function (registrant) {
    // Get the registration date, using moment
    var registrationDate = moment(registrant[field]);

    // Convert the registration date to ISO format
    var isoDate = registrationDate.format();

    // Update the registrant field with ISO date
    registrant[field] = isoDate;
  })
};
<|endoftext|>


<commit_before>var app = require('app')
var meow = require('meow')
var fs = require('fs')
var path = require('path')
var BrowserWindow = require('browser-window')

var wargs = require('./lib/args')
var markdownToHTMLPath = require('./lib/markdown')

app.on('ready', appReady)

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

var cli = meow({
  pkg: './package.json',
  help: [
    'Options',
    '  --help                     Show this help',
    '  --version                  Current version of package',
    '  -i | --input               String - The path to the HTML file or url',
    '  -o | --output              String - The path of the output PDF',
    '  -c | --css                 String - The path to custom CSS',
    '  -b | --printBackground     Boolean - Whether to print CSS backgrounds.',
    '                               false - default',
    '  -s | --printSelectionOnly  Boolean - Whether to print selection only',
    '                               false - default',
    '  -l | --landscape           Boolean - true for landscape, false for portrait.',
    '                               false - default',
    '  -m | --marginType          Integer - Specify the type of margins to use',
    '                               0 - default',
    '                               1 - none',
    '                               2 - minimum',
    '',
    'Usage',
    '  $ electron-pdf <input> <output>',
    '  $ electron-pdf <input> <output> -l',
    '',
    'Examples',
    '  $ electron-pdf http://fraserxu.me ~/Desktop/fraserxu.pdf',
    '  $ electron-pdf ./index.html ~/Desktop/index.pdf',
    '  $ electron-pdf ./README.md ~/Desktop/README.pdf -l',
    '  $ electron-pdf ./README.md ~/Desktop/README.pdf -l -c my-awesome-css.css',

    ''
  ].join('\n')
})

function appReady () {
  var input = cli.input[0] || cli.flags.i || cli.flags.input
  var output = cli.input[1] || cli.flags.o || cli.flags.output
  var customCss = cli.flags.c || cli.flags.css
  if (!input || !output) {
    cli.showHelp()
    app.quit()
  }

  function isMarkdown (input) {
    var ext = path.extname(input)
    return ext.indexOf('md') > 0 || ext.indexOf('markdown') > 0
  }

  if (isMarkdown(input)) {
    var opts = {}

    if (customCss) {
      opts.customCss = customCss
    }

    // if given a markdown, render it into HTML and return the path of the HTML
    input = markdownToHTMLPath(input, opts, function (err, tmpHTMLPath) {
      if (err) {
        console.error('Parse markdown file error', err)
        app.quit()
      }

      var indexUrl = wargs.urlWithArgs(tmpHTMLPath, {})
      render(indexUrl, output)
    })
  } else {
    var indexUrl = wargs.urlWithArgs(input, {})
    render(indexUrl, output)
  }
}

/**
 * render file to pdf
 * @param  {String} indexUrl The path to the HTML or url
 */
function render (indexUrl, output) {
  var win = new BrowserWindow({ width: 0, height: 0, show: false })
  win.on('closed', function () { win = null })
  win.loadUrl(indexUrl)

  // print to pdf args
  var opts = {
    marginType: cli.flags.m || cli.flags.marginType || 0,
    printBackground: cli.flags.p || cli.flags.printBackground || true,
    printSelectionOnly: cli.flags.s || cli.flags.printSelectionOnly || false,
    landscape: cli.flags.l || cli.flags.landscape || false
  }

  win.webContents.on('did-finish-load', function () {
    win.printToPDF(opts, function (err, data) {
      if (err) {
        console.error(err)
      }

      fs.writeFile(path.join(process.cwd(), output), data, function (err) {
        if (err) {
          console.error(err)
        }
        app.quit()
      })
    })
  })
}
<commit_msg>rename loadUrl to loadURL<commit_after>var app = require('app')
var meow = require('meow')
var fs = require('fs')
var path = require('path')
var BrowserWindow = require('browser-window')

var wargs = require('./lib/args')
var markdownToHTMLPath = require('./lib/markdown')

app.on('ready', appReady)

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

var cli = meow({
  pkg: './package.json',
  help: [
    'Options',
    '  --help                     Show this help',
    '  --version                  Current version of package',
    '  -i | --input               String - The path to the HTML file or url',
    '  -o | --output              String - The path of the output PDF',
    '  -c | --css                 String - The path to custom CSS',
    '  -b | --printBackground     Boolean - Whether to print CSS backgrounds.',
    '                               false - default',
    '  -s | --printSelectionOnly  Boolean - Whether to print selection only',
    '                               false - default',
    '  -l | --landscape           Boolean - true for landscape, false for portrait.',
    '                               false - default',
    '  -m | --marginType          Integer - Specify the type of margins to use',
    '                               0 - default',
    '                               1 - none',
    '                               2 - minimum',
    '',
    'Usage',
    '  $ electron-pdf <input> <output>',
    '  $ electron-pdf <input> <output> -l',
    '',
    'Examples',
    '  $ electron-pdf http://fraserxu.me ~/Desktop/fraserxu.pdf',
    '  $ electron-pdf ./index.html ~/Desktop/index.pdf',
    '  $ electron-pdf ./README.md ~/Desktop/README.pdf -l',
    '  $ electron-pdf ./README.md ~/Desktop/README.pdf -l -c my-awesome-css.css',

    ''
  ].join('\n')
})

function appReady () {
  var input = cli.input[0] || cli.flags.i || cli.flags.input
  var output = cli.input[1] || cli.flags.o || cli.flags.output
  var customCss = cli.flags.c || cli.flags.css
  if (!input || !output) {
    cli.showHelp()
    app.quit()
  }

  function isMarkdown (input) {
    var ext = path.extname(input)
    return ext.indexOf('md') > 0 || ext.indexOf('markdown') > 0
  }

  if (isMarkdown(input)) {
    var opts = {}

    if (customCss) {
      opts.customCss = customCss
    }

    // if given a markdown, render it into HTML and return the path of the HTML
    input = markdownToHTMLPath(input, opts, function (err, tmpHTMLPath) {
      if (err) {
        console.error('Parse markdown file error', err)
        app.quit()
      }

      var indexUrl = wargs.urlWithArgs(tmpHTMLPath, {})
      render(indexUrl, output)
    })
  } else {
    var indexUrl = wargs.urlWithArgs(input, {})
    render(indexUrl, output)
  }
}

/**
 * render file to pdf
 * @param  {String} indexUrl The path to the HTML or url
 */
function render (indexUrl, output) {
  var win = new BrowserWindow({ width: 0, height: 0, show: false })
  win.on('closed', function () { win = null })
  win.loadURL(indexUrl)

  // print to pdf args
  var opts = {
    marginType: cli.flags.m || cli.flags.marginType || 0,
    printBackground: cli.flags.p || cli.flags.printBackground || true,
    printSelectionOnly: cli.flags.s || cli.flags.printSelectionOnly || false,
    landscape: cli.flags.l || cli.flags.landscape || false
  }

  win.webContents.on('did-finish-load', function () {
    win.printToPDF(opts, function (err, data) {
      if (err) {
        console.error(err)
      }

      fs.writeFile(path.join(process.cwd(), output), data, function (err) {
        if (err) {
          console.error(err)
        }
        app.quit()
      })
    })
  })
}
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var colors = util.inspect.colors;
var colo = {};

var deco = function(_styles) {
  var decorator = function() {
    return decorate.apply(decorator, arguments);
  };
  decorator._styles = _styles;
  decorator.__proto__ = Object.defineProperties(function(){}, styles);
  return decorator;
}

var decorate = function() {
  var result = arguments[0];
  this._styles.forEach(function(style) {
    var color = colors[style];
    if (color) {
      result = '\u001b[' + color[0] + 'm' + result + '\u001b[' + color[1] + 'm';
    }
  });
  return result;
}

var styles = (function () {
  var result = {};
  Object.keys(colors).forEach(function (color) {
  result[color] = {
    get: function () {
      if (!this._styles) this._styles = [];
      return deco(this._styles.concat(color));
    }
  };
  });
  return result;
})();

Object.defineProperties(colo, styles);

module.exports = colo;
<commit_msg>fix indent<commit_after>'use strict';
var util = require('util');
var colors = util.inspect.colors;
var colo = {};

var deco = function(_styles) {
  var decorator = function(str) {
    return decorate.apply(decorator, [str]);
  };
  decorator._styles = _styles;
  decorator.__proto__ = Object.defineProperties(function(){}, styles);
  return decorator;
};

var decorate = function(str) {
  var result = str;
  this._styles.forEach(function(style) {
    var color = colors[style];
    if (color) {
      result = '\u001b[' + color[0] + 'm' + result + '\u001b[' + color[1] + 'm';
    }
  });
  return result;
};

var styles = (function () {
  var result = {};
  Object.keys(colors).forEach(function (color) {
    result[color] = {
      get: function () {
        if (!this._styles) this._styles = [];
        return deco(this._styles.concat(color));
      }
    };
  });
  return result;
})();

Object.defineProperties(colo, styles);

module.exports = colo;
<|endoftext|>


<commit_before>var options = {
  //keepHistory: 1000 * 60 * 5,
  //localSearch: true
};
var fields = ['preferredName', "callings.positionName"];

memberSearch = new SearchSource("members", fields, options, 5);

Template.memberSelect.helpers({
  memberData: function(){
    return memberSearch.getData({
      transform: function(matchText, regExp) {
        return matchText.replace(regExp, "$&")
      },
      sort: {isoScore: -1}
    });
  },
  isLoading: function() {
    return memberSearch.getStatus().loading;
  },
  isLikelyOptions: function () {
    return (
      (Session.get("memberSelectType") == "organist") ||
      (Session.get("memberSelectType") == "chorister") ||
      (Session.get("memberSelectType") == "music") ||
      (Session.get("memberSelectType") == "presiding") ||
      (Session.get("memberSelectType") == "conducting") ||
      (Session.get("memberSelectType") == "visitor")
    );
  },
  memberSelectTypeIs: function (inMemberSelectType) {
    return (Session.get("memberSelectType") == inMemberSelectType);
  },
  organistData: function() {
    //get Organist or Pianist position
    return memberCollection.find({"callings.positionTypeId": 234, "wardUnitNo": Meteor.user().wardUnitNo});
  },
  choristerData: function() {
    //get Chorister position
    return memberCollection.find({"callings.positionTypeId": 1585, "wardUnitNo": Meteor.user().wardUnitNo});
  },
  musicData: function() {
    return memberCollection.find({"callings.orgTypeId": 1300, "wardUnitNo": Meteor.user().wardUnitNo});
  },
  presidingData: function() {
    //get Presiding position - Stake Presidency, Bishopric
    var selector = {$or: [
      {"callings.positionTypeId": {$in: [4, 54, 55]}, "wardUnitNo": Meteor.user().wardUnitNo},
      {"callings.positionTypeId": {$in: [1, 2, 3]}, "stakeUnitNo": Meteor.user().stakeUnitNo}
    ]};
    var options = {sort: {"callings.positionTypeId": 1}};
    return memberCollection.find(selector, options);
  },
  conductingData: function() {
    //get Presiding position - Bishopric
    var selector = {$or: [
      {"callings.positionTypeId": {$in: [4, 54, 55]}, "wardUnitNo": Meteor.user().wardUnitNo}
    ]};
    var options = {sort: {"callings.positionTypeId": 1}};
    return memberCollection.find(selector, options);
  },
  visitorData: function() {
    //get Visiting Authority position - Stake Presidency, High Council
    var selector = {$or: [
      {"callings.positionTypeId": {$in: [1, 2, 3, 94]}, "stakeUnitNo": Meteor.user().stakeUnitNo}
    ]};
    var options = {sort: {"callings.positionTypeId": 1}};
    return memberCollection.find(selector, options);
  }
});

function doUpdate (inUpdateObject) {
  if (Session.get("memberSelectType") == "callingChangeMember") {
    Session.set('selectedCallingChangeMember', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "organist") {
    Session.set('selectedOrganist', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "chorister") {
    Session.set('selectedChorister', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "invocation") {
    Session.set('selectedInvocation', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "benediction") {
    Session.set('selectedBenediction', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "presiding") {
    Session.set('selectedPresiding', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "conducting") {
    Session.set('selectedConducting', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "visitor") {
    var updateObject = {};
    updateObject.$set = {visitor: inUpdateObject, wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    visitorCollection.update(Session.get("visitorId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "speaker") {
    var updateObject = {};
    updateObject.$set = {speaker: inUpdateObject, meetingDate: Session.get("meetingDate"), wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    speakerCollection.update(Session.get("speakerId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "recognition") {
    //first delete
    var updateObject = {
      $pull:
        {
          "members":
            {
              _id: Session.get("recognitionMemberId")
            }
        }
    }
    recognitionCollection.update(Session.get("recognitionId"), updateObject);
    //then add back
    var updateObject = {
      $addToSet:
        {
          "members": inUpdateObject
        }
    }
    recognitionCollection.update(Session.get("recognitionId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "musicalNumberPerformer") {
    var updateObject = {};
    updateObject.$set = {performer: inUpdateObject, wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    musicalNumberCollection.update(Session.get("musicalNumberId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "musicalNumberAccompanist") {
    var updateObject = {};
    updateObject.$set = {accompanist: inUpdateObject, wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    musicalNumberCollection.update(Session.get("musicalNumberId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "musicalNumberConductor") {
    var updateObject = {};
    updateObject.$set = {conductor: inUpdateObject, wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    musicalNumberCollection.update(Session.get("musicalNumberId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "responsible") {
    Session.set('selectedResponsible', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "volunteer") {
    var updateObject = {};
    updateObject.$set = {volunteer: inUpdateObject, signupDate: Session.get("signupDate"), wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    volunteerCollection.update(Session.get("volunteerId"), updateObject);
  }
  history.back();
}

Template.memberSelect.events({
  "keyup #memberSearchInput": _.throttle(function(e) {
    var text = $(e.target).val().trim();
    memberSearch.search(text);
  }, 200),
  "click #goButton": function() {
    var memberObject = {
      "preferredName": $('#other').val()
    }
    doUpdate(memberObject);
  },
  "click #memberRadioButton": function(e, instance) {
    //strip out html tags
    if (this.preferredName) {
      this.preferredName = jQuery('
' + this.preferredName + '
').text();
    }
    if (this.callings) {
      this.callings.positionName = jQuery('
' + this.callings.positionName + '
').text();
    }
    doUpdate(this);
  },
});
<commit_msg>find music stuff better<commit_after>var options = {
  //keepHistory: 1000 * 60 * 5,
  //localSearch: true
};
var fields = ['preferredName', "callings.positionName"];

memberSearch = new SearchSource("members", fields, options, 5);

Template.memberSelect.helpers({
  memberData: function(){
    return memberSearch.getData({
      transform: function(matchText, regExp) {
        return matchText.replace(regExp, "$&")
      },
      sort: {isoScore: -1}
    });
  },
  isLoading: function() {
    return memberSearch.getStatus().loading;
  },
  isLikelyOptions: function () {
    return (
      (Session.get("memberSelectType") == "organist") ||
      (Session.get("memberSelectType") == "chorister") ||
      (Session.get("memberSelectType") == "music") ||
      (Session.get("memberSelectType") == "presiding") ||
      (Session.get("memberSelectType") == "conducting") ||
      (Session.get("memberSelectType") == "visitor")
    );
  },
  memberSelectTypeIs: function (inMemberSelectType) {
    return (Session.get("memberSelectType") == inMemberSelectType);
  },
  organistData: function() {
    //get Organist or Pianist position
    return memberCollection.find({"callings.positionTypeId": 234, "wardUnitNo": Meteor.user().wardUnitNo});
  },
  choristerData: function() {
    //get Chorister position
    return memberCollection.find({"callings.positionTypeId": {$in: [223, 1585]}, "wardUnitNo": Meteor.user().wardUnitNo});
  },
  musicData: function() {
    return memberCollection.find({"callings.positionTypeId": {$in: [223, 1585]}, "wardUnitNo": Meteor.user().wardUnitNo});
  },
  presidingData: function() {
    //get Presiding position - Stake Presidency, Bishopric
    var selector = {$or: [
      {"callings.positionTypeId": {$in: [4, 54, 55]}, "wardUnitNo": Meteor.user().wardUnitNo},
      {"callings.positionTypeId": {$in: [1, 2, 3]}, "stakeUnitNo": Meteor.user().stakeUnitNo}
    ]};
    var options = {sort: {"callings.positionTypeId": 1}};
    return memberCollection.find(selector, options);
  },
  conductingData: function() {
    //get Presiding position - Bishopric
    var selector = {$or: [
      {"callings.positionTypeId": {$in: [4, 54, 55]}, "wardUnitNo": Meteor.user().wardUnitNo}
    ]};
    var options = {sort: {"callings.positionTypeId": 1}};
    return memberCollection.find(selector, options);
  },
  visitorData: function() {
    //get Visiting Authority position - Stake Presidency, High Council
    var selector = {$or: [
      {"callings.positionTypeId": {$in: [1, 2, 3, 94]}, "stakeUnitNo": Meteor.user().stakeUnitNo}
    ]};
    var options = {sort: {"callings.positionTypeId": 1}};
    return memberCollection.find(selector, options);
  }
});

function doUpdate (inUpdateObject) {
  if (Session.get("memberSelectType") == "callingChangeMember") {
    Session.set('selectedCallingChangeMember', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "organist") {
    Session.set('selectedOrganist', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "chorister") {
    Session.set('selectedChorister', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "invocation") {
    Session.set('selectedInvocation', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "benediction") {
    Session.set('selectedBenediction', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "presiding") {
    Session.set('selectedPresiding', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "conducting") {
    Session.set('selectedConducting', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "visitor") {
    var updateObject = {};
    updateObject.$set = {visitor: inUpdateObject, wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    visitorCollection.update(Session.get("visitorId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "speaker") {
    var updateObject = {};
    updateObject.$set = {speaker: inUpdateObject, meetingDate: Session.get("meetingDate"), wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    speakerCollection.update(Session.get("speakerId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "recognition") {
    //first delete
    var updateObject = {
      $pull:
        {
          "members":
            {
              _id: Session.get("recognitionMemberId")
            }
        }
    }
    recognitionCollection.update(Session.get("recognitionId"), updateObject);
    //then add back
    var updateObject = {
      $addToSet:
        {
          "members": inUpdateObject
        }
    }
    recognitionCollection.update(Session.get("recognitionId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "musicalNumberPerformer") {
    var updateObject = {};
    updateObject.$set = {performer: inUpdateObject, wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    musicalNumberCollection.update(Session.get("musicalNumberId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "musicalNumberAccompanist") {
    var updateObject = {};
    updateObject.$set = {accompanist: inUpdateObject, wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    musicalNumberCollection.update(Session.get("musicalNumberId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "musicalNumberConductor") {
    var updateObject = {};
    updateObject.$set = {conductor: inUpdateObject, wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    musicalNumberCollection.update(Session.get("musicalNumberId"), updateObject);
  }
  else if (Session.get("memberSelectType") == "responsible") {
    Session.set('selectedResponsible', inUpdateObject);
  }
  else if (Session.get("memberSelectType") == "volunteer") {
    var updateObject = {};
    updateObject.$set = {volunteer: inUpdateObject, signupDate: Session.get("signupDate"), wardUnitNo: Meteor.user().wardUnitNo, stakeUnitNo: Meteor.user().stakeUnitNo};
    volunteerCollection.update(Session.get("volunteerId"), updateObject);
  }
  history.back();
}

Template.memberSelect.events({
  "keyup #memberSearchInput": _.throttle(function(e) {
    var text = $(e.target).val().trim();
    memberSearch.search(text);
  }, 200),
  "click #goButton": function() {
    var memberObject = {
      "preferredName": $('#other').val()
    }
    doUpdate(memberObject);
  },
  "click #memberRadioButton": function(e, instance) {
    //strip out html tags
    if (this.preferredName) {
      this.preferredName = jQuery('
' + this.preferredName + '
').text();
    }
    if (this.callings) {
      this.callings.positionName = jQuery('
' + this.callings.positionName + '
').text();
    }
    doUpdate(this);
  },
});
<|endoftext|>


<commit_before>
var self = module.exports = {
  configure: function(grunt) {
    // Project configuration.
    grunt.initConfig({
      particles: {
        install: {
          options: {
            runServices: ['svc|sequence!install/install']
          }
        }
      }
    });

    //Auto load grunt plugins.
    require('glob').sync("grunt-*", {cwd: 'node_modules'}).filter(function(name) {
      return name !== "grunt" && name !== "grunt-cli";
    }).forEach(grunt.loadNpmTasks);

    grunt.registerTask('build', ['particles-build']);
    grunt.registerTask('rebuild', ['particles-rebuild']);
    grunt.registerTask('watch-assets', ['particles-watch']);
    grunt.registerTask('install', ['particles:install']);
    grunt.registerTask('dev', ['particles-develop']);

    grunt.registerTask('default', ['rebuild']);
  }
};
<commit_msg>Fix, runServices becomes runService<commit_after>
var self = module.exports = {
  configure: function(grunt) {
    // Project configuration.
    grunt.initConfig({
      particles: {
        install: {
          options: {
            runService: 'svc|sequence!install/install'
          }
        }
      }
    });

    //Auto load grunt plugins.
    require('glob').sync("grunt-*", {cwd: 'node_modules'}).filter(function(name) {
      return name !== "grunt" && name !== "grunt-cli";
    }).forEach(grunt.loadNpmTasks);

    grunt.registerTask('build', ['particles-build']);
    grunt.registerTask('rebuild', ['particles-rebuild']);
    grunt.registerTask('watch-assets', ['particles-watch']);
    grunt.registerTask('install', ['particles:install']);
    grunt.registerTask('dev', ['particles-develop']);

    grunt.registerTask('default', ['rebuild']);
  }
};
<|endoftext|>


<commit_before>var vendor = require('postcss/lib/vendor');

var mapFunctions = require('./lib/mapFunctions');
var parseBytes = require('./lib/parseBytes');
var unescapeCss = require('./lib/unescapeCss');

var fs = require('fs');
var path = require('path');
var url = require('url');

var base64 = require('js-base64').Base64;
var cssesc = require('cssesc');
var mime = require('mime');
var sizeOf = require('image-size');

const AUTO_SIZE   = ['background-size', 'border-image-width', 'border-width',
                     'margin', 'padding'];
const AUTO_WIDTH  = ['border-left', 'border-left-width', 'border-right',
                     'border-right-width', 'left', 'margin-left',
                     'margin-right', 'max-width', 'min-width', 'padding-left',
                     'padding-right', 'width'];
const AUTO_HEIGHT = ['border-bottom', 'border-bottom-width', 'border-top',
                     'border-top-width', 'bottom', 'height', 'margin-bottom',
                     'margin-top', 'max-height', 'min-height',
                     'padding-bottom', 'padding-top'];

const R_URL = /^([^\?#]+)(.*)/;

module.exports = function (options) {

  options = options || {};
  options.baseUrl = options.baseUrl || '/';

  if (options.basePath) {
    options.basePath = path.resolve(options.basePath);
  } else {
    options.basePath = process.cwd();
  }

  if (options.loadPaths) {
    options.loadPaths = options.loadPaths.map(function (loadPath) {
      return path.resolve(options.basePath, loadPath);
    });
  } else {
    options.loadPaths = [];
  }
  options.loadPaths.unshift(options.basePath);

  if (options.relativeTo) {
    options.relativeTo = path.resolve(options.relativeTo);
  } else {
    options.relativeTo = false;
  }

  function matchLoadPath(assetPath) {
    var matchingPath;
    var isFound = options.loadPaths.some(function (loadPath) {
      matchingPath = loadPath;
      return fs.existsSync(path.join(loadPath, assetPath));
    });
    if (!isFound) throw new Error("Asset not found or unreadable: " + assetPath);
    return matchingPath;
  }

  function resolveDataUrl(assetStr) {
    var resolvedPath = resolvePath(assetStr);
    var mimeType = mime.lookup(resolvedPath);
    var data = base64.encode(fs.readFileSync(resolvedPath));
    return 'data:' + mimeType + ';base64,' + data;
  }

  function resolvePath(assetStr) {
    var chunks = splitPathFromQuery(assetStr);
    var assetPath = unescapeCss(chunks[0]);
    return path.resolve(matchLoadPath(assetPath), assetPath);
  }

  function resolveUrl(assetStr) {
    var assetUrl = url.parse(unescapeCss(assetStr));
    var assetPath = decodeURI(assetUrl.pathname);
    if (options.relativeTo) {
      var toLoadPath = path.relative(options.relativeTo, matchLoadPath(assetPath));
      toLoadPath = path.join(toLoadPath, '/');
      assetUrl.pathname = url.resolve(toLoadPath, assetPath);
    } else {
      var baseToLoadPath = path.relative(options.basePath, matchLoadPath(assetPath));
      baseToLoadPath = path.join(baseToLoadPath || '.', '/');
      var baseUrl = url.resolve(options.baseUrl, baseToLoadPath);
      assetUrl.pathname = url.resolve(baseUrl, assetPath);
    }
    return cssesc(url.format(assetUrl));
  }

  function shouldBeInline(assetPath) {
    if (options.inline && options.inline.maxSize) {
      var size = fs.statSync(assetPath).size;
      return (size <= parseBytes(options.inline.maxSize));
    }
    return false;
  }

  function splitPathFromQuery(assetStr) {
    return Array.prototype.slice.call(assetStr.match(R_URL), 1, 3);
  }

  return function (cssTree) {
    cssTree.eachDecl(function (decl) {

      decl.value = mapFunctions(decl.value, function (before, quote, assetStr, modifier, after) {

        if (AUTO_WIDTH.indexOf(vendor.unprefixed(decl.prop)) !== -1 || modifier === 'width') {
          return sizeOf(resolvePath(assetStr)).width + 'px';
        } else if (AUTO_HEIGHT.indexOf(vendor.unprefixed(decl.prop)) !== -1 || modifier === 'height') {
          return sizeOf(resolvePath(assetStr)).height + 'px';
        } else if (AUTO_SIZE.indexOf(vendor.unprefixed(decl.prop)) !== -1 || modifier === 'size') {
          var size = sizeOf(resolvePath(assetStr));
          return size.width + 'px ' + size.height + 'px';
        }
        var assetPath = resolvePath(assetStr);
        if (shouldBeInline(assetPath)) {
          return 'url(' + before + quote + resolveDataUrl(assetStr) + quote + after + ')';
        }
        return 'url(' + before + quote + resolveUrl(assetStr) + quote + after + ')';
      });
    });
  };
};
<commit_msg>Remove `splitPathFromQuery` function<commit_after>var vendor = require('postcss/lib/vendor');

var mapFunctions = require('./lib/mapFunctions');
var parseBytes = require('./lib/parseBytes');
var unescapeCss = require('./lib/unescapeCss');

var fs = require('fs');
var path = require('path');
var url = require('url');

var base64 = require('js-base64').Base64;
var cssesc = require('cssesc');
var mime = require('mime');
var sizeOf = require('image-size');

const AUTO_SIZE   = ['background-size', 'border-image-width', 'border-width',
                     'margin', 'padding'];
const AUTO_WIDTH  = ['border-left', 'border-left-width', 'border-right',
                     'border-right-width', 'left', 'margin-left',
                     'margin-right', 'max-width', 'min-width', 'padding-left',
                     'padding-right', 'width'];
const AUTO_HEIGHT = ['border-bottom', 'border-bottom-width', 'border-top',
                     'border-top-width', 'bottom', 'height', 'margin-bottom',
                     'margin-top', 'max-height', 'min-height',
                     'padding-bottom', 'padding-top'];

module.exports = function (options) {

  options = options || {};
  options.baseUrl = options.baseUrl || '/';

  if (options.basePath) {
    options.basePath = path.resolve(options.basePath);
  } else {
    options.basePath = process.cwd();
  }

  if (options.loadPaths) {
    options.loadPaths = options.loadPaths.map(function (loadPath) {
      return path.resolve(options.basePath, loadPath);
    });
  } else {
    options.loadPaths = [];
  }
  options.loadPaths.unshift(options.basePath);

  if (options.relativeTo) {
    options.relativeTo = path.resolve(options.relativeTo);
  } else {
    options.relativeTo = false;
  }

  function matchLoadPath(assetPath) {
    var matchingPath;
    var isFound = options.loadPaths.some(function (loadPath) {
      matchingPath = loadPath;
      return fs.existsSync(path.join(loadPath, assetPath));
    });
    if (!isFound) throw new Error("Asset not found or unreadable: " + assetPath);
    return matchingPath;
  }

  function resolveDataUrl(assetStr) {
    var resolvedPath = resolvePath(assetStr);
    var mimeType = mime.lookup(resolvedPath);
    var data = base64.encode(fs.readFileSync(resolvedPath));
    return 'data:' + mimeType + ';base64,' + data;
  }

  function resolvePath(assetStr) {
    var assetUrl = url.parse(unescapeCss(assetStr));
    var assetPath = decodeURI(assetUrl.pathname);
    return path.resolve(matchLoadPath(assetPath), assetPath);
  }

  function resolveUrl(assetStr) {
    var assetUrl = url.parse(unescapeCss(assetStr));
    var assetPath = decodeURI(assetUrl.pathname);
    if (options.relativeTo) {
      var toLoadPath = path.relative(options.relativeTo, matchLoadPath(assetPath));
      toLoadPath = path.join(toLoadPath, '/');
      assetUrl.pathname = url.resolve(toLoadPath, assetPath);
    } else {
      var baseToLoadPath = path.relative(options.basePath, matchLoadPath(assetPath));
      baseToLoadPath = path.join(baseToLoadPath || '.', '/');
      var baseUrl = url.resolve(options.baseUrl, baseToLoadPath);
      assetUrl.pathname = url.resolve(baseUrl, assetPath);
    }
    return cssesc(url.format(assetUrl));
  }

  function shouldBeInline(assetPath) {
    if (options.inline && options.inline.maxSize) {
      var size = fs.statSync(assetPath).size;
      return (size <= parseBytes(options.inline.maxSize));
    }
    return false;
  }

  return function (cssTree) {
    cssTree.eachDecl(function (decl) {

      decl.value = mapFunctions(decl.value, function (before, quote, assetStr, modifier, after) {

        if (AUTO_WIDTH.indexOf(vendor.unprefixed(decl.prop)) !== -1 || modifier === 'width') {
          return sizeOf(resolvePath(assetStr)).width + 'px';
        } else if (AUTO_HEIGHT.indexOf(vendor.unprefixed(decl.prop)) !== -1 || modifier === 'height') {
          return sizeOf(resolvePath(assetStr)).height + 'px';
        } else if (AUTO_SIZE.indexOf(vendor.unprefixed(decl.prop)) !== -1 || modifier === 'size') {
          var size = sizeOf(resolvePath(assetStr));
          return size.width + 'px ' + size.height + 'px';
        }
        var assetPath = resolvePath(assetStr);
        if (shouldBeInline(assetPath)) {
          return 'url(' + before + quote + resolveDataUrl(assetStr) + quote + after + ')';
        }
        return 'url(' + before + quote + resolveUrl(assetStr) + quote + after + ')';
      });
    });
  };
};
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */
var request = require('superagent')
  , _ = require('underscore');

// Endpoint template
var endpoint = _.template('http://<%=service%>/service/<%=method%>/lomadee/<%=id%>/<%=country%>/');

module.exports = function (opts) {
  return new Buscape(opts);
};

var Buscape = function Buscape (opts) {
  // Use production by default
  this._service = 'bws.buscape.com';

  // Allow keywords string in place of opts
  opts = 'string' === typeof opts ? {keywords: opts} : opts;

  if (opts.keywords) {
    this._keywords = opts.keywords;
    this.mode = 'search';
  }
};

// Set application id
Buscape.prototype.id = function (id) {
  return this._id = id, this;
};

// Set price range
Buscape.prototype.price = function (price) {
  // Allow min..max style pricerange
  price = ('string' === typeof price) ? price.split('..') : price;

  if (price[0]) this._minPrice = price[0];
  if (price[1]) this._maxPrice = price[0];

  return this;
};

// Set search country
Buscape.prototype.country = function (country) {
  return this._country = country, this;
};

// Enable or disable test mode (make calls to the sanbox, rather than primary)
Buscape.prototype.test = function (test) {
  // Default test to true
  test = (arguments.length === 0 ? true : !!test)
  return this._service = test ? 'sandbox.buscape.com' : 'bws.buscape.com', this;
};

// Return a limited number of results
Buscape.prototype.limit = function (limit) {
  // Don't accept falsy or 0 limits
  if (!limit) return this;
  return this._limit = limit, this;
};

// Return only one result
Buscape.prototype.one = function (one) {
  // Default one to true
  one = (arguments.length === 0 ? true : !!one)
  return this._one = one, this;
};

// Set caller ip address
Buscape.prototype.client = function (ip) {
  return this._client = ip, this;
}

Buscape.prototype.done = function (cb) {
  request
    .get(endpoint({
      service: this._service,
      method: 'findProductList',
      id: this._id,
      country: this._country || 'BR'
    }))
    .query({keyword: this._keywords})
    .query({priceMin: this._minPrice})
    .query({priceMax: this._priceMax})
    .query({clientIp: this._client})
    .query({format: 'json'})
    .end(function (err, res) {
      if (err) return cb(err);
      if (!res.body.product) return cb(new Error('Invalid response'));

      // Format results
      var formatted = format(res.body.product);

      // Limit
      if (this._limit) {
        formatted = _.first(formatted, this._limit);
      }

      // One
      if (this._one) {
        formatted = _.first(formatted);
      }

      return cb(null, formatted);
    }.bind(this));
};

var format = function (products) {
  return products.map(function (product) {
    var p = product.product
      , name = p.productname || p.productshortname
      , price = p.pricemin || p.pricemax
      , offers = p.numoffers
      , currency = p.currency.abbreviation
      , link = productLink(p.links)
      , id = p.id;

    // Filter unusable results
    if (!p || !name || !price || !link) return null;

    return {
      name: name,
      listPrice: price,
      remaining: offers,
      currency: currency,
      url: link,
      id: id
    }
  })
  .filter(function (p) {
    return p !== null
  });
};

var productLink = function (links) {
  var productLink = _.find(links, function (l) {
    return l.link.type === 'product';
  });

  return productLink.link.url || null;
};
<commit_msg>Behave a little more sensibly when no results found<commit_after>/**
 * Module dependencies
 */
var request = require('superagent')
  , _ = require('underscore');

// Endpoint template
var endpoint = _.template('http://<%=service%>/service/<%=method%>/lomadee/<%=id%>/<%=country%>/');

module.exports = function (opts) {
  return new Buscape(opts);
};

var Buscape = function Buscape (opts) {
  // Use production by default
  this._service = 'bws.buscape.com';

  // Allow keywords string in place of opts
  opts = 'string' === typeof opts ? {keywords: opts} : opts;

  if (opts.keywords) {
    this._keywords = opts.keywords;
    this.mode = 'search';
  }
};

// Set application id
Buscape.prototype.id = function (id) {
  return this._id = id, this;
};

// Set price range
Buscape.prototype.price = function (price) {
  // Allow min..max style pricerange
  price = ('string' === typeof price) ? price.split('..') : price;

  if (price[0]) this._minPrice = price[0];
  if (price[1]) this._maxPrice = price[0];

  return this;
};

// Set search country
Buscape.prototype.country = function (country) {
  return this._country = country, this;
};

// Enable or disable test mode (make calls to the sanbox, rather than primary)
Buscape.prototype.test = function (test) {
  // Default test to true
  test = (arguments.length === 0 ? true : !!test)
  return this._service = test ? 'sandbox.buscape.com' : 'bws.buscape.com', this;
};

// Return a limited number of results
Buscape.prototype.limit = function (limit) {
  // Don't accept falsy or 0 limits
  if (!limit) return this;
  return this._limit = limit, this;
};

// Return only one result
Buscape.prototype.one = function (one) {
  // Default one to true
  one = (arguments.length === 0 ? true : !!one)
  return this._one = one, this;
};

// Set caller ip address
Buscape.prototype.client = function (ip) {
  return this._client = ip, this;
}

Buscape.prototype.done = function (cb) {
  request
    .get(endpoint({
      service: this._service,
      method: 'findProductList',
      id: this._id,
      country: this._country || 'BR'
    }))
    .query({keyword: this._keywords})
    .query({priceMin: this._minPrice})
    .query({priceMax: this._priceMax})
    .query({clientIp: this._client})
    .query({format: 'json'})
    .end(function (err, res) {
      if (err) return cb(err);
      // No products found
      if (!res.body.product) return cb(null, this._one ? null : [])

      // Format results
      var formatted = format(res.body.product);

      // Limit
      if (this._limit) {
        formatted = _.first(formatted, this._limit);
      }

      // One
      if (this._one) {
        formatted = _.first(formatted);
      }

      return cb(null, formatted);
    }.bind(this));
};

var format = function (products) {
  return products.map(function (product) {
    var p = product.product
      , name = p.productname || p.productshortname
      , price = p.pricemin || p.pricemax
      , offers = p.numoffers
      , currency = p.currency.abbreviation
      , link = productLink(p.links)
      , id = p.id;

    // Filter unusable results
    if (!p || !name || !price || !link) return null;

    return {
      name: name,
      listPrice: price,
      remaining: offers,
      currency: currency,
      url: link,
      id: id
    }
  })
  .filter(function (p) {
    return p !== null
  });
};

var productLink = function (links) {
  var productLink = _.find(links, function (l) {
    return l.link.type === 'product';
  });

  return productLink.link.url || null;
};
<|endoftext|>


<commit_before>const S3rver = require('s3rver');
const fs = require('fs-extra'); // Using fs-extra to ensure destination directory exist
const AWS = require('aws-sdk');
const shell = require('shelljs');
const path = require('path');
const uuid = require('uuid/v1');
const functionHelper = require('serverless-offline/src/functionHelper');
const createLambdaContext = require('serverless-offline/src/createLambdaContext');

const defaultOptions = {
  port: 4569,
  host: 'localhost',
  location: '.'
}

class ServerlessS3Local {
  constructor(serverless, options) {
    this.serverless = serverless;
    this.service = serverless.service;
    this.options = options;
    this.provider = 'aws';
    this.client = null;

    this.commands = {
      s3: {
        commands: {
          start: {
            usage: 'Start S3 local server.',
            lifecycleEvents: ['startHandler'],
            options: {
              port: {
                shortcut: 'p',
                usage:
                  'The port number that S3 will use to communicate with your application. If you do not specify this option, the default port is 4569',
              },
              directory: {
                shortcut: 'd',
                usage:
                  'The directory where S3 will store its objects. If you do not specify this option, the file will be written to the current directory.',
              },
              buckets: {
                shortcut: 'b',
                usage: 'After starting S3 local, create specified buckets',
              },
              cors: {
                shortcut: 'c',
                usage: 'Enable CORS',
              },
              noStart: {
                shortcut: 'n',
                default: false,
                usage: 'Do not start S3 local (in case it is already running)',
              },
            },
          },
          create: {
            usage: 'Create local S3 buckets.',
            lifecycleEvents: ['createHandler'],
            options: {
              port: {
                shortcut: 'p',
                usage:
                  'The port number that S3 will use to communicate with your application. If you do not specify this option, the default port is 4569',
              },
              buckets: {
                shortcut: 'b',
                usage: 'After starting S3 local, create specified buckets',
              },
            }
          },
          remove: {
            usage: 'Remove local S3 buckets.',
            lifecycleEvents: ['createHandler'],
            options: {
              port: {
                shortcut: 'p',
                usage:
                  'The port number that S3 will use to communicate with your application. If you do not specify this option, the default port is 4569',
              },
              buckets: {
                shortcut: 'b',
                usage: 'After starting S3 local, create specified buckets',
              },
            }
          }
        },
      },
    };

    this.hooks = {
      's3:start:startHandler': this.startHandler.bind(this),
      's3:create:createHandler': this.createHandler.bind(this),
      's3:remove:createHandler': this.removeHandler.bind(this),
      'before:offline:start:init': this.startHandler.bind(this),
      'before:offline:start': this.startHandler.bind(this),
      'before:offline:start:end': this.endHandler.bind(this),
    };
  }

  startHandler() {
    return new Promise((resolve, reject) => {
      this._setOptions();
      const { noStart, port, host, cors } = this.options;
      if (noStart) {
        return this.createBuckets().then(resolve, reject);
      }

      const dirPath = this.options.directory || './buckets';
      fs.ensureDirSync(dirPath); // Create destination directory if not exist
      const directory = fs.realpathSync(dirPath);

      const corsPolicy = cors ?
            fs.readFileSync(path.resolve(this.serverless.config.servicePath, cors) , 'utf8') :
            cors ;

      this.client = new S3rver({
        port,
        hostname: host,
        silent: false,
        directory,
        cors: corsPolicy,
      }).run((err, s3Host, s3Port) => {
        if (err) {
          console.error('Error occurred while starting S3 local.');
          reject(err);
          return;
        }

        this.options.port = s3Port
        console.log(`S3 local started ( port:${s3Port} )`);

        this.createBuckets().then(resolve, reject);
      });

      this.eventHandlers = this.getEventHandlers();

      this.client.s3Event.map((event) => {
          const bucketName = event.Records[0].s3.bucket.name;
          const eventName = event.Records[0].eventName;
          const key = event.Records[0].s3.object.key;

          return this.eventHandlers
              .filter(handler => handler.name == bucketName)
              .filter(handler => eventName.match(handler.pattern) !== null)
              .filter(handler => handler.rules.every(rule => key.match(rule)))
              .map(handler => () => handler.func(event));
      }).mergeMap((handler) => {
          return handler;
      }).subscribe((handler) => {
          handler();
      });
    });
  }

  endHandler() {
    if (!this.options.noStart) {
      this.client.close();
      console.log('S3 local closed');
    }
  }

  createHandler() {
    this._setOptions();
    return this.createBuckets();
  }

  removeHandler() {
    this._setOptions();
    return this.removeBuckets();
  }

  createBuckets() {
    return Promise.resolve().then(() => {
      const buckets = this.buckets();
      if (!buckets.length) return;

      const s3Client = this.getClient();
      return Promise.all(buckets.map(Bucket => {
        this.serverless.cli.log(`creating bucket: ${Bucket}`);
        return s3Client.createBucket({ Bucket }).promise();
      }));
    })
    .catch(x => {});
  }

  removeBuckets() {
    return Promise.resolve().then(() => {
      const { port } = this.options;
      const buckets = this.buckets();
      if (!buckets.length) return;

      return Promise.all(buckets.map(bucket => {
        this.serverless.cli.log(`removing bucket: ${bucket}`);
        return removeBucket({ port, bucket });
      }));
    });
  }

  getClient() {
    return new AWS.S3({
      s3ForcePathStyle: true,
      endpoint: new AWS.Endpoint(`http://localhost:${this.options.port}`),
    });
  }

  getEventHandlers() {
      if (typeof this.service !== 'object' || typeof this.service.functions !== 'object') {
          return {}
      }

      const eventHandlers = [];
      const servicePath = path.join(this.serverless.config.servicePath, this.options.location);
      Object.keys(this.service.functions).forEach(key => {
          const serviceFunction = this.service.getFunction(key);

          let handler = null;
          const lambdaContext = createLambdaContext(serviceFunction);
          const funOptions = functionHelper.getFunctionOptions(serviceFunction, key, servicePath);
          const func = (s3Event) => {
              handler = handler || functionHelper.createHandler(funOptions, this.options);

              const oldEnv = process.env;
              try {
                  process.env = Object.assign(
                    {},
                    oldEnv,
                    serviceFunction.environment
                  );
                  handler(s3Event, lambdaContext, lambdaContext.done);
              }
              finally {
                  process.env = oldEnv;
              }
          };
          serviceFunction.events.forEach(event => {
              const s3 = (event && event.s3) || undefined;
              if (!s3) {
                  return;
              }

              const handlerBucketName = (typeof s3 === 'object') ? s3.bucket : s3;
              const bucketResource = this.getResourceForBucket(handlerBucketName);
              const name = bucketResource ? bucketResource.Properties.BucketName : handlerBucketName ;
              const pattern = (typeof s3 === 'object') ? s3.event.replace(/^s3:/,'').replace('*', '.*') :'.*';

              const rule2regex = (rule) => Object.keys(rule).map( key => key == 'prefix' && `^${rule[key]}` || `${rule[key]}$`);
              const rules = (typeof s3 === 'object') ? [].concat(...(s3.rules || []).map(rule2regex)) : [];

              eventHandlers.push({
                  name,
                  pattern,
                  rules,
                  func
              });
              this.serverless.cli.log(`Found S3 event listener for ${name}`);
          });
      });

      return eventHandlers;
  }

  getResourceForBucket(bucketName){
    const logicalResourceName = `S3Bucket${bucketName.charAt(0).toUpperCase()}${bucketName.substr(1)}`;
    return this.service.resources ? this.service.resources.Resources[logicalResourceName] : false ;
  }

  getAdditionalStacks() {
    const serviceAdditionalStacks = this.service.custom.additionalStacks || {};
    const additionalStacks = [];
    Object.keys(serviceAdditionalStacks).forEach((stack) => {
      additionalStacks.push(serviceAdditionalStacks[stack]);
    });
    return additionalStacks;
  }

  hasAdditionalStacksPlugin() {
    return (
      this.service &&
      this.service.plugins &&
      this.service.plugins.indexOf('serverless-plugin-additional-stacks') >= 0
    );
  }

  /**
   * Get bucket list from serverless.yml resources and additional stacks
   *
   * @return {object} Array of bucket name
   */
  buckets() {
    const resources = (this.service.resources && this.service.resources.Resources) || {};
    if (this.hasAdditionalStacksPlugin()) {
      let additionalStacks = [];
      additionalStacks = additionalStacks.concat(this.getAdditionalStacks());
      additionalStacks.forEach((stack) => {
        if (stack.Resources) {
          Object.keys(stack.Resources).forEach((key) => {
            if (stack.Resources[key].Type === 'AWS::S3::Bucket') {
              resources[key] = stack.Resources[key];
            }
          });
        }
      });
    }
    return Object.keys(resources)
      .map((key) => {
        if (resources[key].Type === 'AWS::S3::Bucket' && resources[key].Properties && resources[key].Properties.BucketName) {
          return resources[key].Properties.BucketName;
        }
        return null;
      })
      .concat(this.options.buckets)
      .filter(n => n);
  }

  _setOptions() {
    const config = (this.serverless.service.custom && this.serverless.service.custom.s3) || {};
    this.options = Object.assign({}, defaultOptions, (this.service.custom || {})['serverless-offline'], this.options, config);
  }
}

const removeBucket = ({ bucket, port }) => new Promise((resolve, reject) => {
  shell.exec(
    `aws --endpoint http://localhost:${port} s3 rb "s3://${bucket}" --force`,
    { silent: true },
    function (code, stdout, stderr) {
      if (code === 0) return resolve();
      if (stderr && stderr.indexOf('NoSuchBucket') !== -1) return resolve();

      reject(new Error(`failed to delete bucket ${bucket}: ${stderr || stdout}`));
    }
  );
});

module.exports = ServerlessS3Local;
<commit_msg>Add accessKeyId and secretAccessKey to S3 Client init to remove aws configure dependency<commit_after>const S3rver = require('s3rver');
const fs = require('fs-extra'); // Using fs-extra to ensure destination directory exist
const AWS = require('aws-sdk');
const shell = require('shelljs');
const path = require('path');
const uuid = require('uuid/v1');
const functionHelper = require('serverless-offline/src/functionHelper');
const createLambdaContext = require('serverless-offline/src/createLambdaContext');

const defaultOptions = {
  port: 4569,
  host: 'localhost',
  location: '.',
  accessKeyId: 'something has to be here',
  secretAccessKey: 'to prevent requiring ~/.aws/credentials',
}

class ServerlessS3Local {
  constructor(serverless, options) {
    this.serverless = serverless;
    this.service = serverless.service;
    this.options = options;
    this.provider = 'aws';
    this.client = null;

    this.commands = {
      s3: {
        commands: {
          start: {
            usage: 'Start S3 local server.',
            lifecycleEvents: ['startHandler'],
            options: {
              port: {
                shortcut: 'p',
                usage:
                  'The port number that S3 will use to communicate with your application. If you do not specify this option, the default port is 4569',
              },
              directory: {
                shortcut: 'd',
                usage:
                  'The directory where S3 will store its objects. If you do not specify this option, the file will be written to the current directory.',
              },
              buckets: {
                shortcut: 'b',
                usage: 'After starting S3 local, create specified buckets',
              },
              cors: {
                shortcut: 'c',
                usage: 'Enable CORS',
              },
              noStart: {
                shortcut: 'n',
                default: false,
                usage: 'Do not start S3 local (in case it is already running)',
              },
            },
          },
          create: {
            usage: 'Create local S3 buckets.',
            lifecycleEvents: ['createHandler'],
            options: {
              port: {
                shortcut: 'p',
                usage:
                  'The port number that S3 will use to communicate with your application. If you do not specify this option, the default port is 4569',
              },
              buckets: {
                shortcut: 'b',
                usage: 'After starting S3 local, create specified buckets',
              },
            }
          },
          remove: {
            usage: 'Remove local S3 buckets.',
            lifecycleEvents: ['createHandler'],
            options: {
              port: {
                shortcut: 'p',
                usage:
                  'The port number that S3 will use to communicate with your application. If you do not specify this option, the default port is 4569',
              },
              buckets: {
                shortcut: 'b',
                usage: 'After starting S3 local, create specified buckets',
              },
            }
          }
        },
      },
    };

    this.hooks = {
      's3:start:startHandler': this.startHandler.bind(this),
      's3:create:createHandler': this.createHandler.bind(this),
      's3:remove:createHandler': this.removeHandler.bind(this),
      'before:offline:start:init': this.startHandler.bind(this),
      'before:offline:start': this.startHandler.bind(this),
      'before:offline:start:end': this.endHandler.bind(this),
    };
  }

  startHandler() {
    return new Promise((resolve, reject) => {
      this._setOptions();
      const { noStart, port, host, cors } = this.options;
      if (noStart) {
        return this.createBuckets().then(resolve, reject);
      }

      const dirPath = this.options.directory || './buckets';
      fs.ensureDirSync(dirPath); // Create destination directory if not exist
      const directory = fs.realpathSync(dirPath);

      const corsPolicy = cors ?
            fs.readFileSync(path.resolve(this.serverless.config.servicePath, cors) , 'utf8') :
            cors ;

      this.client = new S3rver({
        port,
        hostname: host,
        silent: false,
        directory,
        cors: corsPolicy,
      }).run((err, s3Host, s3Port) => {
        if (err) {
          console.error('Error occurred while starting S3 local.');
          reject(err);
          return;
        }

        this.options.port = s3Port
        console.log(`S3 local started ( port:${s3Port} )`);

        this.createBuckets().then(resolve, reject);
      });

      this.eventHandlers = this.getEventHandlers();

      this.client.s3Event.map((event) => {
          const bucketName = event.Records[0].s3.bucket.name;
          const eventName = event.Records[0].eventName;
          const key = event.Records[0].s3.object.key;

          return this.eventHandlers
              .filter(handler => handler.name == bucketName)
              .filter(handler => eventName.match(handler.pattern) !== null)
              .filter(handler => handler.rules.every(rule => key.match(rule)))
              .map(handler => () => handler.func(event));
      }).mergeMap((handler) => {
          return handler;
      }).subscribe((handler) => {
          handler();
      });
    });
  }

  endHandler() {
    if (!this.options.noStart) {
      this.client.close();
      console.log('S3 local closed');
    }
  }

  createHandler() {
    this._setOptions();
    return this.createBuckets();
  }

  removeHandler() {
    this._setOptions();
    return this.removeBuckets();
  }

  createBuckets() {
    return Promise.resolve().then(() => {
      const buckets = this.buckets();
      if (!buckets.length) return;

      const s3Client = this.getClient();
      return Promise.all(buckets.map(Bucket => {
        this.serverless.cli.log(`creating bucket: ${Bucket}`);
        return s3Client.createBucket({ Bucket }).promise();
      }));
    })
    .catch(x => {});
  }

  removeBuckets() {
    return Promise.resolve().then(() => {
      const { port } = this.options;
      const buckets = this.buckets();
      if (!buckets.length) return;

      return Promise.all(buckets.map(bucket => {
        this.serverless.cli.log(`removing bucket: ${bucket}`);
        return removeBucket({ port, bucket });
      }));
    });
  }

  getClient() {
    return new AWS.S3({
      s3ForcePathStyle: true,
      endpoint: new AWS.Endpoint(`http://${this.options.host}:${this.options.port}`),
      accessKeyId: this.options.accessKeyId,
      secretAccessKey: this.options.secretAccessKey,
    });
  }

  getEventHandlers() {
      if (typeof this.service !== 'object' || typeof this.service.functions !== 'object') {
          return {}
      }

      const eventHandlers = [];
      const servicePath = path.join(this.serverless.config.servicePath, this.options.location);
      Object.keys(this.service.functions).forEach(key => {
          const serviceFunction = this.service.getFunction(key);

          let handler = null;
          const lambdaContext = createLambdaContext(serviceFunction);
          const funOptions = functionHelper.getFunctionOptions(serviceFunction, key, servicePath);
          const func = (s3Event) => {
              handler = handler || functionHelper.createHandler(funOptions, this.options);

              const oldEnv = process.env;
              try {
                  process.env = Object.assign(
                    {},
                    oldEnv,
                    serviceFunction.environment
                  );
                  handler(s3Event, lambdaContext, lambdaContext.done);
              }
              finally {
                  process.env = oldEnv;
              }
          };
          serviceFunction.events.forEach(event => {
              const s3 = (event && event.s3) || undefined;
              if (!s3) {
                  return;
              }

              const handlerBucketName = (typeof s3 === 'object') ? s3.bucket : s3;
              const bucketResource = this.getResourceForBucket(handlerBucketName);
              const name = bucketResource ? bucketResource.Properties.BucketName : handlerBucketName ;
              const pattern = (typeof s3 === 'object') ? s3.event.replace(/^s3:/,'').replace('*', '.*') :'.*';

              const rule2regex = (rule) => Object.keys(rule).map( key => key == 'prefix' && `^${rule[key]}` || `${rule[key]}$`);
              const rules = (typeof s3 === 'object') ? [].concat(...(s3.rules || []).map(rule2regex)) : [];

              eventHandlers.push({
                  name,
                  pattern,
                  rules,
                  func
              });
              this.serverless.cli.log(`Found S3 event listener for ${name}`);
          });
      });

      return eventHandlers;
  }

  getResourceForBucket(bucketName){
    const logicalResourceName = `S3Bucket${bucketName.charAt(0).toUpperCase()}${bucketName.substr(1)}`;
    return this.service.resources ? this.service.resources.Resources[logicalResourceName] : false ;
  }

  getAdditionalStacks() {
    const serviceAdditionalStacks = this.service.custom.additionalStacks || {};
    const additionalStacks = [];
    Object.keys(serviceAdditionalStacks).forEach((stack) => {
      additionalStacks.push(serviceAdditionalStacks[stack]);
    });
    return additionalStacks;
  }

  hasAdditionalStacksPlugin() {
    return (
      this.service &&
      this.service.plugins &&
      this.service.plugins.indexOf('serverless-plugin-additional-stacks') >= 0
    );
  }

  /**
   * Get bucket list from serverless.yml resources and additional stacks
   *
   * @return {object} Array of bucket name
   */
  buckets() {
    const resources = (this.service.resources && this.service.resources.Resources) || {};
    if (this.hasAdditionalStacksPlugin()) {
      let additionalStacks = [];
      additionalStacks = additionalStacks.concat(this.getAdditionalStacks());
      additionalStacks.forEach((stack) => {
        if (stack.Resources) {
          Object.keys(stack.Resources).forEach((key) => {
            if (stack.Resources[key].Type === 'AWS::S3::Bucket') {
              resources[key] = stack.Resources[key];
            }
          });
        }
      });
    }
    return Object.keys(resources)
      .map((key) => {
        if (resources[key].Type === 'AWS::S3::Bucket' && resources[key].Properties && resources[key].Properties.BucketName) {
          return resources[key].Properties.BucketName;
        }
        return null;
      })
      .concat(this.options.buckets)
      .filter(n => n);
  }

  _setOptions() {
    const config = (this.serverless.service.custom && this.serverless.service.custom.s3) || {};
    this.options = Object.assign({}, defaultOptions, (this.service.custom || {})['serverless-offline'], this.options, config);
  }
}

const removeBucket = ({ bucket, port }) => new Promise((resolve, reject) => {
  shell.exec(
    `aws --endpoint http://localhost:${port} s3 rb "s3://${bucket}" --force`,
    { silent: true },
    function (code, stdout, stderr) {
      if (code === 0) return resolve();
      if (stderr && stderr.indexOf('NoSuchBucket') !== -1) return resolve();

      reject(new Error(`failed to delete bucket ${bucket}: ${stderr || stdout}`));
    }
  );
});

module.exports = ServerlessS3Local;
<|endoftext|>


<commit_before>//jqui
window.since = null;
window.until = null;

window.pid = null;

window._result = null;
window._resultArray = null;

$(function() {
    window.since = $( "#since" );
    window.until = $( "#until" );
    window.pid = $( "#pid" );
    window._result = $("#result");

    window.since.datepicker({
        regional: "zh-TW",
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        changeYear: true,
        onClose: function( selectedDate ) {
            window.until.datepicker( "option", "minDate", selectedDate );
        }
    });
    window.until.datepicker({
        regional: "zh-TW",
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        changeYear: true,
        onClose: function( selectedDate ) {
            window.since.datepicker( "option", "maxDate", selectedDate );
        }
    });

    if(!!Cookies.get("pid")) {
        window.pid.val( Cookies.get("pid") );
    }
});

//init once.
window.initonce = false;

//uid
window.uid = null;

//accessToken
window.accessToken = null;

window.loopquery = function(url) {

    console.log("==loopquery==");

    if(!!url) {

        $.get(url, function(response) {

            console.log(response);

            //is no error
            if (response && !response.error) {

                console.log(response);
                console.log(response.data);
                console.log(response.data.length);

                if (!!response && !!response.data && response.data.length != 0) {
                    window.totalcount = window.totalcount + response.data.length;
                    //output result
                    window._result.text(window.totalcount);
                    //push
                    window._resultArray.push(response.data);
                }
            }

            //if over 100 && has next
            if(!!response && !!response.paging && !!response.paging.next) {
                console.log(response.paging);
                console.log(response.paging.next);

                setTimeout(function() {
                    window.loopquery(response.paging.next);
                }, 300);
            }

            if(!!response && !!response.data && response.data.length === 0) {
                $("#execute").show();
                console.log("==result==")
                console.log(window._resultArray);
                //render
                window.ReactRender();
            }

        });

    }

};

//fbAsyncInit on pageload
window.fbAsyncInit = function() {

    console.log("==fbAsyncInit==");

    //Turn Init Off.
    initonce = true;

    FB.init({
        appId: '442137115889177',
        xfbml: true,
        oauth: true,
        version: 'v2.5'
    });

    //check Login Status
    FB.getLoginStatus(function (response) {

        //authorized success now can connected
        if (response.status === "connected") {

            $("#getFBLogin").hide();
            $("#execute").show();

            //Welcome Message Display.
            FB.api("/me", function (response) {

                console.log("/me :", response);

                $("#message").text("Welocome Back：" + response.name + "！");

            });

        }else{

            $("#getFBLogin").show();
            $("#execute").hide();

        }

    });

};

//get Facebook Login Authorized
window.getFBLogin = function() {

    console.log("==getFBLogin==");

    //Check init once
    if(!!!window.initonce) {

        //Exe Init.
        window.fbAsyncInit();

    } else {

        FB.login(function(response) {

            console.log("FB.login", response);

            //reload
            window.location.replace( window.location.href );

        },{
            scope: 'user_posts'
        });

    }

};

window.totalcount = 0;

//getFBAllPostsCount
window.getFBAllPostsCount = function() {

    console.log("==getFBAllPostsCount==");

    $("#execute").hide();

    window.totalcount = 0;

    window._resultArray = [];

    //Check init once
    if(!!!window.initonce) {

        //Exe Init.
        window.fbAsyncInit();

    } else {

        //check Login Status
        FB.getLoginStatus(function (response) {

            //authorized success now can connected
            if (response.status === "connected") {

                // 程式有連結到 Facebook 帳號
                console.log("authorized success [response]:", response);

                // Get UID
                window.uid = response.authResponse.userID;
                // Get accessToken
                window.accessToken = response.authResponse.accessToken;

                if( !!!window.pid.val() ) {

                    alert("please enter a Pid.");

                } else if (window.uid && window.accessToken) {

                    //Cookies Set
                    Cookies.set("pid", window.pid.val())

                    var min = null;
                    var max = null;

                    if ( !!window.since.datepicker( "getDate" ) ) {
                        min = window.since.datepicker( "getDate" );
                    } else {
                        min = new Date();
                    }
                    console.log("min str:", min.toISOString());

                    if ( !!window.until.datepicker( "getDate" ) ) {
                        max = window.until.datepicker( "getDate" );
                    } else {
                        max = new Date();
                    }
                    console.log("max str:", max.toISOString());

                    min.setHours(0);
                    min.setMinutes(0);
                    min.setSeconds(0);
                    min.setMilliseconds(0);

                    console.log("min str:", min.toISOString());

                    max.setHours(23);
                    max.setMinutes(59);
                    max.setSeconds(59);
                    max.setMilliseconds(999);

                    console.log("max str:", max.toISOString());

                    FB.api('/' + window.pid.val() + '',
                      'GET', {"fields":"posts.limit(100)"+
                        ".since("
                            + min.toISOString() +
                        ").until("
                            + max.toISOString() +
                        "){type,message,link}"},
                      function(response) {

                        //is no error
                        if (!!response && !!!response.error) {

                            if (!!response && !!response.posts && !!response.posts.data && response.posts.data.length >= 0) {

                                console.log(response);
                                console.log(response.posts);
                                console.log(response.posts.data);
                                console.log(response.posts.data.length);

                                window.totalcount = window.totalcount + response.posts.data.length;
                                //output result
                                window._result.text(window.totalcount);
                                //push
                                window._resultArray.push(response.posts.data);
                            }
                        }

                        //if over 100 && has next
                        if(!!response && !!response.posts && !!response.posts.paging && !!response.posts.paging.next) {

                            console.log(response.posts.paging);
                            console.log(response.posts.paging.next);

                            window.loopquery(response.posts.paging.next);
                        }

                      }
                    );

                }

            } else if (response.status === "not_authorized" || !!!response.authResponse) {

                // 帳號沒有授權 Facebook App 程式 撈取資料
                console.log("not_authorized  [response]:", response);

                //getFBLogin
                window.getFBLogin();

            } else {
                // 帳號沒有登入 請膽擊Facebook Login按鈕執行
                alert("please click Facebook login button to authorized execute.");
            }

            window.uid = null;
            window.accessToken = null;

        });

    }
};

(function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/zh_TW/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<commit_msg>removed console.log mark. add push and count total get max count to display.<commit_after>//jqui
window.since = null;
window.until = null;

window.pid = null;

window._result = null;
window._resultArray = null;

$(function() {
    window.since = $( "#since" );
    window.until = $( "#until" );
    window.pid = $( "#pid" );
    window._result = $("#result");

    window.since.datepicker({
        regional: "zh-TW",
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        changeYear: true,
        onClose: function( selectedDate ) {
            window.until.datepicker( "option", "minDate", selectedDate );
        }
    });
    window.until.datepicker({
        regional: "zh-TW",
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        changeYear: true,
        onClose: function( selectedDate ) {
            window.since.datepicker( "option", "maxDate", selectedDate );
        }
    });

    if(!!Cookies.get("pid")) {
        window.pid.val( Cookies.get("pid") );
    }
});

//init once.
window.initonce = false;

//uid
window.uid = null;

//accessToken
window.accessToken = null;

window.loopquery = function(url) {

    console.log("==loopquery==");

    if(!!url) {

        $.get(url, function(response) {

            //is no error
            if (response && !response.error) {

                if (!!response && !!response.data && response.data.length != 0) {
                    //Count Total
                    window.totalcount = window.totalcount + response.data.length;
                    //push
                    for(var p = 0; p < response.posts.data.length; p++) {
                        window._resultArray.push(response.posts.data[p]);
                    }
                    //output result
                    window._result.text(Math.max(window.totalcount, window._resultArray.length));
                }
            }

            //if over 100 && has next
            if(!!response && !!response.paging && !!response.paging.next) {

                setTimeout(function() {
                    window.loopquery(response.paging.next);
                }, 300);
            }

            if(!!response && !!response.data && response.data.length === 0) {

                $("#execute").show();

                console.log("==result==")

                //render
                window.ReactRender(window._resultArray);

            }

        });

    }

};

//fbAsyncInit on pageload
window.fbAsyncInit = function() {

    console.log("==fbAsyncInit==");

    //Turn Init Off.
    initonce = true;

    FB.init({
        appId: '442137115889177',
        xfbml: true,
        oauth: true,
        version: 'v2.5'
    });

    //check Login Status
    FB.getLoginStatus(function (response) {

        //authorized success now can connected
        if (response.status === "connected") {

            $("#getFBLogin").hide();
            $("#execute").show();

            //Welcome Message Display.
            FB.api("/me", function (response) {

                console.log("/me :", response);

                $("#message").text("Welocome Back：" + response.name + "！");

            });

        }else{

            $("#getFBLogin").show();
            $("#execute").hide();

        }

    });

};

//get Facebook Login Authorized
window.getFBLogin = function() {

    console.log("==getFBLogin==");

    //Check init once
    if(!!!window.initonce) {

        //Exe Init.
        window.fbAsyncInit();

    } else {

        FB.login(function(response) {

            console.log("FB.login", response);

            //reload
            window.location.replace( window.location.href );

        },{
            scope: 'user_posts'
        });

    }

};

window.totalcount = 0;

//getFBAllPostsCount
window.getFBAllPostsCount = function() {

    console.log("==getFBAllPostsCount==");

    $("#execute").hide();

    window.totalcount = 0;

    window._resultArray = [];

    //Check init once
    if(!!!window.initonce) {

        //Exe Init.
        window.fbAsyncInit();

    } else {

        //check Login Status
        FB.getLoginStatus(function (response) {

            //authorized success now can connected
            if (response.status === "connected") {

                // 程式有連結到 Facebook 帳號
                console.log("authorized success [response]:", response);

                // Get UID
                window.uid = response.authResponse.userID;
                // Get accessToken
                window.accessToken = response.authResponse.accessToken;

                if( !!!window.pid.val() ) {

                    alert("please enter a Pid.");

                } else if (window.uid && window.accessToken) {

                    //Cookies Set
                    Cookies.set("pid", window.pid.val())

                    var min = null;
                    var max = null;

                    if ( !!window.since.datepicker( "getDate" ) ) {
                        min = window.since.datepicker( "getDate" );
                    } else {
                        min = new Date();
                    }
                    console.log("min str:", min.toISOString());

                    if ( !!window.until.datepicker( "getDate" ) ) {
                        max = window.until.datepicker( "getDate" );
                    } else {
                        max = new Date();
                    }
                    console.log("max str:", max.toISOString());

                    min.setHours(0);
                    min.setMinutes(0);
                    min.setSeconds(0);
                    min.setMilliseconds(0);

                    console.log("min str:", min.toISOString());

                    max.setHours(23);
                    max.setMinutes(59);
                    max.setSeconds(59);
                    max.setMilliseconds(999);

                    console.log("max str:", max.toISOString());

                    FB.api('/' + window.pid.val() + '',
                      'GET', {"fields":"posts.limit(100)"+
                        ".since("
                            + min.toISOString() +
                        ").until("
                            + max.toISOString() +
                        "){type,message,link}"},
                      function(response) {

                        //is no error
                        if (!!response && !!!response.error) {

                            if (!!response && !!response.posts && !!response.posts.data && response.posts.data.length >= 0) {

                                //Count Total
                                window.totalcount = window.totalcount + response.posts.data.length;

                                //push
                                for(var p = 0; p < response.posts.data.length; p++) {
                                    window._resultArray.push(response.posts.data[p]);
                                }

                                //output result
                                window._result.text(Math.max(window.totalcount, window._resultArray.length));

                            }
                        }

                        //if over 100 && has next
                        if(!!response && !!response.posts && !!response.posts.paging && !!response.posts.paging.next) {

                            window.loopquery(response.posts.paging.next);

                        }

                      }
                    );

                }

            } else if (response.status === "not_authorized" || !!!response.authResponse) {

                // 帳號沒有授權 Facebook App 程式 撈取資料
                console.log("not_authorized  [response]:", response);

                //getFBLogin
                window.getFBLogin();

            } else {
                // 帳號沒有登入 請膽擊Facebook Login按鈕執行
                alert("please click Facebook login button to authorized execute.");
            }

            window.uid = null;
            window.accessToken = null;

        });

    }
};

(function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/zh_TW/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<|endoftext|>


<commit_before>'use strict';

module.exports = function() {};
<commit_msg>Added source<commit_after>// 'use strict';

var modal_base_element;
var modal_background;
var modal_element;
var text_element_title;
var text_element_text;
var buttons_container;
var button_confirm;
var button_cancel;
var button_confirm_p;
var button_cancel_p;

var modal_width 		= 440;
var modal_height 		= 200;
var modal_width_px 		= String(modal_width) + 'px';
var modal_height_px		= String(modal_height) + 'px';

var settings = {

	closeOnOKClick 			: false,
	type 					: 'simple',
	titleText				: 'Title',
	textText				: 'Text',
	confirmButtonText 		: 'OK',
	cancelButtonText 		: 'Cancel',
	showTitle 				: true,
	showText 				: true,
	fontFamily 				: 'sans serif',
	titleMarginBottom 		: '30px',
	buttonsMarginTop 		: '30px',
	addButtons 				: false,
	showConfirmButton 		: true,
	showCancelButton 		: true,
	confirmButtonColor 		: '#27AE60',
	cancelButtonColor 		: '#E74C3C',
	confirmButtonTextColor	: 'white',
	cancelButtonTextColor	: 'white',
	defaultCancelIsClose	: true,
	defaultOKIsClose		: false,
	cancelCallback			: null,
	confirmCallback			: null,
	fadeOut					: true,
	modalPadding			: '30px 70px 30px 70px',
};

module.exports = {

    createModal: function(options)
    {
    	console.log('createModal');

    	$.extend( settings, options );

    	var w=window,
		d=document,
		e=d.documentElement,
		g=d.getElementsByTagName('body')[0],
		x=w.innerWidth||e.clientWidth||g.clientWidth,
		y=w.innerHeight||e.clientHeight||g.clientHeight;

		var window_width 		= x;
		var window_height 		= y;

		var window_width_px 	= String(window_width) + 'px';
		var window_height_px	= String(window_height) + 'px';

    	var title 				= 'title';
    	var text 				= 'text';

        modal_base_element		= document.createElement('DIV');
        modal_background		= document.createElement('DIV');
        modal_element 			= document.createElement('DIV');
        text_element_title 		= document.createElement('H3');
        text_element_text 		= document.createElement('p');

        modal_background.addClass('ui-modal-background');
        modal_element.addClass('ui-modal-element');

        if (settings.showConfirmButton || settings.showCancelButton)
        {
        	console.log('1');
        	settings.addButtons 						= true;
        	buttons_container							= document.createElement('DIV');
        	buttons_container.style.marginTop 			= settings.buttonsMarginTop;
        	buttons_container.setAttribute('id', 		'ui-modal-buttons');

        	if (settings.showCancelButton)
        	{
        		console.log('2');
	        	button_cancel							= document.createElement('DIV');
	        	button_cancel.addClass('ui-button');
	        	button_cancel.addClass('cancel');
	        	button_cancel.style.backgroundColor 	= settings.cancelButtonColor;
	        	button_cancel.style.color 				= settings.cancelButtonTextColor;
	        	button_cancel.style.paddingTop 			= '10px';
	        	button_cancel.style.paddingBottom 		= '10px';
	        	button_cancel.style.paddingLeft 		= '20px';
	        	button_cancel.style.paddingRight 		= '20px';
	        	button_cancel.style.minWidth 			= '80px';
	        	if (settings.showConfirmButton ) 		{ button_cancel.style.marginRight = '40px'; };
	        	button_cancel.textContent 				= settings.cancelButtonText;
	        	// button_cancel.appendChild(button_cancel_p);
	        	buttons_container.appendChild(button_cancel);

	        	if (settings.defaultCancelIsClose)
	        	{ 		 button_cancel.addEventListener('click', closeModal);
	        	} else { button_cancel.addEventListener('click', settings.cancelCallback); }
        	};

        	if (settings.showConfirmButton)
        	{
        		console.log('3');
	        	button_confirm							= document.createElement('DIV');
	        	button_confirm.addClass('ui-button');
	        	button_confirm.addClass('confirm');
	        	button_confirm.style.backgroundColor	=  settings.confirmButtonColor;
	        	button_confirm.style.color 				= settings.confirmButtonTextColor;
	        	button_confirm.style.paddingTop 		= '10px';
	        	button_confirm.style.paddingBottom 		= '10px';
	        	button_confirm.style.paddingLeft 		= '20px';
	        	button_confirm.style.paddingRight 		= '20px';
	        	button_confirm.style.minWidth 			= '80px';
	        	button_confirm.textContent 				= settings.confirmButtonText;
	        	// button_confirm.appendChild(button_confirm_p);
	        	buttons_container.appendChild(button_confirm);
	        	console.log('settings.defaultOKIsClose: ' + settings.defaultOKIsClose);
	        	if (settings.defaultOKIsClose)
	        	{
	        		button_confirm.addEventListener('click', closeModal);
	        	}
	        	else
	        	{
	        		button_confirm.addEventListener('click', handleConfirmCallback);
	        	}
        	};
        }
        else
        {
        	settings.addButtons = false;
        }

        if (settings.showTitle)
        {
        	text_element_title.textContent 			= settings.titleText;
        	text_element_title.style.marginBottom 	= settings.titleMarginBottom;
        	text_element_title.style.fontFamily 	= settings.fontFamily;
        };

        if (settings.showText)
        {
        	text_element_text.textContent 			= settings.textText;
        	text_element_text.style.fontFamily 		= settings.fontFamily;
        };

		modal_base_element.style.webkitTransition 	= 'all 0.5s';
		modal_base_element.style.mozTransition 		= 'all 0.5s';
		modal_base_element.style.msTransition 		= 'all 0.5s';
		modal_base_element.style.oTransition 		= 'all 0.5s';

		modal_base_element.style.position			= 'fixed';
		modal_base_element.style.top				= '0';
		modal_base_element.style.left				= '0';
		modal_base_element.style.width				= window_width_px;
		modal_base_element.style.height				= window_height_px;
		modal_base_element.style.zIndex				= '1000';
		modal_base_element.style.opacity			= '1';

		modal_background.style.position				= 'fixed';
		modal_background.style.top					= '0';
		modal_background.style.left					= '0';
		modal_background.style.width				= window_width_px;
		modal_background.style.height				= window_height_px;
		modal_background.style.backgroundColor 		= 'black';
		modal_background.style.display				= 'block';
		modal_background.style.opacity 				= '0.3';

		modal_element.style.position				= 'fixed';
        // modal_element.style.width					= modal_width_px;
        // modal_element.style.height					= modal_height_px;
        modal_element.style.backgroundColor 		= 'white';
		modal_element.style.display					= 'block';
		modal_element.style.textAlign				= 'center';
        modal_element.style.borderRadius			= '3px';
		modal_element.style.boxSizing				= 'border-box';
        // modal_element.style.padding 				= '20px';
		modal_element.style.padding 				= settings.modalPadding;

		modal_element.style.top						= String((window_height / 2) - (modal_height / 2)) + 'px';
		modal_element.style.left					= String((window_width / 2) - (modal_width / 2)) + 'px';

		modal_base_element.appendChild(modal_background);
		modal_base_element.appendChild(modal_element);

        if (settings.showTitle) {
        	modal_element.appendChild(text_element_title);
        };

        if (settings.showText) {
        	modal_element.appendChild(text_element_text);
        };

		if (settings.addButtons) {
			modal_element.appendChild(buttons_container);
		};

		modal_base_element.setAttribute('id', 'ui-modal');
		modal_element.setAttribute('id', 'ui-modal-element');

		document.getElementById('root-wrapper').appendChild(modal_base_element);

		if (settings.closeOnBGClick) {
			modal_background.addEventListener('click', closeModal);
		};

		addViewportListeners();
		adjustViewPortModal();
    }
}

var closeModal = function()
{
	removeViewportListeners();

	if (settings.showCancelButton)
	{
		if (settings.defaultCancelIsClose)
		{
			button_cancel.removeEventListener('click', closeModal);
		}
		else
		{
			button_cancel.removeEventListener('click', settings.cancelCallback);
		}
	};

	if (settings.showConfirmButton)
	{
		if (settings.defaultOKIsClose)
		{
			button_confirm.removeEventListener('click', closeModal);
		}
		else
		{
			button_confirm.removeEventListener('click', settings.confirmCallback);
		}
	};

	var removeElement = function() {
		document.getElementById('root-wrapper').removeChild(document.getElementById('ui-modal'));
	}

	if (settings.fadeOut)
	{
		modal_base_element.style.opacity = '0';

		setTimeout(function() { removeElement(); }, 500)
	}
	else { removeElement(); }
}

var addViewportListeners = function()
{
	console.log('addViewportListeners');
	if(window.attachEvent) 			 	{ console.log('1'); window.attachEvent('onresize', 	adjustViewPortModal);
	} else if(window.addEventListener) 	{ console.log('3'); window.addEventListener('resize', adjustViewPortModal, true);
	} else { 							//The browser does not support Javascript event binding
	}
}

var removeViewportListeners = function()
{
	console.log('removeViewportListeners');
	if(window.detachEvent)  				{ console.log('2'); window.detachEvent('onresize', 		adjustViewPortModal);
	} else if(window.removeEventListener) 	{ window.removeEventListener('resize', 	adjustViewPortModal);
	} else { 								//The browser does not support Javascript event binding
	}
}

var handleConfirmCallback = function()
{
	settings.confirmCallback();

	closeModal();
}

var adjustViewPortModal = function()
{
	console.log('addViewportListeners');

    var w=window,
		d=document,
		e=d.documentElement,
		g=d.getElementsByTagName('body')[0],
		x=w.innerWidth||e.clientWidth||g.clientWidth,
		y=w.innerHeight||e.clientHeight||g.clientHeight;

	var modal_instance 				= document.getElementById('ui-modal-element');

	if (modal_instance) {
		console.log('modal_instance.offsetWidth: ' + modal_instance.offsetWidth);
		console.log('modal_instance.offsetHeight: ' + modal_instance.offsetHeight);

		modal_background.style.width	= String(x) + 'px';
		modal_background.style.height	= String(y) + 'px';

		modal_instance.style.left		= String((x / 2) - (modal_instance.offsetWidth / 2)) + 'px';
		modal_instance.style.top		= String((y / 2) - (modal_instance.offsetHeight / 2)) + 'px';
	};
}
<|endoftext|>