<commit_before>/* global XLSX, XLS */
define(['alertify', 'alertify_defaults', 'XLSX'], function (alertify) {

  var DropSheet = function DropSheet(opts) {
    if (!opts) {
      opts = {};
    }
    var nullfunc = function () {
    };
    if (!opts.errors) {
      opts.errors = {};
    }
    if (!opts.handle_file) {
      opts.handle_file = handleFile;
    }
    if (!opts.errors.badfile) {
      opts.errors.badfile = nullfunc;
    }
    if (!opts.errors.pending) {
      opts.errors.pending = nullfunc;
    }
    if (!opts.errors.failed) {
      opts.errors.failed = nullfunc;
    }
    if (!opts.errors.large) {
      opts.errors.large = nullfunc;
    }
    if (!opts.on) {
      opts.on = {};
    }
    if (!opts.on.workstart) {
      opts.on.workstart = nullfunc;
    }
    if (!opts.on.workend) {
      opts.on.workend = nullfunc;
    }
    if (!opts.on.sheet) {
      opts.on.sheet = nullfunc;
    }
    if (!opts.on.wb) {
      opts.on.wb = nullfunc;
    }

    var rABS = typeof FileReader !== 'undefined' && typeof FileReader.prototype !== 'undefined' && typeof FileReader.prototype.readAsBinaryString !== 'undefined';
    // var useworker = typeof Worker !== 'undefined';
    var pending = false;

    // Various functions for reading in, parsing.
    function readFile(files) {

      var i, f;
      for (i = 0; i !== files.length; ++i) {
        f = files[i];
        var reader = new FileReader();

        reader.onload = function (e) {
          var data = e.target.result;

          var wb, arr = false;
          var readtype = {type: rABS ? 'binary' : 'base64'};
          if (!rABS) {
            arr = fixData(data);
            data = btoa(arr);
          }

          function doit() {
            try {
              opts.on.workstart();

              wb = XLSX.read(data, readtype);
              opts.on.workend(processWB(wb, 'XLSX'));
            } catch (e) {
              opts.errors.failed(e);
            }
          }

          if (e.target.result.length > 500000) {
            opts.errors.large(e.target.result.length, function (e) {
              if (e) {
                doit();
              }
            });
          } else {
            doit();
          }
        };
        if (rABS) {
          reader.readAsBinaryString(f);
        } else {
          reader.readAsArrayBuffer(f);
        }
      }
    }

    // Helper method for array buffer read-in.
    function fixData(data) {
      var o = '', l = 0, w = 10240;
      for (; l < data.byteLength / w; ++l) {
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
      }
      o += String.fromCharCode.apply(null, new Uint8Array(data.slice(o.length)));
      return o;
    }

    // Parses workbook for relevant cells.
    function processWB(wb, type, sheetidx) {
      var hotTable = opts.tables[0];
      var sheet = wb.Sheets[wb.SheetNames[0]];

      if ((sheet['A2'].h === 'Dollar Amount Spent with Local MBEs') &&
          (sheet['A3'].h === 'Dollar Amount Spent with MBEs') &&
          (sheet['A4'].h  === 'Total Dollar Amount Spent Procuring All Goods and Services') &&
          (sheet['A5'].h === 'Number of Local MBEs Contracted')) {
            hotTable.setDataAtCell(0,0, sheet['B2'].v);
            hotTable.setDataAtCell(1,0, sheet['B3'].v);
            hotTable.setDataAtCell(2,0, sheet['B4'].v);
            hotTable.setDataAtCell(3,0, sheet['B5'].v);

            return true;
      }
      return false;
    }

    // // Processes single XLSX JS worksheet and updates one Handsontable.
    // function processWS(ws, table_def, table) {
    //   // console.log("WORKSHEET", ws, table_def, table);

    //   // Clear existing values in case user is submitting updated sheet after error.
    //   //table.clear();

    //   // Default range for input section of spreadsheet, obtained from tables.json.
    //   var sheet_start = table_def.excel[0].start;
    //   var sheet_end = table_def.excel[0].end;

    //   // Ranges for handsontable.
    //   var table_start = XLS.utils.decode_cell(sheet_start);
    //   var table_end = XLS.utils.decode_cell(sheet_end);
    //   var num_rows = table_end.r - table_start.r + 1;
    //   var num_cols = table_end.c - table_start.c + 1;

    //   var changes = [];

    //   // Keys of XLSX js worksheet.
    //   var ws_keys = Object.keys(ws);

    //   // Default settings for matrix boundary.
    //   var matrix = XLSX.utils.sheet_to_json(ws, {raw: true, range: table_start.r, header: 1});

    //   // console.log("MATRIX", matrix)
    //   // Check if default range is correct based on top row name.
    //   if (!(ws[XLS.utils.encode_cell({r: table_start.r, c: table_start.c - 1})] !== undefined &&
    //       ws[XLS.utils.encode_cell({r: table_start.r, c: table_start.c - 1})].v === table_def.excel[0].firstrow)) {

    //     var found_row = false;

    //     // If table is not in expected position, get new boundaries.
    //     for (var i = 0; i < ws_keys.length; i++) {
    //       var key = ws_keys[i];

    //       // Parse for location of top row name.
    //       if (ws[key].v !== undefined && ws[key].v !== null && table_def.excel[0].firstrow.toString() === ws[key].v.toString()) {
    //         // Update to boundaries of table (start, end, etc.)
    //         var new_start_row = Number(XLS.utils.decode_cell(key).r);
    //         var new_start_col = Number(XLS.utils.decode_cell(key).c) + 1;
    //         sheet_start = XLSX.utils.encode_cell({r: new_start_row, c: new_start_col});
    //         sheet_end = XLSX.utils.encode_cell({r: new_start_row + num_rows - 1, c: new_start_col + num_cols - 1});
    //         table_start = XLSX.utils.decode_cell(sheet_start);
    //         table_end = XLSX.utils.decode_cell(sheet_end);
    //         matrix = XLSX.utils.sheet_to_json(ws, {raw: true, range: table_start.r, header: 1});
    //         found_row = true;
    //         break;
    //       }
    //     }

    //     // If expected row name not found.
    //     if (!found_row) {
    //       alertify.alert("Error!",
    //         "Spreadsheet format does not match original template. Please copy-and-paste or type data into the '" +
    //         table_def.name + "' table manually.");
    //       return false;
    //     }
    //   }

    //   // Filter array to get rid of undefined values/any headers.
    //   for (i = 0; i < matrix.length; i++) {
    //     matrix[i] = matrix[i].filter(function (cell) {
    //       return cell !== undefined && cell !== null && !isNaN(Number(cell));
    //     })
    //   }

    //   // Parsing sometimes leads to empty rows, remove these.
    //   for (var j = matrix.length - 1; j >= 0; j--) {
    //     if (matrix[j].length === 0) {
    //       matrix.splice(j, 1);
    //     }
    //   }

    //   // Check that number of expected numeric cells is correct. Otherwise alert user.
    //   // Row and column checks.
    //   if (matrix.length !== num_rows) {
    //     alertify.alert("Error!",
    //       "Spreadsheet format does not match original template, or there are empty cells, or non-numeric data. Please copy-and-paste or type data into the '" +
    //       table_def.name + "' table manually.");
    //     return false;
    //   }

    //   for (i = 0; i < matrix.length; i++) {
    //     if (matrix[i].length !== num_cols) {
    //       alertify.alert("Error!",
    //         "Spreadsheet format does not match original template, or there are empty cells, or non-numeric data. Please copy-and-paste or type data into the '" +
    //         table_def.name + "' table manually.");
    //       return false;
    //     }
    //   }

    //   // For each sheet, set value in handsontable.
    //   for (var r = 0; r < num_rows; r++) {
    //     for (var c = 0; c < num_cols; c++) {
    //       changes.push([r, c, matrix[r][c]]);
    //     }
    //   }

    //   if (changes.length > 0) {
    //     table.setDataAtCell(changes);
    //     return true;
    //   }

    //   alertify.alert("Error!",
    //     "Spreadsheet format does not match original template, or there are empty cells, or non-numeric data. Please copy-and-paste or type data into the '" +
    //     table_def.name + "' table manually.");
    //   return false;

    // }

    // For drag-and-drop.

    function handleDrop(e) {

      if (typeof jQuery !== 'undefined') {
        e.stopPropagation();
        e.preventDefault();
        if (pending) {
          return opts.errors.pending();
        }
        // var files = e.dataTransfer.files;
        $('#drop-area').removeClass('dragenter');
        // readFile(files);
        opts.handle_file(e);
      } else {
        alertify.alert("Error!", "Drag and drop not supported. Please use the 'Choose File' button or copy-and-paste data.");
      }

    }

    function handleDragover(e) {

      if (typeof jQuery !== 'undefined') {
        e.stopPropagation();
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
        $('#drop-area').removeClass('dragdefault');
        $('#drop-area').addClass('dragenter');
      } else {
        alertify.alert("Error!", "Drag and drop not supported. Please use the 'Choose File' button or copy-and-paste data.");
      }
    }

    function handleDragleave(e) {
      if (typeof jQuery !== 'undefined') {
        $('#drop-area').removeClass('dragenter');
      } else {
        alertify.alert("Error!", "Drag and drop not supported. Please use the 'Choose File' button or copy-and-paste data.");
      }
    }

    function handleClick(e) {
      if (typeof jQuery !== 'undefined') {
        $('#choose-file').click();
      } else {
        alertify.alert("Error!", "Drag and drop not supported. Please use the 'Choose File' button or copy-and-paste data.");
      }
    }

    if (opts.drop.addEventListener) {
      opts.drop.addEventListener('dragenter', handleDragover, false);
      opts.drop.addEventListener('dragleave', handleDragleave);
      opts.drop.addEventListener('dragover', handleDragover, false);
      opts.drop.addEventListener('drop', handleDrop, false);
      opts.choose.addEventListener('click', handleClick, false);
    }

    // For choosing a file using <input> (ie Choose File button).

    function handleFile(e) {
      var files;

      if (e.type === 'drop') {
        files = e.dataTransfer.files
      } else if (e.type === 'change') {
        files = e.target.files;
      }

      if (window.FileReader) {
        // FileReader is supported.
        readFile(files);
      } else {
        alertify.alert("Error!", 'FileReader is not supported in this browser.');
      }
    }

    if (opts.choose.addEventListener) {
      if (typeof jQuery !== 'undefined') {
        $('#choose-file').change(opts.handle_file);
      }
    }
  };

  return DropSheet;

});
<commit_msg>Deleted unused code<commit_after>/* global XLSX, XLS */
define(['alertify', 'alertify_defaults', 'XLSX'], function (alertify) {

  var DropSheet = function DropSheet(opts) {
    if (!opts) {
      opts = {};
    }
    var nullfunc = function () {
    };
    if (!opts.errors) {
      opts.errors = {};
    }
    if (!opts.handle_file) {
      opts.handle_file = handleFile;
    }
    if (!opts.errors.badfile) {
      opts.errors.badfile = nullfunc;
    }
    if (!opts.errors.pending) {
      opts.errors.pending = nullfunc;
    }
    if (!opts.errors.failed) {
      opts.errors.failed = nullfunc;
    }
    if (!opts.errors.large) {
      opts.errors.large = nullfunc;
    }
    if (!opts.on) {
      opts.on = {};
    }
    if (!opts.on.workstart) {
      opts.on.workstart = nullfunc;
    }
    if (!opts.on.workend) {
      opts.on.workend = nullfunc;
    }
    if (!opts.on.sheet) {
      opts.on.sheet = nullfunc;
    }
    if (!opts.on.wb) {
      opts.on.wb = nullfunc;
    }

    var rABS = typeof FileReader !== 'undefined' && typeof FileReader.prototype !== 'undefined' && typeof FileReader.prototype.readAsBinaryString !== 'undefined';
    // var useworker = typeof Worker !== 'undefined';
    var pending = false;

    // Various functions for reading in, parsing.
    function readFile(files) {

      var i, f;
      for (i = 0; i !== files.length; ++i) {
        f = files[i];
        var reader = new FileReader();

        reader.onload = function (e) {
          var data = e.target.result;

          var wb, arr = false;
          var readtype = {type: rABS ? 'binary' : 'base64'};
          if (!rABS) {
            arr = fixData(data);
            data = btoa(arr);
          }

          function doit() {
            try {
              opts.on.workstart();

              wb = XLSX.read(data, readtype);
              opts.on.workend(processWB(wb, 'XLSX'));
            } catch (e) {
              opts.errors.failed(e);
            }
          }

          if (e.target.result.length > 500000) {
            opts.errors.large(e.target.result.length, function (e) {
              if (e) {
                doit();
              }
            });
          } else {
            doit();
          }
        };
        if (rABS) {
          reader.readAsBinaryString(f);
        } else {
          reader.readAsArrayBuffer(f);
        }
      }
    }

    // Helper method for array buffer read-in.
    function fixData(data) {
      var o = '', l = 0, w = 10240;
      for (; l < data.byteLength / w; ++l) {
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
      }
      o += String.fromCharCode.apply(null, new Uint8Array(data.slice(o.length)));
      return o;
    }

    // Parses workbook for relevant cells.
    function processWB(wb, type, sheetidx) {
      var hotTable = opts.tables[0];
      var sheet = wb.Sheets[wb.SheetNames[0]];

      if ((sheet['A2'].h === 'Dollar Amount Spent with Local MBEs') &&
          (sheet['A3'].h === 'Dollar Amount Spent with MBEs') &&
          (sheet['A4'].h  === 'Total Dollar Amount Spent Procuring All Goods and Services') &&
          (sheet['A5'].h === 'Number of Local MBEs Contracted')) {
            hotTable.setDataAtCell(0,0, sheet['B2'].v);
            hotTable.setDataAtCell(1,0, sheet['B3'].v);
            hotTable.setDataAtCell(2,0, sheet['B4'].v);
            hotTable.setDataAtCell(3,0, sheet['B5'].v);

            return true;
      }
      return false;
    }

    // For drag-and-drop.

    function handleDrop(e) {

      if (typeof jQuery !== 'undefined') {
        e.stopPropagation();
        e.preventDefault();
        if (pending) {
          return opts.errors.pending();
        }
        // var files = e.dataTransfer.files;
        $('#drop-area').removeClass('dragenter');
        // readFile(files);
        opts.handle_file(e);
      } else {
        alertify.alert("Error!", "Drag and drop not supported. Please use the 'Choose File' button or copy-and-paste data.");
      }

    }

    function handleDragover(e) {

      if (typeof jQuery !== 'undefined') {
        e.stopPropagation();
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
        $('#drop-area').removeClass('dragdefault');
        $('#drop-area').addClass('dragenter');
      } else {
        alertify.alert("Error!", "Drag and drop not supported. Please use the 'Choose File' button or copy-and-paste data.");
      }
    }

    function handleDragleave(e) {
      if (typeof jQuery !== 'undefined') {
        $('#drop-area').removeClass('dragenter');
      } else {
        alertify.alert("Error!", "Drag and drop not supported. Please use the 'Choose File' button or copy-and-paste data.");
      }
    }

    function handleClick(e) {
      if (typeof jQuery !== 'undefined') {
        $('#choose-file').click();
      } else {
        alertify.alert("Error!", "Drag and drop not supported. Please use the 'Choose File' button or copy-and-paste data.");
      }
    }

    if (opts.drop.addEventListener) {
      opts.drop.addEventListener('dragenter', handleDragover, false);
      opts.drop.addEventListener('dragleave', handleDragleave);
      opts.drop.addEventListener('dragover', handleDragover, false);
      opts.drop.addEventListener('drop', handleDrop, false);
      opts.choose.addEventListener('click', handleClick, false);
    }

    // For choosing a file using <input> (ie Choose File button).

    function handleFile(e) {
      var files;

      if (e.type === 'drop') {
        files = e.dataTransfer.files
      } else if (e.type === 'change') {
        files = e.target.files;
      }

      if (window.FileReader) {
        // FileReader is supported.
        readFile(files);
      } else {
        alertify.alert("Error!", 'FileReader is not supported in this browser.');
      }
    }

    if (opts.choose.addEventListener) {
      if (typeof jQuery !== 'undefined') {
        $('#choose-file').change(opts.handle_file);
      }
    }
  };

  return DropSheet;

});
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src',
      'protos'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2019 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/cloudbuild',
    theme: 'lumen',
    default: {
      outputSourceFiles: false
    }
  },
  markdown: {
    idInHeadings: true
  }
};
<commit_msg>chore: update jsdoc with macro license (#73)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src',
      'protos'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2019 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/cloudbuild',
    theme: 'lumen',
    default: {
      outputSourceFiles: false
    }
  },
  markdown: {
    idInHeadings: true
  }
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';'
      },
      all: {
        src: ['src/log.js',         // logging system
              'src/DataStream.js',  // bit/byte/string read operations
              'src/DataStream-write.js',  // bit/byte/string write operations
              'src/DataStream-map.js',  // bit/byte/string other operations
              'src/descriptor.js',  // MPEG-4 descriptor parsing
              'src/box.js',         // base code for box parsing/writing
              'src/box-parse.js',   // box parsing code
              'src/box-write.js',   // box writing code
              'src/box-unpack.js',  // box code for sample manipulation
              'src/meta.js',        // box code for meta-related box parsing
              'src/text-mp4.js',  // text-based track manipulations
              'src/isofile.js',     // file level operations (read, write)
              'src/mp4box.js'       // application level operations (data append, sample extraction, segmentation, ...)
        ],
        dest: 'dist/<%= pkg.name %>.all.js'
      },
      simple: {
        src: ['src/log.js',         // logging system
              'src/DataStream.js',  // bit/byte/string read-write operations
              'src/box.js',         // base code for box parsing/writing
              'src/box-parse.js',   // box parsing code
              'src/meta.js',        // box code for meta-related box parsing
              'src/isofile.js',     // file level operations (read, write)
              'src/mp4box.js'       // application level operations (data append, sample extraction, segmentation, ...)
        ],
        dest: 'dist/<%= pkg.name %>.simple.js'
      },
      boxparser: {
        src: ['src/log.js',         // logging system
              'src/DataStream.js',  // bit/byte/string read-write operations
              'src/box.js',         // base code for box parsing/writing
              'src/box-parse.js',   // box parsing code
              'src/isofile.js',     // file level operations (read, write)
              'src/mp4box.js'       // application level operations (data append, sample extraction, segmentation, ...)
        ],
        dest: 'dist/boxparser.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n',
        sourceMap: true
      },
      all: {
        files: {
          'dist/<%= pkg.name %>.all.min.js': ['<%= concat.all.dest %>']
        }
      },
      simple: {
        files: {
          'dist/<%= pkg.name %>.simple.min.js': ['<%= concat.simple.dest %>']
        }
      },
      boxparser: {
        files: {
          'dist/boxparser.min.js': ['<%= concat.boxparser.dest %>']
        }
      }

    },
    qunit: {
		all: {
		  options: {
		    urls: [
		      'http://localhost:9000/test/qunit.html'
		    ]
		  }
		}
    },
    connect: {
	    server: {
	      options: {
	        port: 9000,
	        base: '.'
	      }
	    }
  	},
  	jshint: {
      files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js', '!test/lib/**/*.js' , '!test/mp4/**/*.js'],
      options: {
        // options here to override JSHint defaults
    	eqeqeq: false,
    	asi: true,
    	loopfunc: true,
    	eqnull: true,
        globals: {
        }
      }
    },
    watch: {
      files: ['<%= jshint.files %>'],
      tasks: ['jshint', 'connect', 'qunit']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-connect');

  grunt.registerTask('test', ['connect', 'qunit']);

  grunt.registerTask('all', [ 'concat:all', 'uglify:all']);
  grunt.registerTask('simple', [ 'concat:simple', 'uglify:simple']);
  grunt.registerTask('boxparser', [ 'concat:boxparser', 'uglify:boxparser']);

  grunt.registerTask('default', [ 'jshint', 'all', 'simple', 'boxparser', 'test']);

};<commit_msg>add karma tasks, remove test from default<commit_after>module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';'
      },
      all: {
        src: ['src/log.js',         // logging system
              'src/DataStream.js',  // bit/byte/string read operations
              'src/DataStream-write.js',  // bit/byte/string write operations
              'src/DataStream-map.js',  // bit/byte/string other operations
              'src/descriptor.js',  // MPEG-4 descriptor parsing
              'src/box.js',         // base code for box parsing/writing
              'src/box-parse.js',   // box parsing code
              'src/box-write.js',   // box writing code
              'src/box-unpack.js',  // box code for sample manipulation
              'src/meta.js',        // box code for meta-related box parsing
              'src/text-mp4.js',  // text-based track manipulations
              'src/isofile.js',     // file level operations (read, write)
              'src/mp4box.js'       // application level operations (data append, sample extraction, segmentation, ...)
        ],
        dest: 'dist/<%= pkg.name %>.all.js'
      },
      simple: {
        src: ['src/log.js',         // logging system
              'src/DataStream.js',  // bit/byte/string read-write operations
              'src/box.js',         // base code for box parsing/writing
              'src/box-parse.js',   // box parsing code
              'src/meta.js',        // box code for meta-related box parsing
              'src/isofile.js',     // file level operations (read, write)
              'src/mp4box.js'       // application level operations (data append, sample extraction, segmentation, ...)
        ],
        dest: 'dist/<%= pkg.name %>.simple.js'
      },
      boxparser: {
        src: ['src/log.js',         // logging system
              'src/DataStream.js',  // bit/byte/string read-write operations
              'src/box.js',         // base code for box parsing/writing
              'src/box-parse.js',   // box parsing code
              'src/isofile.js',     // file level operations (read, write)
              'src/mp4box.js'       // application level operations (data append, sample extraction, segmentation, ...)
        ],
        dest: 'dist/boxparser.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n',
        sourceMap: true
      },
      all: {
        files: {
          'dist/<%= pkg.name %>.all.min.js': ['<%= concat.all.dest %>']
        }
      },
      simple: {
        files: {
          'dist/<%= pkg.name %>.simple.min.js': ['<%= concat.simple.dest %>']
        }
      },
      boxparser: {
        files: {
          'dist/boxparser.min.js': ['<%= concat.boxparser.dest %>']
        }
      }

    },
    qunit: {
		all: {
		  options: {
		    urls: [
		      'http://localhost:9000/test/qunit.html'
		    ]
		  }
		}
    },
    connect: {
	    server: {
	      options: {
	        port: 9000,
	        base: '.'
	      }
	    }
  	},
  	jshint: {
      files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js', '!test/lib/**/*.js' , '!test/mp4/**/*.js'],
      options: {
        // options here to override JSHint defaults
    	eqeqeq: false,
    	asi: true,
    	loopfunc: true,
    	eqnull: true,
        globals: {
        }
      }
    },
    watch: {
      files: ['<%= jshint.files %>'],
      tasks: ['jshint', 'connect', 'qunit']
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js'
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-karma');

  grunt.registerTask('test', ['connect', 'qunit']);

  grunt.registerTask('all', [ 'concat:all', 'uglify:all']);
  grunt.registerTask('simple', [ 'concat:simple', 'uglify:simple']);
  grunt.registerTask('boxparser', [ 'concat:boxparser', 'uglify:boxparser']);

  grunt.registerTask('default', [ 'jshint', 'all', 'simple', 'boxparser']);

};<|endoftext|>


<commit_before>module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Task configuration.
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: {
        src: ['Gruntfile.js', 'index.js', 'example/**/*.js', 'models/**/*.js', 'public/**/*.js', 'routes/**/*.js', 'tests/**/*.js']
      },
      ci: {
        options: {
          force: true,
          reporter: 'checkstyle',
          reporterOutput: 'jshint-result.xml'
        },
        src: '<%= jshint.all.src %>'
      }
    },
    vows: {
      all: {
        options: {
          reporter: 'spec'
        },
        src: ['tests/**/*.js']
      }
    },
    watch: {
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile']
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-vows');

  // Tasks
  grunt.registerTask('test', ['vows:all']);
  // Default task.
  grunt.registerTask('default', ['jshint', 'test']);

};
<commit_msg>chore(gruntfile): add grunt test<commit_after>module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Task configuration.
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: {
        src: ['Gruntfile.js', 'index.js', 'example/**/*.js', 'models/**/*.js', 'public/**/*.js', 'routes/**/*.js', 'tests/**/*.js']
      },
      ci: {
        options: {
          force: true,
          reporter: 'checkstyle',
          reporterOutput: 'jshint-result.xml'
        },
        src: '<%= jshint.all.src %>'
      }
    },
    mochacov: {
      all: {
        options: {
          reporter: 'spec',
          require: ['should'],
        },
        src: ['test/**/*.js'],
      }
    },
    watch: {
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile']
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-mocha-cov');

  // Tasks
  grunt.registerTask('test', ['mochacov']);
  // Default task.
  grunt.registerTask('default', ['jshint', 'test']);

};
<|endoftext|>


<commit_before>var this$1=this,HTMLLinkElement=function(){function t(){}return t.onload=function(t){var e=t.target["import"].querySelector("template"),n=function(t){var n=e.content.cloneNode(!0);n.slots=Array.from(n.querySelectorAll("slot")),t.slots=Array.from(t.querySelectorAll("[slot]")),t.slots.map(function(t){n.slots.filter(function(e){return e.getAttribute("name")===t.getAttribute("slot")}).map(function(e){return e.parentNode.replaceChild(t,e)})}),t.innerHTML="",t.append(n)};Array.from(document.getElementsByTagName(this)).map(n)},t}(),TokenList=function(t){var e=this,n=function(t){return t.text=t.textContent,t},r=function(t){return t.textContent.match(/{(\w+|#)}/g).map(o).map(i(t))},o=function(t){return t.match(/(\w+|#)/g)[0]},i=function(t){return function(n){return(e[n]=e[n]||[])&&e[n].push(t)}};this.sift(t).map(n).map(r)};TokenList.prototype.sift=function(t){for(var e=[],n=function(t){return t.nodeType===Node.TEXT_NODE?r(t)&&NodeFilter.FILTER_ACCEPT:o(t.attributes)&&NodeFilter.FILTER_REJECT},r=function(t){return t.nodeType===Node.TEXT_NODE&&/{(\w+|#)}/.test(t.textContent)},o=function(t){return Array.from(t||[]).filter(function(t){return/{(\w+|#)}/g.test(t.textContent)}).map(function(t){return e.push(t)})},i=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,n);t=i.nextNode();)e.push(t);return e},TokenList.prototype.bind=function(t){var e=this,n=function(t){return e[t].map(function(t){return t.textContent=t.text})&&t},r=function(t){return e[t].map(o(t))},o=function(e){return function(n){return n.textContent=n.textContent.replace("{"+e+"}",t[e])}};return Object.keys(this).map(n).map(r),this};var Template=function(t){function e(t){var e=this;this.dependents=this.dependents||[],t=Array.isArray(t)?t:[t];for(var n=void 0,r=[];n=this.dependents.pop();)n.remove();return t.forEach(function(t,n){var o=e.cloneNode(!0),i=new TokenList(o.content);t="object"==typeof t?t:{self:t},t["#"]=n,i.bind(t),r.push(o.content)}),r.map(function(t){(e=this.dependents).push.apply(e,t.childNodes);var e},this)(o=this).after.apply(o,r),this;var o}return void 0===t&&(t="snuggsi"),Object.assign(document.querySelector("template[name="+t+"]"),{bind:e})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.listen=function(t,e){void 0===e&&(e=this$1[t]),this.addEventListener(t,e)},e}(t)},ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={tokens:{}};return e.prototype.selectAll=function(t){return this.querySelectorAll(t)},e.prototype.select=function(t){return this.selectAll(t)[0]},n.tokens.get=function(){return this._tokens=this._tokens||new TokenList(this)},Object.defineProperties(e.prototype,n),e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.register=function(e){var n=this;void 0===e&&(e=function(t){return/^on/.exec(t)});var r=":not(script):not(template):not(style):not(link)",o=Array.from(this.querySelectorAll(r)),i=function(t){return Array.from(t.attributes).map(function(t){return t.name}).filter(e).length>0},u=function(e,r){return void 0===r&&(r=(/{\s*(\w+)\s*}/.exec(e)||[])[1]),r&&t[r].bind(n)||e||null},c=function(){return function(t){return Array.from(t.attributes).map(function(t){return t.name}).filter(e).filter(function(t){return void 0!==n[t]}).map(p(t))}},p=function(t){return function(e){t[e]=u(t[e])}},s=function(e){return!n[e]&&(n[e]=t[e].bind(n))};return void[this].concat(o).filter(i).map(c(this)),Object.getOwnPropertyNames(t).filter(e).map(s),this},e}(t)},ElementPrototype=window.Element.prototype,Element=function(t,e){void 0===e&&(e=window.customElements),t=t[0];var n=document.querySelector("link#"+t+"[rel=import], link[href*="+t+"][rel=import]");return n&&(n.onload=HTMLLinkElement.onload.bind(t)),function(n){var r=this===window?{}:this,o=function(t){function e(){t.call(this),this.context=r,t.prototype.initialize&&t.prototype.initialize.call(this)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.render=function(){this.tokens.bind(this),void function(t){var e=this,n=function(t){var n=t.getAttribute("name");void new Template(n).bind(e[n])};t.map(n)}.call(this,Array.from(this.selectAll("template[name]"))),this.register(),this.onready&&this.onready()},e.prototype.connectedCallback=function(){t.prototype.constructor.onconnect&&t.prototype.constructor.onconnect(),this.render()},e}(EventTarget(ParentNode(GlobalEventHandlers(n))));return e.define(t,o),e.get(t)}};Element.prototype=ElementPrototype;<commit_msg>:muscle: bump distribution for dist/snuggsi.min.js<commit_after>var this$1=this,HTMLLinkElement=function(){function t(){}return t.onload=function(t){var e=t.target["import"].querySelector("template"),n=function(t){var n=this,r=e.attributes,o=e.content.cloneNode(!0),i=function(t){return n.setAttribute(t.name,t.value)};Array.from(r).map(i),o.slots=Array.from(o.querySelectorAll("slot")),t.slots=Array.from(t.querySelectorAll("[slot]")),t.slots.map(function(t){o.slots.filter(function(e){return e.getAttribute("name")===t.getAttribute("slot")}).map(function(e){return e.parentNode.replaceChild(t,e)})}),t.innerHTML="",t.append(o)};Array.from(document.getElementsByTagName(this.tagName.toLowerCase())).map(n,this)},t}(),TokenList=function(t){var e=this,n=function(t){return t.text=t.textContent,t},r=function(t){return t.textContent.match(/{(\w+|#)}/g).map(o).map(i(t))},o=function(t){return t.match(/(\w+|#)/g)[0]},i=function(t){return function(n){return(e[n]=e[n]||[])&&e[n].push(t)}};this.sift(t).map(n).map(r)};TokenList.prototype.sift=function(t){for(var e=[],n=function(t){return t.nodeType===Node.TEXT_NODE?r(t)&&NodeFilter.FILTER_ACCEPT:o(t.attributes)&&NodeFilter.FILTER_REJECT},r=function(t){return t.nodeType===Node.TEXT_NODE&&/{(\w+|#)}/.test(t.textContent)},o=function(t){return Array.from(t||[]).filter(function(t){return/{(\w+|#)}/g.test(t.textContent)}).map(function(t){return e.push(t)})},i=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,n);t=i.nextNode();)e.push(t);return e},TokenList.prototype.bind=function(t){var e=this,n=function(t){return e[t].map(function(t){return t.textContent=t.text})&&t},r=function(t){return e[t].map(o(t))},o=function(e){return function(n){return n.textContent=n.textContent.replace("{"+e+"}",t[e])}};return Object.keys(this).map(n).map(r),this};var Template=function(t){function e(t){var e=this;this.dependents=this.dependents||[],t=Array.isArray(t)?t:[t];for(var n=void 0,r=[];n=this.dependents.pop();)n.remove();return t.forEach(function(t,n){var o=e.cloneNode(!0),i=new TokenList(o.content);t="object"==typeof t?t:{self:t},t["#"]=n,i.bind(t),r.push(o.content)}),r.map(function(t){(e=this.dependents).push.apply(e,t.childNodes);var e},this)(o=this).after.apply(o,r),this;var o}return void 0===t&&(t="snuggsi"),Object.assign(document.querySelector("template[name="+t+"]"),{bind:e})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.listen=function(t,e){void 0===e&&(e=this$1[t]),this.addEventListener(t,e)},e}(t)},ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={tokens:{}};return e.prototype.selectAll=function(t){return this.querySelectorAll(t)},e.prototype.select=function(t){return this.selectAll(t)[0]},n.tokens.get=function(){return this._tokens=this._tokens||new TokenList(this)},Object.defineProperties(e.prototype,n),e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.register=function(e){var n=this;void 0===e&&(e=function(t){return/^on/.exec(t)});var r=":not(script):not(template):not(style):not(link)",o=Array.from(this.querySelectorAll(r)),i=function(t){return Array.from(t.attributes).map(function(t){return t.name}).filter(e).length>0},u=function(e,r){return void 0===r&&(r=(/{\s*(\w+)\s*}/.exec(e)||[])[1]),r&&t[r].bind(n)||e||null},c=function(){return function(t){return Array.from(t.attributes).map(function(t){return t.name}).filter(e).filter(function(t){return void 0!==n[t]}).map(s(t))}},s=function(t){return function(e){t[e]=u(t[e])}},p=function(e){return!n[e]&&(n[e]=t[e].bind(n))};return void[this].concat(o).filter(i).map(c(this)),Object.getOwnPropertyNames(t).filter(e).map(p),this},e}(t)},ElementPrototype=window.Element.prototype,Element=function(t,e){void 0===e&&(e=window.customElements),t=t[0];var n=document.querySelector("link#"+t+"[rel=import], link[href*="+t+"][rel=import]");return function(r){var o=this===window?{}:this,i=function(t){function e(){t.call(this),this.context=o,t.prototype.initialize&&t.prototype.initialize.call(this)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.render=function(){this.tokens.bind(this),void function(t){var e=this,n=function(t){var n=t.getAttribute("name");void new Template(n).bind(e[n])};t.map(n)}.call(this,Array.from(this.selectAll("template[name]"))),this.register(),this.onready&&this.onready()},e.prototype.connectedCallback=function(){n&&(n.onload=HTMLLinkElement.onload.bind(this)),t.prototype.constructor.onconnect&&t.prototype.constructor.onconnect(),this.render()},e}(EventTarget(ParentNode(GlobalEventHandlers(r))));return e.define(t,i),e.get(t)}};Element.prototype=ElementPrototype;<|endoftext|>


<commit_before>
//
// Copyright © 2016-present Kary Foundation, Inc. All Rights Reserved
//   Author: Pouya Kary <k@karyfoundation.org>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

//
// ─── IMPORTS ────────────────────────────────────────────────────────────────────
//

    const argv                  = require('yargs').argv
    const darwinInfoPlistBase   = require('./build/darwin-info-base.json')
    const exec                  = require('child_process').exec
    const fs                    = require('fs-extra')
    const gulp                  = require('gulp')
    const less                  = require('less')
    const mv                    = require('mv')
    const packageJson           = require('./package.json')
    const path                  = require('path')
    const plist                 = require('plist')
    const request               = require('request')
    const ugly                  = require('gulp-uglify')
    const util                  = require('util')

//
// ─── CONSTANTS ──────────────────────────────────────────────────────────────────
//

    const version = "v1.0"
    const resultDirPath = '_compiled'
    const nightlyName = 'Orchestra Nightly'

//
// ─── TOOLS ──────────────────────────────────────────────────────────────────────
//

    /** Run shell commands easy! */
    async function shell ( command , callback ) {
        return new Promise(( resolve, reject ) => {
            exec( command, err => {
                if ( err )
                    reject( err )
                else
                    resolve( )
            })
        })
    }

//
// ─── COPY DIR FILES ─────────────────────────────────────────────────────────────
//

    /** Copy to binary from dir */
    function copyToBinaryFromDir ( dir, subfolder ) {
        fs.readdir( dir , ( err , files ) => {
            // if error
            if ( err )
                console.log(`Could not get files from directory ${ dir }`)

            // if right
            files.forEach( name => {
                let dest
                if ( !( subfolder === undefined || subfolder === '' || subfolder === null ) )
                    dest = path.join( resultDirPath , subfolder , name )
                else
                    dest = path.join( resultDirPath , name )

                if ( !( name.endsWith('.map') || name.endsWith('.d.ts') ) )
                    copyFile(
                        getLocalPath( path.join( dir , name ) ),
                        getLocalPath( dest )
                    )})})}

//
// ─── COPY SINGLE FILE ───────────────────────────────────────────────────────────
//

    /** Copy file `A` to `B` */
    function copyFile ( A, B ) {
        if ( /\.DS_Store/.test( A ) ) {
            return
        }
        fs.copy( A, B, err => {
            if ( err ) {
                console.log(`Could not copy file ${ A }`)
            }
        })
    }

//
// ─── GET LOCAL PATH ─────────────────────────────────────────────────────────────
//

    /** Get Local Path in the current directory */
    function getLocalPath ( address ) {
        return path.join( __dirname , address )
    }

//
// ─── COPY FILES ─────────────────────────────────────────────────────────────────
//

    /** Copies static resource files into the result directory */
    gulp.task( 'copyResourceFiles', callback => {

        function copyNodeModules ( handle ) {
            let address = path.join( 'node_modules', handle )
            copyToBinaryFromDir( address, address )
        }

        // codes
        copyToBinaryFromDir( 'view' )
        copyToBinaryFromDir( 'editor' )
        copyToBinaryFromDir( 'libs' )
        copyToBinaryFromDir( 'windows' )
        copyToBinaryFromDir( 'winserver' )

        // design files
        copyToBinaryFromDir( 'resources' )
        copyToBinaryFromDir( 'designs/icon/file-icon-darwin/icns' )

        // node modules
        copyNodeModules( 'concerto-compiler' )
        copyNodeModules( 'messenger' )
        copyNodeModules( 'regulex' )
        copyNodeModules( 'amdefine' )
        copyNodeModules( 'monaco-editor/min/vs' )
        copyNodeModules( 'regexpu-core' )
        copyNodeModules( 'regexpu' )
        copyNodeModules( 'regjsgen' )
        copyNodeModules( 'regjsparser' )
        copyNodeModules( 'regenerate' )
        copyNodeModules( 'unicode-match-property-ecmascript' )
        copyNodeModules( 'unicode-canonical-property-names-ecmascript' )
        copyNodeModules( 'unicode-property-aliases-ecmascript' )
        copyNodeModules( 'jsesc' )
        copyNodeModules( 'recast' )
        copyNodeModules( 'unicode-match-property-value-ecmascript' )
        copyNodeModules( 'ast-types' )
        copyNodeModules( 'source-map' )
        copyNodeModules( 'esprima' )
        copyNodeModules( 'private' )

        // package
        copyFile(
            getLocalPath( 'package.json' ),
            getLocalPath( path.join( resultDirPath , 'package.json' ) )
        )

        callback()
    })

//
// ─── GETTING COMMIT COUNT ───────────────────────────────────────────────────────
//

    gulp.task( 'get-commit-counts', callback => {
        const commitCountFilePath = `./${resultDirPath}/about/commit-count.txt`
        const githubOrchestraRepositoryAPI =
            'https://api.github.com/repos/karyfoundation/orchestra/stats/contributors'

        try {
            new Promise (( resolve, reject ) => {
                const rejectHandler = ( ) =>
                    reject('Could not connect to GitHub')

                const options = {
                    url: githubOrchestraRepositoryAPI,
                    method: 'GET',
                    headers: {
                        'User-Agent':   'Super Agent/0.0.1',
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                }

                request( options, ( error, response, body ) => {
                    if ( !error && response.statusCode == 200 ) {
                        try {
                            const data = JSON.parse( body )[ 0 ].total.toString( )
                            resolve( data )
                        } catch ( parseError ) {
                            rejectHandler( )
                        }
                    } else {
                        rejectHandler( )
                    }
                })
            })
            .then( GitHubCommitCount => {
                fs.writeFileSync( commitCountFilePath, GitHubCommitCount )
                callback( )
            })
            .catch( e => {
                throw e
            })

        } catch ( error ) {
            try {
                shell( 'git rev-list --all --count > ' + commitCountFilePath )
                callback( )

            } catch ( error2 ) {
                callback('Could not save latest commits count')
            }
        }
    })

//
// ─── SHEETS ─────────────────────────────────────────────────────────────────────
//

    /** Compiles the Less style sheets */
    gulp.task( 'sheets', callback => {
        try {
            let lessSourceCode = fs.readFileSync(
                path.join( __dirname, 'sheets', 'ui.less' ), 'utf8' )

            less.render( lessSourceCode, ( err, output ) => {
                if ( err ) {
                    console.log(`Less failure: ${ err }`); return
                }
                fs.writeFile(
                    path.join( __dirname, '_compiled/style.css' ),
                    output.css,
                    error => {
                        if ( error ) {
                            console.log('could not store the less file')
                        } else {
                            callback()
                        }
                    }
                )
            })
        } catch ( err ) {
            console.log('Compiling less failed ' + err )
        }
    })

//
// ─── ELECTRON PACKER ────────────────────────────────────────────────────────────
//

    async function packOrchestraForMac ( ) {
        return new Promise(( resolve, reject ) => {
            try {
                // assets
                const iconFile = (( packageJson.productName !== nightlyName )
                    ? './designs/icon/icns/icon.icns'
                    : './designs/icon-nightly/icns/icon.icns'
                )

                // build script
                const packBashScript = (
                    'electron-packager' +
                        ' _compiled "' + packageJson.productName + '"' +
                        ' --platform=darwin --arch=x64' +
                        ' --overwrite=true' +
                        ' --app-copyright="Copyright 2016-present, Kary Foundation, Inc. All rights reserved."' +
                        ' --app-version="' + packageJson.version + '"' +
                        ' --icon=' + iconFile +
                        ' --name="' + packageJson.productName + '"'+
                        ' --out=_release'
                )

                // building
                const execPromise = shell( packBashScript )

                // after mac build
                execPromise.then(( ) => {
                    updateDarwinInfoPlistFile( )
                    resolve( )
                })

                execPromise.catch( error => {
                    reject( error )
                })
            } catch ( buildError ) {
                reject( buildError )
            }
        })
    }

    function updateDarwinInfoPlistFile ( ) {
        // data
        const plistFilePath = (( packageJson.productName !== nightlyName )
            ? '_release/Orchestra-darwin-x64/Orchestra.app/Contents/Info.plist'
            : '_release/Orchestra Nightly-darwin-x64/Orchestra.app/Contents/Info.plist'
        )

        // loading the info file
        const plistFileString =
            fs.readFileSync( plistFilePath, 'utf8' )
        const infoJSON =
            plist.parse( plistFileString )

        // adding stuff to the plist data
        const newInfoJSON =
            Object.assign( infoJSON, darwinInfoPlistBase )

        // making new plist info
        const newPlistFileString =
            plist.build( newInfoJSON )

        // done, now saving it back
        fs.writeFileSync( plistFilePath, newPlistFileString )
    }

//
// ─── PACK ───────────────────────────────────────────────────────────────────────
//

    gulp.task( 'pack-orchestra',
        [ 'copyResourceFiles', /* 'get-commit-counts' ,*/ 'sheets' ], callback => {

        if ( argv.pack ) {
            packOrchestraForMac( )
        }

        else if ( argv.debug ) {
            shell('npm run electron')
        }
    })

//
// ─── AFTER PACK ─────────────────────────────────────────────────────────────────
//

    gulp.task( 'build-orchestra', [ 'pack-orchestra' ], ( ) => {

    })

//
// ─── MAIN ───────────────────────────────────────────────────────────────────────
//

    /** Where everything starts */
    gulp.task( 'default', [ 'build-orchestra' ])

// ────────────────────────────────────────────────────────────────────────────────
<commit_msg>lots and lots of formatting<commit_after>
//
// Copyright © 2016-present Kary Foundation, Inc. All Rights Reserved
//   Author: Pouya Kary <k@karyfoundation.org>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

//
// ─── IMPORTS ────────────────────────────────────────────────────────────────────
//

    const argv                  = require('yargs').argv
    const darwinInfoPlistBase   = require('./build/darwin-info-base.json')
    const exec                  = require('child_process').exec
    const fs                    = require('fs-extra')
    const gulp                  = require('gulp')
    const less                  = require('less')
    const mv                    = require('mv')
    const packageJson           = require('./package.json')
    const path                  = require('path')
    const plist                 = require('plist')
    const request               = require('request')
    const ugly                  = require('gulp-uglify')
    const util                  = require('util')

//
// ─── CONSTANTS ──────────────────────────────────────────────────────────────────
//

    const version = "v1.0"
    const resultDirPath = '_compiled'
    const nightlyName = 'Orchestra Nightly'

//
// ─── TOOLS ──────────────────────────────────────────────────────────────────────
//

    /** Run shell commands easy! */
    async function shell ( command , callback ) {
        return new Promise(( resolve, reject ) => {
            exec( command, err => {
                if ( err )
                    reject( err )
                else
                    resolve( )
            })
        })
    }

//
// ─── COPY DIR FILES ─────────────────────────────────────────────────────────────
//

    /** Copy to binary from dir */
    function copyToBinaryFromDir ( dir, subfolder ) {
        fs.readdir( dir , ( err , files ) => {
            // if error
            if ( err )
                console.log(`Could not get files from directory ${ dir }`)

            // if right
            files.forEach( name => {
                let dest
                if ( !( subfolder === undefined || subfolder === '' || subfolder === null ) )
                    dest = path.join( resultDirPath , subfolder , name )
                else
                    dest = path.join( resultDirPath , name )

                if ( !( name.endsWith('.map') || name.endsWith('.d.ts') ) )
                    copyFile(
                        getLocalPath( path.join( dir , name ) ),
                        getLocalPath( dest )
                    )})})}

//
// ─── COPY SINGLE FILE ───────────────────────────────────────────────────────────
//

    /** Copy file `A` to `B` */
    function copyFile ( A, B ) {
        if ( /\.DS_Store/.test( A ) ) {
            return
        }
        fs.copy( A, B, err => {
            if ( err ) {
                console.log(`Could not copy file ${ A }`)
            }
        })
    }

//
// ─── GET LOCAL PATH ─────────────────────────────────────────────────────────────
//

    /** Get Local Path in the current directory */
    function getLocalPath ( address ) {
        return path.join( __dirname , address )
    }

//
// ─── COPY FILES ─────────────────────────────────────────────────────────────────
//

    /** Copies static resource files into the result directory */
    gulp.task( 'copyResourceFiles', callback => {

        function copyNodeModules ( handle ) {
            let address = path.join( 'node_modules', handle )
            copyToBinaryFromDir( address, address )
        }

        // codes
        copyToBinaryFromDir( 'view' )
        copyToBinaryFromDir( 'editor' )
        copyToBinaryFromDir( 'libs' )
        copyToBinaryFromDir( 'windows' )
        copyToBinaryFromDir( 'winserver' )

        // design files
        copyToBinaryFromDir( 'resources' )
        copyToBinaryFromDir( 'designs/icon/file-icon-darwin/icns' )

        // node modules
        copyNodeModules( 'concerto-compiler' )
        copyNodeModules( 'messenger' )
        copyNodeModules( 'regulex' )
        copyNodeModules( 'amdefine' )
        copyNodeModules( 'monaco-editor/min/vs' )
        copyNodeModules( 'regexpu-core' )
        copyNodeModules( 'regexpu' )
        copyNodeModules( 'regjsgen' )
        copyNodeModules( 'regjsparser' )
        copyNodeModules( 'regenerate' )
        copyNodeModules( 'unicode-match-property-ecmascript' )
        copyNodeModules( 'unicode-canonical-property-names-ecmascript' )
        copyNodeModules( 'unicode-property-aliases-ecmascript' )
        copyNodeModules( 'jsesc' )
        copyNodeModules( 'recast' )
        copyNodeModules( 'unicode-match-property-value-ecmascript' )
        copyNodeModules( 'ast-types' )
        copyNodeModules( 'source-map' )
        copyNodeModules( 'esprima' )
        copyNodeModules( 'private' )

        // package
        copyFile(
            getLocalPath( 'package.json' ),
            getLocalPath( path.join( resultDirPath , 'package.json' ) )
        )

        callback()
    })

//
// ─── GETTING COMMIT COUNT ───────────────────────────────────────────────────────
//

    gulp.task( 'get-commit-counts', callback => {
        const commitCountFilePath = `./${resultDirPath}/about/commit-count.txt`
        const githubOrchestraRepositoryAPI =
            'https://api.github.com/repos/karyfoundation/orchestra/stats/contributors'

        try {
            new Promise (( resolve, reject ) => {
                const rejectHandler = ( ) =>
                    reject('Could not connect to GitHub')

                const options = {
                    url: githubOrchestraRepositoryAPI,
                    method: 'GET',
                    headers: {
                        'User-Agent':   'Super Agent/0.0.1',
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                }

                request( options, ( error, response, body ) => {
                    if ( !error && response.statusCode == 200 ) {
                        try {
                            const data = JSON.parse( body )[ 0 ].total.toString( )
                            resolve( data )
                        } catch ( parseError ) {
                            rejectHandler( )
                        }
                    } else {
                        rejectHandler( )
                    }
                })
            })
            .then( GitHubCommitCount => {
                fs.writeFileSync( commitCountFilePath, GitHubCommitCount )
                callback( )
            })
            .catch( e => {
                throw e
            })

        } catch ( error ) {
            try {
                shell( 'git rev-list --all --count > ' + commitCountFilePath )
                callback( )

            } catch ( error2 ) {
                callback('Could not save latest commits count')
            }
        }
    })

//
// ─── SHEETS ─────────────────────────────────────────────────────────────────────
//

    /** Compiles the Less style sheets */
    gulp.task( 'sheets', callback => {
        try {
            let lessSourceCode = fs.readFileSync(
                path.join( __dirname, 'sheets', 'ui.less' ), 'utf8' )

            less.render( lessSourceCode, ( err, output ) => {
                if ( err ) {
                    console.log(`Less failure: ${ err }`); return
                }
                fs.writeFile(
                    path.join( __dirname, '_compiled/style.css' ),
                    output.css,
                    error => {
                        if ( error ) {
                            console.log('could not store the less file')
                        } else {
                            callback()
                        }
                    }
                )
            })
        } catch ( err ) {
            console.log('Compiling less failed ' + err )
        }
    })

//
// ─── ELECTRON PACKER ────────────────────────────────────────────────────────────
//

    async function packOrchestraForDarwin ( ) {
        const iconFile =
            (( packageJson.productName !== nightlyName )
                ? './designs/icon/icns/icon.icns'
                : './designs/icon-nightly/icns/icon.icns'
                )

        // build script
        const packBashScript =
            ( 'electron-packager'
            + ' _compiled "' + packageJson.productName + '"'
            + ' --platform=darwin --arch=x64'
            + ' --overwrite=true'
            + ' --app-copyright="Copyright 2016-present, Kary Foundation, Inc. All rights reserved."'
            + ' --app-version="' + packageJson.version + '"'
            + ' --icon=' + iconFile
            + ' --name="' + packageJson.productName + '"'
            + ' --out=_release'
            )

        // building
        await shell( packBashScript )
        updateDarwinInfoPlistFile( )
    }

    function updateDarwinInfoPlistFile ( ) {
        // data
        const plistFilePath = (( packageJson.productName !== nightlyName )
            ? '_release/Orchestra-darwin-x64/Orchestra.app/Contents/Info.plist'
            : '_release/Orchestra Nightly-darwin-x64/Orchestra.app/Contents/Info.plist'
        )

        // loading the info file
        const plistFileString =
            fs.readFileSync( plistFilePath, 'utf8' )
        const infoJSON =
            plist.parse( plistFileString )

        // adding stuff to the plist data
        const newInfoJSON =
            Object.assign( infoJSON, darwinInfoPlistBase )

        // making new plist info
        const newPlistFileString =
            plist.build( newInfoJSON )

        // done, now saving it back
        fs.writeFileSync( plistFilePath, newPlistFileString )
    }

//
// ─── PACK FOR LINUX ─────────────────────────────────────────────────────────────
//

    async function packOrchestraForLinux ( ) {
        // to be continued...
    }

//
// ─── PACK FOR WINDOWS ───────────────────────────────────────────────────────────
//

    async function packOrchestraForWindows ( ) {
        // to be continued...
    }

//
// ─── PACK ───────────────────────────────────────────────────────────────────────
//

    gulp.task( 'pack-orchestra', [ 'copyResourceFiles', 'sheets' ], callback => {
        if ( argv.pack )
            buildAllPlatforms( callback )
        else if ( argv.debug )
            runElectron( callback )
    })

    function runElectron ( callback ) {
        shell('npm run electron')
            .then(( ) => callback )
            .catch( error => callback( error ) )
    }

    function buildAllPlatforms ( callback ) {
        const buildPromises = [
            packOrchestraForDarwin,
            packOrchestraForLinux,
            packOrchestraForWindows
        ]

        Promise.all( buildPromises )
            .then(( ) => callback )
            .catch( error => callback( error ) )
    }

//
// ─── AFTER PACK ─────────────────────────────────────────────────────────────────
//

    gulp.task( 'build-orchestra', [ 'pack-orchestra' ], ( ) => {

    })

//
// ─── MAIN ───────────────────────────────────────────────────────────────────────
//

    /** Where everything starts */
    gulp.task( 'default', [ 'build-orchestra' ])

// ────────────────────────────────────────────────────────────────────────────────
<|endoftext|>


<commit_before>(function($, window) {

	/**
	 * constructor
	 */
	window.Sprite = function (sprite_data)
	{

		this.position = null;
		this.halfWidth = null;
		this.halfHeight = null;
		this.animation_class = null;
		this.moving = false;
		this.manager = null;
		this.move_timer_id = null;

		this.properties = {
			x: sprite_data.x,
			y: sprite_data.y,
			facing: sprite_data.facing,
			start: 0,
			sprite_data: sprite_data,
			object: null
		};

	};

	/**
	* update sprite
	*
	* @return {Sprite}
	*/
	window.Sprite.prototype.update = function() {

		this.properties.start += this.moving ? 2 : 1;
		if (this.properties.start >= this.properties.sprite_data.maxFrame) {
			this.properties.start = this.properties.sprite_data.minFrame;
		}

		this.position = $(this.properties.object).position();
		this.setAnimationClass();

		return this;
	};

	/**
	 * check if sprite is in collision with another sprite
	 *
	 * @param {Sprite} another_sprite
	 * @return {boolean}
	 */
	window.Sprite.prototype.collides = function(another_sprite) {

		if (another_sprite === this) {
			return false;
		}

		return !(this.position.left > (another_sprite.position.left + another_sprite.halfWidth*2)
			|| (this.position.left + this.halfWidth*2) < another_sprite.position.left
			|| this.position.top > (another_sprite.position.top + another_sprite.halfHeight*2)
			|| (this.position.top + this.halfHeight*2) < another_sprite.position.top
		);
	};

	/**
	 * stop moving
	 *
	 * @return {Sprite}
	 */
	window.Sprite.prototype.stop = function() {
		this.moving = false;
		$(this.properties.object).stop(true, false);

		return this;
	};

	/**
	* initialite sprite movement to given coordinates
	*
	* @param {integer} x
	* @param {integer} y
	* @param {integer} speed_factor
	* @return {Sprite}
	*/
	window.Sprite.prototype.move = function(x, y, speed_factor) {

		var self = this;

		if ((typeof(x) == 'undefined' && typeof(y) == 'undefined') || (!x && x !== 0 && !y && y !== 0)) {
			// no move
			return this;
		}

		if (!x && x !== 0) {
			x = this.position.left + this.halfWidth;
		}

		if (!y && y !== 0) {
			y = this.position.top + this.halfHeight;
		}

		// source center
		var position_x = this.position.left + this.halfWidth,
			position_y = this.position.top + this.halfHeight,
			position_x2 = x - this.halfWidth,
			position_y2 = y - this.halfHeight,
			angle = calculateFacingAngle(x, y, position_x, position_y),
			animation_duration = 4000 / speed_factor,
			distance = Math.sqrt((position_x2-position_x)*(position_x2-position_x)+(position_y2-position_y)*(position_y2-position_y));

		if (Math.abs(distance) < 200) {
			animation_duration = animation_duration / 2;
		}

		window.clearTimeout(this.move_timer_id);

		this.move_timer_id = window.setTimeout(function(){
			self.properties.facing = calculateFacing(angle);

			self.stop();
			self.moving = true;
			$(self.properties.object).animate({
				top : position_y2 + 'px',
				left : position_x2 + 'px'
			}, {
				duration: animation_duration,
				queue: true,
				easing: 'swing',
				step: function(now, fx) {
				},
				complete: function(now, fx) {
					self.moving = false;
					window.clearTimeout(self.move_timer_id);
				}
			});
		}, 300);

		return this;

	};

	window.Sprite.prototype.setManager = function(my_manager) {

		this.manager = my_manager;

	};

	window.Sprite.prototype.init = function(target) {

		return this.initView(target)
			.registerEvents()
			.update();

	};

	/**
	* set player status of sprite
	*
	* @return {Sprite}
	*/
	window.Sprite.prototype.setPlayer = function(isPlayer) {

		this.properties.sprite_data.player = isPlayer;

		if (isPlayer) {
			this.properties.object.addClass('player');
		} else {
			this.properties.object.removeClass('player');
		}

		return this;

	};

	/**
	* get player status of sprite
	*
	* @return {boolean}
	*/
	window.Sprite.prototype.isPlayer = function() {

		return this.properties.sprite_data.player;

	};

	/**
	 * set collision state
	 *
	 * @param {boolean} has_collision
	 * @return Sprite
	 */
	window.Sprite.prototype.setCollision = function(has_collision) {
		if (has_collision) {
			this.properties.object.addClass('collision');
		} else {
			this.properties.object.removeClass('collision');
		}

		return this;
	};

	window.Sprite.prototype.hasCollision = function() {
		return this.properties.object.hasClass('collision');
	};

	window.Sprite.prototype.setAnimationClass = function() {

		this.properties.object.removeClass(this.animation_class);
		this.animation_class = this.properties.facing + '_' + pad(this.properties.start + '', 2);
		this.properties.object.addClass(this.animation_class);

		return this;
	};

	window.Sprite.prototype.initView = function(target) {

		this.properties.start = 0;

		this.properties.object = $('

')
			.appendTo($(target));

		$(this.properties.object).css({
			top: this.properties.y + 'px',
			left: this.properties.x + 'px',
			zIndex : this.properties.sprite_data.zIndex++
		});

		this.position = $(this.properties.object).position();
		this.halfWidth = $(this.properties.object).width() / 2;
		this.halfHeight = $(this.properties.object).height() / 2;

		this.setAnimationClass();

		return this;

	};

	window.Sprite.prototype.registerEvents = function() {

		var self = this;

		$(this.properties.object).on('move', function(eventObject, eventData) {
			if (self.properties.sprite_data.player || eventData.force) {
				self.move(eventData.x, eventData.y, eventData.speed);
			}
		});

		$(this.properties.object).on('click', function(eventObject) {
			self.manager.setPlayer(self);
			eventObject.stopPropagation();
		});

		return this;

	};

})(jQuery, window);<commit_msg>save last position before move<commit_after>(function($, window) {

	/**
	 * constructor
	 */
	window.Sprite = function (sprite_data)
	{

		this.position = null;
		this.halfWidth = null;
		this.halfHeight = null;
		this.animation_class = null;
		this.moving = false;
		this.manager = null;
		this.move_timer_id = null;
		this.last_position = null;

		this.properties = {
			x: sprite_data.x,
			y: sprite_data.y,
			facing: sprite_data.facing,
			start: 0,
			sprite_data: sprite_data,
			object: null
		};

	};

	/**
	* update sprite
	*
	* @return {Sprite}
	*/
	window.Sprite.prototype.update = function() {

		this.properties.start += this.moving ? 2 : 1;
		if (this.properties.start >= this.properties.sprite_data.maxFrame) {
			this.properties.start = this.properties.sprite_data.minFrame;
		}

		this.position = $(this.properties.object).position();
		this.setAnimationClass();

		return this;
	};

	/**
	 * check if sprite is in collision with another sprite
	 *
	 * @param {Sprite} another_sprite
	 * @return {boolean}
	 */
	window.Sprite.prototype.collides = function(another_sprite) {

		if (another_sprite === this) {
			return false;
		}

		return !(this.position.left > (another_sprite.position.left + another_sprite.halfWidth*2)
			|| (this.position.left + this.halfWidth*2) < another_sprite.position.left
			|| this.position.top > (another_sprite.position.top + another_sprite.halfHeight*2)
			|| (this.position.top + this.halfHeight*2) < another_sprite.position.top
		);
	};

	/**
	 * stop moving
	 *
	 * @return {Sprite}
	 */
	window.Sprite.prototype.stop = function() {
		this.moving = false;
		$(this.properties.object).stop(true, false);

		return this;
	};

	/**
	* initialite sprite movement to given coordinates
	*
	* @param {integer} x
	* @param {integer} y
	* @param {integer} speed_factor
	* @return {Sprite}
	*/
	window.Sprite.prototype.move = function(x, y, speed_factor) {

		var self = this;

		if ((typeof(x) == 'undefined' && typeof(y) == 'undefined') || (!x && x !== 0 && !y && y !== 0)) {
			// no move
			return this;
		}

		if (!x && x !== 0) {
			x = this.position.left + this.halfWidth;
		}

		if (!y && y !== 0) {
			y = this.position.top + this.halfHeight;
		}

		// source center
		var position_x = this.position.left + this.halfWidth,
			position_y = this.position.top + this.halfHeight,
			position_x2 = x - this.halfWidth,
			position_y2 = y - this.halfHeight,
			angle = calculateFacingAngle(x, y, position_x, position_y),
			animation_duration = 4000 / speed_factor,
			distance = Math.sqrt((position_x2-position_x)*(position_x2-position_x)+(position_y2-position_y)*(position_y2-position_y));

		if (Math.abs(distance) < 200) {
			animation_duration = animation_duration / 2;
		}

		window.clearTimeout(this.move_timer_id);

		this.move_timer_id = window.setTimeout(function(){
			self.properties.facing = calculateFacing(angle);

			self.stop();
			self.moving = true;
			self.last_position = {top: position_y, left: position_x};
			$(self.properties.object).animate({
				top : position_y2 + 'px',
				left : position_x2 + 'px'
			}, {
				duration: animation_duration,
				queue: true,
				easing: 'swing',
				step: function(now, fx) {
				},
				complete: function(now, fx) {
					self.moving = false;
					window.clearTimeout(self.move_timer_id);
				}
			});
		}, 300);

		return this;

	};

	window.Sprite.prototype.setManager = function(my_manager) {

		this.manager = my_manager;

	};

	window.Sprite.prototype.init = function(target) {

		return this.initView(target)
			.registerEvents()
			.update();

	};

	/**
	* set player status of sprite
	*
	* @return {Sprite}
	*/
	window.Sprite.prototype.setPlayer = function(isPlayer) {

		this.properties.sprite_data.player = isPlayer;

		if (isPlayer) {
			this.properties.object.addClass('player');
		} else {
			this.properties.object.removeClass('player');
		}

		return this;

	};

	/**
	* get player status of sprite
	*
	* @return {boolean}
	*/
	window.Sprite.prototype.isPlayer = function() {

		return this.properties.sprite_data.player;

	};

	/**
	 * set collision state
	 *
	 * @param {boolean} has_collision
	 * @return Sprite
	 */
	window.Sprite.prototype.setCollision = function(has_collision) {
		if (has_collision) {
			this.properties.object.addClass('collision');
		} else {
			this.properties.object.removeClass('collision');
		}

		return this;
	};

	window.Sprite.prototype.hasCollision = function() {
		return this.properties.object.hasClass('collision');
	};

	window.Sprite.prototype.setAnimationClass = function() {

		this.properties.object.removeClass(this.animation_class);
		this.animation_class = this.properties.facing + '_' + pad(this.properties.start + '', 2);
		this.properties.object.addClass(this.animation_class);

		return this;
	};

	window.Sprite.prototype.initView = function(target) {

		this.properties.start = 0;

		this.properties.object = $('

')
			.appendTo($(target));

		$(this.properties.object).css({
			top: this.properties.y + 'px',
			left: this.properties.x + 'px',
			zIndex : this.properties.sprite_data.zIndex++
		});

		this.position = $(this.properties.object).position();
		this.halfWidth = $(this.properties.object).width() / 2;
		this.halfHeight = $(this.properties.object).height() / 2;

		this.setAnimationClass();

		return this;

	};

	window.Sprite.prototype.registerEvents = function() {

		var self = this;

		$(this.properties.object).on('move', function(eventObject, eventData) {
			if (self.properties.sprite_data.player || eventData.force) {
				self.move(eventData.x, eventData.y, eventData.speed);
			}
		});

		$(this.properties.object).on('click', function(eventObject) {
			self.manager.setPlayer(self);
			eventObject.stopPropagation();
		});

		return this;

	};

})(jQuery, window);<|endoftext|>


<commit_before>var modulus = require('../modulus'),
    librarian = require('../common/api').librarian,
    userConfig = require('../common/api').userConfig,
    fs = require('fs'),
    ProgressBar = require('progress'),
    Progress = require('../util/progress'),
    Errors = require('../util/errors'),
    request = require('request'),
    http = require('http'),
    uploader = require('chunk-loader').Client,
    https = require('https');

http.globalAgent.maxSockets = Number.MAX_VALUE;
https.globalAgent.maxSockets = Number.MAX_VALUE;

//-----------------------------------------------------------------------------
var Project = function() {

};

//-----------------------------------------------------------------------------
Project.prototype.create = function(name, creatorId, callback) {
  librarian.project.create({
    name: name,
    creator: creatorId
  }, false, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.restart = function(projectId, callback) {
  librarian.project.restart(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Restarting [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.running) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.stop = function(projectId, callback) {
  librarian.project.stop(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Stopping [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.stopped) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.start = function(projectId, callback) {
  librarian.project.start(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Starting [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.running) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.find = function(opts, callback) {
  librarian.project.find(opts, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.saveVars = function(projectId, vars, callback) {
  librarian.project.saveVars(projectId, vars, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.deploy = function(projectId, file, callback) {
  var host = librarian._http._host;
  var port = librarian._http._port;
  var protocol = librarian._http._ssl ? 'https' : 'http';

  modulus.io.print('Uploading project...');
  var status = Project.status.uploading;

  // start checking for status changes
  // show progress for upload and inderminate progress for deploying
  var ubar = new ProgressBar('Upload progress [:bar] :percent', {
    complete: '=',
    incomplete: ' ',
    width: 20,
    total: 100
  });
  ubar.tick();

  var client = uploader.uploadFile(file,
    {
      beginProtocol: 'https',
      uploadProtocol: 'http',
      beginPort: '443',
      uploadPort: '80',
      host: host,
      port: port,
      debug: true,
      encrypted: true,
      tag: { projectId: projectId, authToken: userConfig.data.apiKey }
    }
  );

  client.on('progress', function(p) {
    ubar.tick(((p.sent / p.total) * 100) - ubar.curr);
  });

  client.on('error', function(err) {
    callback(err);
  });

  client.on('complete', function() {
    var dbar = new Progress.indeterminate('Deploying [:bar]');

    // check every second for project status change
    var projectStatus = function () {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {
        if(!err) {
          if(proj && proj.status) {
            if(proj.status.toLowerCase() !== status) {
              var newStatus = proj.status.toLowerCase();
              if(newStatus === Project.status.deploying) {
                status = newStatus;
                modulus.io.print('\nDeploying Project...');
                dbar.start();
              } else if(newStatus === Project.status.running && status !== Project.status.uploading) {
                dbar.stop();
                modulus.io.print(' ');
                return callback(null, proj.domain);
              }
            }
          }
        }

        if(status !== Project.status.running) {
          setTimeout(projectStatus, 1000);
        }
      });
    };
    projectStatus();
  });
};

/**
 * Gets the logs for the specified project id.
 * @param {string} projectId The ID of the project.
 * @param {function} callback Function invoked with log results.
 */
//-----------------------------------------------------------------------------
Project.prototype.getLogs = function(projectId, callback) {
  librarian.project.getLog(projectId, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.status = {
  uploading : 'uploading',
  deploying : 'deploying',
  running : 'running',
  stopped: 'stopped'
};

module.exports = new Project();<commit_msg>Removed debug flag.<commit_after>var modulus = require('../modulus'),
    librarian = require('../common/api').librarian,
    userConfig = require('../common/api').userConfig,
    fs = require('fs'),
    ProgressBar = require('progress'),
    Progress = require('../util/progress'),
    Errors = require('../util/errors'),
    request = require('request'),
    http = require('http'),
    uploader = require('chunk-loader').Client,
    https = require('https');

http.globalAgent.maxSockets = Number.MAX_VALUE;
https.globalAgent.maxSockets = Number.MAX_VALUE;

//-----------------------------------------------------------------------------
var Project = function() {

};

//-----------------------------------------------------------------------------
Project.prototype.create = function(name, creatorId, callback) {
  librarian.project.create({
    name: name,
    creator: creatorId
  }, false, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.restart = function(projectId, callback) {
  librarian.project.restart(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Restarting [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.running) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.stop = function(projectId, callback) {
  librarian.project.stop(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Stopping [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.stopped) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.start = function(projectId, callback) {
  librarian.project.start(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Starting [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.running) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.find = function(opts, callback) {
  librarian.project.find(opts, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.saveVars = function(projectId, vars, callback) {
  librarian.project.saveVars(projectId, vars, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.deploy = function(projectId, file, callback) {
  var host = librarian._http._host;
  var port = librarian._http._port;
  var protocol = librarian._http._ssl ? 'https' : 'http';

  modulus.io.print('Uploading project...');
  var status = Project.status.uploading;

  // start checking for status changes
  // show progress for upload and inderminate progress for deploying
  var ubar = new ProgressBar('Upload progress [:bar] :percent', {
    complete: '=',
    incomplete: ' ',
    width: 20,
    total: 100
  });
  ubar.tick();

  var client = uploader.uploadFile(file,
    {
      beginProtocol: 'https',
      uploadProtocol: 'http',
      beginPort: '443',
      uploadPort: '80',
      host: host,
      port: port,
      debug: false,
      encrypted: true,
      tag: { projectId: projectId, authToken: userConfig.data.apiKey }
    }
  );

  client.on('progress', function(p) {
    ubar.tick(((p.sent / p.total) * 100) - ubar.curr);
  });

  client.on('error', function(err) {
    callback(err);
  });

  client.on('complete', function() {
    var dbar = new Progress.indeterminate('Deploying [:bar]');

    // check every second for project status change
    var projectStatus = function () {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {
        if(!err) {
          if(proj && proj.status) {
            if(proj.status.toLowerCase() !== status) {
              var newStatus = proj.status.toLowerCase();
              if(newStatus === Project.status.deploying) {
                status = newStatus;
                modulus.io.print('\nDeploying Project...');
                dbar.start();
              } else if(newStatus === Project.status.running && status !== Project.status.uploading) {
                dbar.stop();
                modulus.io.print(' ');
                return callback(null, proj.domain);
              }
            }
          }
        }

        if(status !== Project.status.running) {
          setTimeout(projectStatus, 1000);
        }
      });
    };
    projectStatus();
  });
};

/**
 * Gets the logs for the specified project id.
 * @param {string} projectId The ID of the project.
 * @param {function} callback Function invoked with log results.
 */
//-----------------------------------------------------------------------------
Project.prototype.getLogs = function(projectId, callback) {
  librarian.project.getLog(projectId, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.status = {
  uploading : 'uploading',
  deploying : 'deploying',
  running : 'running',
  stopped: 'stopped'
};

module.exports = new Project();<|endoftext|>


<commit_before>// Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
$(document).ready(function () {
    Socket.on('console', function (data) {
        if (~data.line.indexOf('You need to agree to the EULA in order to run the server')) {
            swal({
                title: 'EULA Acceptance',
                text: 'By pressing \'I Accept\' below you are indicating your agreement to the Mojang EULA.',
                type: 'info',
                html: true,
                showCancelButton: true,
                showConfirmButton: true,
                cancelButtonText: 'I do not Accept',
                confirmButtonText: 'I Accept',
                closeOnConfirm: false,
                showLoaderOnConfirm: true
            }, function () {
                $.ajax({
                    type: 'POST',
                    url: Pterodactyl.meta.saveFile,
                    headers: { 'X-CSRF-Token': Pterodactyl.meta.csrfToken, },
                    data: {
                        file: 'eula.txt',
                        contents: 'eula=true'
                    }
                }).done(function (data) {
                    $('[data-attr="power"][data-action="start"]').trigger('click');
                    swal({
                        type: 'success',
                        title: '',
                        text: 'The EULA for this server has been accepted, restarting server now.',
                    });
                }).fail(function (jqXHR) {
                    console.error(jqXHR);
                    swal({
                        title: 'Whoops!',
                        text: 'An error occured while attempting to set the EULA as accepted: ' . jqXHR.responseJSON.error,
                        type: 'error'
                    })
                });
            });
        }
    });
});
<commit_msg>Catch potential undefined result.<commit_after>// Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
$(document).ready(function () {
    Socket.on('console', function (data) {
        if (typeof data === 'undefined' || typeof data.line === 'undefined') {
            return;
        }

        if (~data.line.indexOf('You need to agree to the EULA in order to run the server')) {
            swal({
                title: 'EULA Acceptance',
                text: 'By pressing \'I Accept\' below you are indicating your agreement to the Mojang EULA.',
                type: 'info',
                html: true,
                showCancelButton: true,
                showConfirmButton: true,
                cancelButtonText: 'I do not Accept',
                confirmButtonText: 'I Accept',
                closeOnConfirm: false,
                showLoaderOnConfirm: true
            }, function () {
                $.ajax({
                    type: 'POST',
                    url: Pterodactyl.meta.saveFile,
                    headers: { 'X-CSRF-Token': Pterodactyl.meta.csrfToken, },
                    data: {
                        file: 'eula.txt',
                        contents: 'eula=true'
                    }
                }).done(function (data) {
                    $('[data-attr="power"][data-action="start"]').trigger('click');
                    swal({
                        type: 'success',
                        title: '',
                        text: 'The EULA for this server has been accepted, restarting server now.',
                    });
                }).fail(function (jqXHR) {
                    console.error(jqXHR);
                    swal({
                        title: 'Whoops!',
                        text: 'An error occured while attempting to set the EULA as accepted: ' . jqXHR.responseJSON.error,
                        type: 'error'
                    })
                });
            });
        }
    });
});
<|endoftext|>