code
stringlengths
2
1.05M
Iddocs = new Meteor.Collection('iddocs'); Iddocs.helpers({ update(modifier) { modifier.updatedAt = new Date(); return Meteor.call('updateDoc', this._id, modifier); }, approve() { return this.update({ status: 'APPROVED' }); }, reject(reason) { return this.update({ status: 'REJECTED', statusReason: reason }); }, isPending() { return this.status === 'PENDING'; }, isApproved() { return this.status === 'APPROVED'; }, isRejected() { return this.status === 'REJECTED'; }, setPending() { return this.update({ status: 'PENDING' }); }, owner() { return Meteor.users.findOne({ _id: this.userId }); }, file() { return Docs.findOne(this.fileId); }, filetype() { switch (this.mimetype) { case 'image/jpeg': case 'image/png': case 'image/bmp': case 'image/gif': case 'image/pjpeg': case 'image/tiff': case 'image/x-tiff': return 'IMAGE'; case 'application/pdf': case 'application/msword': case 'application/rtf': case 'application/x-rtf': case 'text/richtext': return 'DOC'; default: return 'UNKNOWN'; } }, doctypeName() { return this.doctype.capitalize(); }, isDoc: function() { return this.filetype() === 'DOC'; }, });
"use strict"; const { test } = require("tap"); const { readLastLine, run } = require("./helpers"); test("ntl forward trailing options", t => { const cwd = t.testdir({ "package.json": JSON.stringify({ scripts: { test: "node test.js" } }), "test.js": "console.log(process.argv.slice(2).join(''))" }); const cp = run({ cwd }, ["--all", "--", "--one-more-thing"]); cp.assertNotStderrData(t); cp.getStdoutResult().then(res => { t.equal( readLastLine(res), "--one-more-thing", "should forward trailing options" ); t.end(); }); cp.stdin.write("\n"); cp.stdin.end(); });
/** * The MIT License (MIT) * * Copyright (c) 2013 Scott Will * * 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. **/ ;(function (undefined) { 'use strict'; var __version = '0.0.0004', __defaults = {}; window.Stagehand = function() { var _scope = this; return { version: __version }; }; })();
module.exports = { parse: function(inputString, inputBlocks, inputOperators) { //set default delimiter set var defaultBlocks = { warm: { "{": "}", "(": ")", "[": "]" }, cold: { "'": "'", '"': '"', "`": "`", "/*": "*/", "//": "\n", "/": "/", "<": ">" } } var defaultOperators = [ "~>", "->", "=>", "<<=", ">>=", ">>>", "===", "!==", ">>>", "...", "+=", "*=", "/=", "%=", "&=", "^=", "|=", "==", "!=", ">=", "<=", "++", "--", "<<", ">>", "&&", "||", "::", "=", ">", "<", "%", "-", "+", "&", "|", "^", "~", "!", "?", ":", ",", ";", "." ] //process delims for faster access var blocks = inputBlocks ? inputBlocks : defaultBlocks var operators = inputOperators ? inputOperators : defaultOperators blocks.all = {} for (var attr in blocks.warm) { blocks.all[attr] = blocks.warm[attr] } for (var attr in blocks.cold) { blocks.all[attr] = blocks.cold[attr] } blocks.start = {} blocks.start.cold = Object.keys(blocks.cold) blocks.start.all = Object.keys(blocks.all) //create function used to convert a 'tree node' back into its original string var tokenArrayToString = function() { for (var i = 0, output = ""; i < this.length; i++) { this[i].toString = tokenArrayToString; output += this[i].toString() } return output } var insertChildNode = function(currentNode, newValue, row, col) { //todo: sourceRow and sourceCol properly var newNode = (typeof newValue == "string") ? new String(newValue) : newValue currentNode.splice(-1, 0, newNode) currentNode.sourceRow = row currentNode.sourceCol = col } //token types //todo: add improved handling for 1e-1 var isWhitespace = /^[\r\n\t\s]+$/ //setup initial variables var input = inputString ? inputString + "\n" : "\n" var escapeMode = false var currentNode = [{ BOF: true }, { EOF: true }] var cold = false; var lineage = [currentNode] var buffer = "" //begin parsing for (var cursor = 0; cursor < input.length; cursor++) { var processed = 0; var awaiting = currentNode.slice(-1)[0] //block end if (!escapeMode && (input.slice(cursor, cursor + awaiting.length) == awaiting)) { if (buffer.length) { insertChildNode(currentNode, buffer, 0, 0) buffer = "" } currentNode = lineage.pop() processed = awaiting cold = false } //block start if (!processed && !cold) for (var sdi = 0; sdi < blocks.start.all.length; sdi++) { if (input.slice(cursor, cursor + blocks.start.all[sdi].length) === blocks.start.all[sdi]) { if (buffer.length) { insertChildNode(currentNode, buffer, 0, 0) buffer = '' } var start = blocks.start.all[sdi] var end = blocks.all[blocks.start.all[sdi]] var newNode = [start, end] insertChildNode(currentNode, newNode, 0, 0) lineage.push(currentNode) currentNode = newNode processed = blocks.start.all[sdi] if (blocks.start.cold.indexOf(blocks.start.all[sdi]) > -1) cold = true break } } //escape character (backslash) if (cold && input[cursor] == "\\" && cold) escapeMode = !escapeMode else escapeMode = false //search for operator delims if (!processed && !cold) for (var operatorId = 0; operatorId < operators.length; operatorId++) { var operator = operators[operatorId] if (input.slice(cursor, cursor + operator.length) === operator) { insertChildNode(currentNode, buffer, 0, 0) buffer = "" insertChildNode(currentNode, operator, 0, 0) processed = operator break } } if (!processed && !cold) { var fromWhitespace = isWhitespace.test(buffer) && !isWhitespace.test(input[cursor]) var toWhitespace = !isWhitespace.test(buffer) && isWhitespace.test(input[cursor]) if (false || fromWhitespace || toWhitespace) { insertChildNode(currentNode, buffer, 0, 0) buffer = input[cursor] processed = input[cursor] } } //buffer the current character if it hasn't yet been processed by another rule if (!processed) buffer += input[cursor] else cursor += processed.length - 1 } //output the tree root excluding the EOF and BOF markers var result = lineage[0].slice(1, -1) result.toString = tokenArrayToString return result } }
/** * model/users.js * * Provides users data access object. */ var bcrypt = require('bcrypt-nodejs'); function UsersDAO(connection) { // Adds new user to the database. this.addUser = function(data, callback) { // Generate password hash. var salt = bcrypt.genSaltSync(); var passwordHash = bcrypt.hashSync(data.password, salt); var query = 'INSERT INTO user (email, password, firstname, lastname) ' + 'VALUES (' + connection.escape(data.email) + ', ' + connection.escape(passwordHash) + ', ' + connection.escape(data.firstName) + ', ' + connection.escape(data.lastName) + ')'; connection.query(query, function(err, results) { callback(err, results); }); } // Validates provided username and password against db. this.validateLogin = function(email, password, callback) { // Validates user returned from database. function validateUser(err, user) { // Something unexpected happened. if (err) return callback(err, null); // Let's compare password hashes. if (user.length === 1) { if (bcrypt.compareSync(password, user[0].password)) { callback(null, user[0]); } else { callback(invalidCredentialsError(), null); } } else { callback(invalidCredentialsError(), null); } } function invalidCredentialsError() { var error = new Error('Wrong username or password.'); error.invalidCredentials = true; return error; } var query = 'SELECT * FROM user WHERE email = ' + connection.escape(email) + ' LIMIT 1'; connection.query(query, function(err, user) { validateUser(err, user); }); }; // Checks if username is already in use. this.usernameExists = function(username, callback) { var query = 'SELECT * FROM user WHERE email = ' + connection.escape(username); connection.query(query, function(err, results) { var exists = (results.length === 0) ? false : true; callback(err, exists); }); } } module.exports.UsersDAO = UsersDAO;
'use strict'; System.register('sijad/pages/addPagesPane', ['flarum/extend', 'flarum/components/AdminNav', 'flarum/components/AdminLinkButton', 'sijad/pages/components/PagesPage'], function (_export, _context) { var extend, AdminNav, AdminLinkButton, PagesPage; _export('default', function () { app.routes.pages = { path: '/pages', component: PagesPage.component() }; app.extensionSettings['sijad-pages'] = function () { return m.route(app.route('pages')); }; extend(AdminNav.prototype, 'items', function (items) { items.add('pages', AdminLinkButton.component({ href: app.route('pages'), icon: 'file-text-o', children: app.translator.trans('sijad-pages.admin.nav.pages_button'), description: app.translator.trans('sijad-pages.admin.nav.pages_text') })); }); }); return { setters: [function (_flarumExtend) { extend = _flarumExtend.extend; }, function (_flarumComponentsAdminNav) { AdminNav = _flarumComponentsAdminNav.default; }, function (_flarumComponentsAdminLinkButton) { AdminLinkButton = _flarumComponentsAdminLinkButton.default; }, function (_sijadPagesComponentsPagesPage) { PagesPage = _sijadPagesComponentsPagesPage.default; }], execute: function () {} }; });; 'use strict'; System.register('sijad/pages/components/EditPageModal', ['flarum/components/Modal', 'flarum/components/Button', 'flarum/utils/string'], function (_export, _context) { var Modal, Button, slug, EditPageModal; return { setters: [function (_flarumComponentsModal) { Modal = _flarumComponentsModal.default; }, function (_flarumComponentsButton) { Button = _flarumComponentsButton.default; }, function (_flarumUtilsString) { slug = _flarumUtilsString.slug; }], execute: function () { EditPageModal = function (_Modal) { babelHelpers.inherits(EditPageModal, _Modal); function EditPageModal() { babelHelpers.classCallCheck(this, EditPageModal); return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(EditPageModal).apply(this, arguments)); } babelHelpers.createClass(EditPageModal, [{ key: 'init', value: function init() { babelHelpers.get(Object.getPrototypeOf(EditPageModal.prototype), 'init', this).call(this); this.page = this.props.page || app.store.createRecord('pages'); this.pageTitle = m.prop(this.page.title() || ''); this.slug = m.prop(this.page.slug() || ''); this.pageContent = m.prop(this.page.content() || ''); this.isHidden = m.prop(this.page.isHidden() && true); } }, { key: 'className', value: function className() { return 'EditPageModal Modal--large'; } }, { key: 'title', value: function title() { var title = this.pageTitle(); return title ? title : app.translator.trans('sijad-pages.admin.edit_page.title'); } }, { key: 'content', value: function content() { var _this2 = this; return m( 'div', { className: 'Modal-body' }, m( 'div', { className: 'Form' }, m( 'div', { className: 'Form-group' }, m( 'label', null, app.translator.trans('sijad-pages.admin.edit_page.title_label') ), m('input', { className: 'FormControl', placeholder: app.translator.trans('sijad-pages.admin.edit_page.title_placeholder'), value: this.pageTitle(), oninput: function oninput(e) { _this2.pageTitle(e.target.value); _this2.slug(slug(e.target.value)); } }) ), m( 'div', { className: 'Form-group' }, m( 'label', null, app.translator.trans('sijad-pages.admin.edit_page.slug_label') ), m('input', { className: 'FormControl', placeholder: app.translator.trans('sijad-pages.admin.edit_page.slug_placeholder'), value: this.slug(), oninput: function oninput(e) { _this2.slug(e.target.value); } }) ), m( 'div', { className: 'Form-group' }, m( 'label', null, app.translator.trans('sijad-pages.admin.edit_page.content_label') ), m('textarea', { className: 'FormControl', rows: '5', value: this.pageContent(), onchange: m.withAttr('value', this.pageContent), placeholder: app.translator.trans('sijad-pages.admin.edit_page.content_placeholder') }) ), m( 'div', { className: 'Form-group' }, m( 'div', null, m( 'label', { className: 'checkbox' }, m('input', { type: 'checkbox', value: '1', checked: this.isHidden(), onchange: m.withAttr('checked', this.isHidden) }), app.translator.trans('sijad-pages.admin.edit_page.hidden_label') ) ) ), m( 'div', { className: 'Form-group' }, Button.component({ type: 'submit', className: 'Button Button--primary EditPageModal-save', loading: this.loading, children: app.translator.trans('sijad-pages.admin.edit_page.submit_button') }), this.page.exists ? m( 'button', { type: 'button', className: 'Button EditPageModal-delete', onclick: this.delete.bind(this) }, app.translator.trans('sijad-pages.admin.edit_page.delete_page_button') ) : '' ) ) ); } }, { key: 'onsubmit', value: function onsubmit(e) { var _this3 = this; e.preventDefault(); this.loading = true; this.page.save({ title: this.pageTitle(), slug: this.slug(), content: this.pageContent(), isHidden: this.isHidden() }, { errorHandler: this.onerror.bind(this) }).then(this.hide.bind(this)).catch(function () { _this3.loading = false; m.redraw(); }); } }, { key: 'onhide', value: function onhide() { m.route(app.route('pages')); } }, { key: 'delete', value: function _delete() { if (confirm(app.translator.trans('sijad-pages.admin.edit_page.delete_page_confirmation'))) { this.page.delete().then(function () { return m.redraw(); }); this.hide(); } } }]); return EditPageModal; }(Modal); _export('default', EditPageModal); } }; });; 'use strict'; System.register('sijad/pages/components/PagesList', ['flarum/Component', 'flarum/components/LoadingIndicator', 'flarum/components/Placeholder', 'flarum/components/Button', 'sijad/pages/components/PagesListItem'], function (_export, _context) { var Component, LoadingIndicator, Placeholder, Button, PagesListItem, PagesList; return { setters: [function (_flarumComponent) { Component = _flarumComponent.default; }, function (_flarumComponentsLoadingIndicator) { LoadingIndicator = _flarumComponentsLoadingIndicator.default; }, function (_flarumComponentsPlaceholder) { Placeholder = _flarumComponentsPlaceholder.default; }, function (_flarumComponentsButton) { Button = _flarumComponentsButton.default; }, function (_sijadPagesComponentsPagesListItem) { PagesListItem = _sijadPagesComponentsPagesListItem.default; }], execute: function () { PagesList = function (_Component) { babelHelpers.inherits(PagesList, _Component); function PagesList() { babelHelpers.classCallCheck(this, PagesList); return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(PagesList).apply(this, arguments)); } babelHelpers.createClass(PagesList, [{ key: 'init', value: function init() { /** * Whether or not pages results are loading. * * @type {Boolean} */ this.loading = true; /** * The pages in the pages list. * * @type {Sijad/Pages/Model/Page[]} */ this.pages = []; /** * Current page number. * * @type {Integer} */ this.page = 0; /** * The number of activity items to load per request. * * @type {Integer} */ this.loadLimit = 20; this.refresh(); } }, { key: 'view', value: function view() { if (this.loading) { return m( 'div', { className: 'PageList-loading' }, LoadingIndicator.component() ); } if (this.pages.length === 0) { var text = app.translator.trans('sijad-pages.admin.pages_list.empty_text'); return Placeholder.component({ text: text }); } var next = void 0, prev = void 0; if (this.nextResults === true) { next = Button.component({ className: 'Button Button--PageList-next', icon: 'angle-right', onclick: this.loadNext.bind(this) }); } if (this.prevResults === true) { prev = Button.component({ className: 'Button Button--PageList-prev', icon: 'angle-left', onclick: this.loadPrev.bind(this) }); } return m( 'div', { className: 'PageList' }, m( 'table', { className: 'PageList-results' }, m( 'thead', null, m( 'tr', null, m( 'th', null, app.translator.trans('sijad-pages.admin.pages_list.title') ), m('th', null) ) ), m( 'tbody', null, this.pages.map(function (page) { return PagesListItem.component({ page: page }); }) ) ), m( 'div', { className: 'PageList-pagination' }, next, prev ) ); } }, { key: 'refresh', value: function refresh() { var clear = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; if (clear) { this.loading = true; this.pages = []; } return this.loadResults().then(this.parseResults.bind(this)); } }, { key: 'loadResults', value: function loadResults() { var offset = this.page * this.loadLimit; return app.store.find('pages', { page: { offset: offset, limit: this.loadLimit }, sort: '-time' }); } }, { key: 'loadNext', value: function loadNext() { if (this.nextResults === true) { this.page++; this.refresh(); } } }, { key: 'loadPrev', value: function loadPrev() { if (this.prevResults === true) { this.page--; this.refresh(); } } }, { key: 'parseResults', value: function parseResults(results) { [].push.apply(this.pages, results); this.loading = false; this.nextResults = !!results.payload.links.next; this.prevResults = !!results.payload.links.prev; m.lazyRedraw(); return results; } }]); return PagesList; }(Component); _export('default', PagesList); } }; });; 'use strict'; System.register('sijad/pages/components/PagesListItem', ['flarum/Component', 'flarum/components/Button', 'sijad/pages/components/EditPageModal'], function (_export, _context) { var Component, Button, EditPageModal, PagesListItem; return { setters: [function (_flarumComponent) { Component = _flarumComponent.default; }, function (_flarumComponentsButton) { Button = _flarumComponentsButton.default; }, function (_sijadPagesComponentsEditPageModal) { EditPageModal = _sijadPagesComponentsEditPageModal.default; }], execute: function () { PagesListItem = function (_Component) { babelHelpers.inherits(PagesListItem, _Component); function PagesListItem() { babelHelpers.classCallCheck(this, PagesListItem); return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(PagesListItem).apply(this, arguments)); } babelHelpers.createClass(PagesListItem, [{ key: 'view', value: function view() { var page = this.props.page; var url = app.forum.attribute('baseUrl') + '/p/' + page.id() + '-' + page.slug(); return m( 'tr', { key: page.id() }, m( 'th', null, page.title() ), m( 'td', { className: 'Pages-actions' }, m( 'div', { className: 'ButtonGroup' }, Button.component({ className: 'Button Button--page-edit', icon: 'pencil', onclick: function onclick() { return app.modal.show(new EditPageModal({ page: page })); } }), m( 'a', { 'class': 'Button Button--page-view hasIcon', target: '_blank', href: url }, m('i', { 'class': 'icon fa fa-fw fa-eye Button-icon' }) ), Button.component({ className: 'Button Button--danger Button--page-delete', icon: 'times', onclick: this.delete.bind(this) }) ) ) ); } }, { key: 'delete', value: function _delete() { if (confirm(app.translator.trans('sijad-pages.admin.edit_page.delete_page_confirmation'))) { var page = this.props.page; m.redraw.strategy('all'); page.delete().then(function () { return m.redraw(); }); } } }]); return PagesListItem; }(Component); _export('default', PagesListItem); } }; });; 'use strict'; System.register('sijad/pages/components/PagesPage', ['flarum/components/Page', 'flarum/components/Button', 'flarum/components/LoadingIndicator', 'sijad/pages/components/EditPageModal', 'sijad/pages/components/PagesList'], function (_export, _context) { var Page, Button, LoadingIndicator, EditPageModal, PagesList, PagesPage; return { setters: [function (_flarumComponentsPage) { Page = _flarumComponentsPage.default; }, function (_flarumComponentsButton) { Button = _flarumComponentsButton.default; }, function (_flarumComponentsLoadingIndicator) { LoadingIndicator = _flarumComponentsLoadingIndicator.default; }, function (_sijadPagesComponentsEditPageModal) { EditPageModal = _sijadPagesComponentsEditPageModal.default; }, function (_sijadPagesComponentsPagesList) { PagesList = _sijadPagesComponentsPagesList.default; }], execute: function () { PagesPage = function (_Page) { babelHelpers.inherits(PagesPage, _Page); function PagesPage() { babelHelpers.classCallCheck(this, PagesPage); return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(PagesPage).apply(this, arguments)); } babelHelpers.createClass(PagesPage, [{ key: 'view', value: function view() { return m( 'div', { className: 'PagesPage' }, m( 'div', { className: 'PagesPage-header' }, m( 'div', { className: 'container' }, m( 'p', null, app.translator.trans('sijad-pages.admin.pages.about_text') ), Button.component({ className: 'Button Button--primary', icon: 'plus', children: app.translator.trans('sijad-pages.admin.pages.create_button'), onclick: function onclick() { return app.modal.show(new EditPageModal()); } }) ) ), m( 'div', { className: 'PagesPage-list' }, m( 'div', { className: 'container' }, PagesList.component() ) ) ); } }]); return PagesPage; }(Page); _export('default', PagesPage); } }; });; 'use strict'; System.register('sijad/pages/main', ['flarum/extend', 'sijad/pages/models/Page', 'sijad/pages/addPagesPane'], function (_export, _context) { var extend, Page, addPagesPane; return { setters: [function (_flarumExtend) { extend = _flarumExtend.extend; }, function (_sijadPagesModelsPage) { Page = _sijadPagesModelsPage.default; }, function (_sijadPagesAddPagesPane) { addPagesPane = _sijadPagesAddPagesPane.default; }], execute: function () { app.initializers.add('sijad-pages', function (app) { app.store.models.pages = Page; addPagesPane(); }); } }; });; 'use strict'; System.register('sijad/pages/models/Page', ['flarum/Model', 'flarum/utils/mixin', 'flarum/utils/computed', 'flarum/utils/string'], function (_export, _context) { var Model, mixin, computed, getPlainContent, Page; return { setters: [function (_flarumModel) { Model = _flarumModel.default; }, function (_flarumUtilsMixin) { mixin = _flarumUtilsMixin.default; }, function (_flarumUtilsComputed) { computed = _flarumUtilsComputed.default; }, function (_flarumUtilsString) { getPlainContent = _flarumUtilsString.getPlainContent; }], execute: function () { Page = function (_mixin) { babelHelpers.inherits(Page, _mixin); function Page() { babelHelpers.classCallCheck(this, Page); return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Page).apply(this, arguments)); } return Page; }(mixin(Model, { title: Model.attribute('title'), time: Model.attribute('time', Model.transformDate), editTime: Model.attribute('editTime', Model.transformDate), content: Model.attribute('content'), contentHtml: Model.attribute('contentHtml'), contentPlain: computed('contentHtml', getPlainContent), slug: Model.attribute('slug'), isHidden: Model.attribute('isHidden') })); _export('default', Page); } }; });
/** * Created by WareBare on 4/13/2017. * * @author WareBare (Daniel Kamp) * @license MIT * @website https://github.com/WareBare * */ module.exports = { contentType: `Step 1`, title: `Mastery Wizard`, wndId: `masteryWizard`, Settings: { height: `1000px`, width: `750px`, }, formData: {}, validSteps: {}, err_: ``, dbr: {}, genTrainingValues: function(){ let objValues = {}; for(let $_Field in this.formData.Step02){ if(this.formData.Step02[$_Field] > 0){ objValues[$_Field] = wzMathGD.genValues({ number: this.formData.Step02[$_Field], dec: 6, round: `down` }); } } return objValues; }, saveDBR: function(){ for(let $_DBR in this.dbr){ this.dbr[$_DBR].saveDBR(); } }, /** * create files - button onClick * @return {boolean} */ create: function(){ if(!this.validation()) return false; //console.log(this.formData); let enum_ = (`0${this.formData.Step01.Enum}`).slice(-2); //console.log(enum_); // records/skills/[FOLDER]/_classtraining_class01.dbr => database/templates/skill_mastery.tpl // skillBaseDescription,tagClass02SkillDescription00A, // skillDisplayName,tagClass02SkillName00A, // skillMaxLevel,50, // MasteryEnumeration,SkillClass02, //console.log(wzMathGD.genValues({number: 3.5,dec: 6,round: `down`})); // _CLASS_TRAINING \\ this.dbr._classTraining = new WZ.GrimDawn.cData(); this.dbr._classTraining.changeFilePath(`/${WZ.GrimDawn.tFn.getPaths().MasterySkills}/${this.formData.Step01.MasteryDirectory}/_classtraining_class${enum_}.dbr`); this.dbr._classTraining.fetchTemplate(`database/templates/skill_mastery.tpl`); this.dbr._classTraining.editDBR({ skillBaseDescription: `tagClass${enum_}SkillDescription00`, skillDisplayName: `tagClass${enum_}SkillName00`, skillMaxLevel: `50`, skillTier: ``, MasteryEnumeration: `SkillClass${enum_}`, skillDownBitmapName: this.formData.Step01.classSkillBitmap.wzOut({TYPE: `down`,ENUM: enum_}), skillUpBitmapName: this.formData.Step01.classSkillBitmap.wzOut({TYPE: `up`,ENUM: enum_}) }); this.dbr._classTraining.editDBR(this.genTrainingValues()); // records/skills/[FOLDER]/_classtree_class01.dbr => database/templates/skilltree.tpl // _CLASS_TRAINING \\ this.dbr._classTree = new WZ.GrimDawn.cData(); this.dbr._classTree.changeFilePath(`/${WZ.GrimDawn.tFn.getPaths().MasterySkills}/${this.formData.Step01.MasteryDirectory}/_classtree_class${enum_}.dbr`); this.dbr._classTree.fetchTemplate(`database/templates/skilltree.tpl`); this.dbr._classTree.editDBR({ skillName1: `${WZ.GrimDawn.tFn.getPaths().MasterySkills}/${this.formData.Step01.MasteryDirectory}/_classtraining_class${enum_}.dbr`, skillLevel1: `0` }); // CLASS_IMAGE \\ this.dbr.classImage = new WZ.GrimDawn.cData(); this.dbr.classImage.changeFilePath(`/${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classimage.dbr`); this.dbr.classImage.fetchTemplate(`database/templates/ingameui/bitmapsingle.tpl`); this.dbr.classImage.editDBR({ bitmapPositionX: `20`, bitmapPositionY: `20`, bitmapName: this.formData.Step01.classImage.wzOut({ENUM: enum_}) }); // CLASS_PANEL_BACKGROUND_IMAGE \\ this.dbr.classPanelBackgroundImage = new WZ.GrimDawn.cData(); this.dbr.classPanelBackgroundImage.changeFilePath(`/${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classpanelbackgroundimage.dbr`); this.dbr.classPanelBackgroundImage.fetchTemplate(`database/templates/ingameui/bitmapsingle.tpl`); this.dbr.classPanelBackgroundImage.editDBR({ bitmapName: `ui/skills/skills_classbackgroundimage.tex`, bitmapPositionX: `0`, bitmapPositionY: `0` }); // CLASS_PANEL_REALLOCATION_IMAGE \\ this.dbr.classPanelReallocationImage = new WZ.GrimDawn.cData(); this.dbr.classPanelReallocationImage.changeFilePath(`/${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classpanelreallocationimage.dbr`); this.dbr.classPanelReallocationImage.fetchTemplate(`database/templates/ingameui/bitmapsingle.tpl`); this.dbr.classPanelReallocationImage.editDBR({ bitmapName: `ui/skills/skills_classreallocationbackgroundimage.tex`, bitmapPositionX: `0`, bitmapPositionY: `0` }); // CLASS_TABLE \\ this.dbr.classTable = new WZ.GrimDawn.cData(); this.dbr.classTable.changeFilePath(`/${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classtable.dbr`); this.dbr.classTable.fetchTemplate(`database/templates/ingameui/skillpanectrl.tpl`); this.dbr.classTable.editDBR({ BasePane: `records/ui/skills/classcommon/skills_classpanelconfiguration.dbr`, tabSkillButtons: `${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classtraining.dbr`, masteryBar: `${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classtrainingbar.dbr`, peekThroughColorBlue: `0.800000`, peekThroughColorGreen: `0.600000`, peekThroughColorRed: `0.200000`, peekThroughNextTierSound: `records/sounds/ui/spak_craftingpartcomplete.dbr`, skillPaneBaseBitmap: `${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classpanelbackgroundimage.dbr`, skillPaneBaseReallocationBitmap: `${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classpanelreallocationimage.dbr`, skillPaneMasteryBitmap: `${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classimage.dbr`, skillTabTitle: `tagSkillClassName${enum_}`, skillPaneDescriptionTag: `tagSkillClassDescription${enum_}`, }); // CLASS_TRAINING \\ this.dbr.classTraining = new WZ.GrimDawn.cData(); this.dbr.classTraining.changeFilePath(`/${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classtraining.dbr`); this.dbr.classTraining.fetchTemplate(`database/templates/ingameui/skillbutton.tpl`); this.dbr.classTraining.editDBR({ skillName: `${WZ.GrimDawn.tFn.getPaths().MasterySkills}/${this.formData.Step01.MasteryDirectory}/_classtraining_class${enum_}.dbr`, soundNameDown: `records/sounds/ui/spak_buttonskillmasteryincrement.dbr`, isCircular: `1`, bitmapPositionX: `157`, bitmapPositionY: `502` }); // CLASS_TRAINING_BAR \\ this.dbr.classTrainingBar = new WZ.GrimDawn.cData(); this.dbr.classTrainingBar.changeFilePath(`/${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classtrainingbar.dbr`); this.dbr.classTrainingBar.fetchTemplate(`database/templates/ingameui/bargraph.tpl`); this.dbr.classTrainingBar.editDBR({ bitmapFullName: this.formData.Step01.classTrainingBar.wzOut({ENUM: enum_}), bitmapPositionX: `187`, bitmapPositionY: `514` }); // CLASS_SELECTION_BUTTON \\ this.dbr.classSelectionButton = new WZ.GrimDawn.cData(); this.dbr.classSelectionButton.changeFilePath(`/records/ui/skills/classselection/skills_classselectionbutton${enum_}.dbr`); this.dbr.classSelectionButton.fetchTemplate(`database/templates/ingameui/buttonstatic.tpl`); this.dbr.classSelectionButton.editDBR({ bitmapNameDisabled: this.formData.Step01.classSelectionButtonImage.wzOut({TYPE: `disabled`,ENUM: enum_}), bitmapNameDown: this.formData.Step01.classSelectionButtonImage.wzOut({TYPE: `down`,ENUM: enum_}), bitmapNameInFocus: this.formData.Step01.classSelectionButtonImage.wzOut({TYPE: `over`,ENUM: enum_}), bitmapNameUp: this.formData.Step01.classSelectionButtonImage.wzOut({TYPE: `up`,ENUM: enum_}), bitmapPositionX: `0`, bitmapPositionY: `0`, soundNameDown: `records/sounds/ui/spak_buttonclickgenericlarge.dbr` }); // CLASS_SELECTION_TEXT \\ this.dbr.classSelectionText = new WZ.GrimDawn.cData(); this.dbr.classSelectionText.changeFilePath(`/records/ui/skills/classselection/skills_classselectiontext${enum_}.dbr`); this.dbr.classSelectionText.fetchTemplate(`database/templates/ingameui/textstaticstring.tpl`); this.dbr.classSelectionText.editDBR({ style: `records/ui/styles/text/style_special_skillnames.dbr`, textAlignmentX: `Center`, textAlignmentY: `Center`, textBoxXSize: this.formData.Step01.classSelectionButtonTextX, textBoxYSize: this.formData.Step01.classSelectionButtonTextY, textBoxX: `0`, textBoxY: `0`, textTag: `tagSkillClassName${enum_}` }); let tempOpt = {}; tempOpt[`skillTree${this.formData.Step01.Enum}`] = `${WZ.GrimDawn.tFn.getPaths().MasterySkills}/${this.formData.Step01.MasteryDirectory}/_classtree_class${enum_}.dbr`; this.dbr.femalepc01.editDBR(tempOpt); this.dbr.malepc01.editDBR(tempOpt); tempOpt = {}; tempOpt[`skillCtrlPane${this.formData.Step01.Enum}`] = `${WZ.GrimDawn.tFn.getPaths().MasteryUI}/${this.formData.Step01.MasteryDirectory}/classtable.dbr`; this.dbr.masterTable.editDBR(tempOpt); let aButtons = this.dbr.classSelectionTable.__getField(`masteryMasteryButtons`), aTexts = this.dbr.classSelectionTable.__getField(`masteryMasteryText`), aBitmaps = this.dbr.classSelectionTable.__getField(`masteryMasterySelectedBitmapNames`), aTags = this.dbr.classSelectionTable.__getField(`masteryMasterySelectedDescriptionTags`); //this.formData.Step01.Enum - 1 for(let i=0; i<30; i++){ if(this.formData.Step01.Enum - 1 === i){ aButtons[i] = `records/ui/skills/classselection/skills_classselectionbutton${enum_}.dbr`; aTexts[i] = `records/ui/skills/classselection/skills_classselectiontext${enum_}.dbr`; aBitmaps[i] = `${WZ.GrimDawn.tFn.getPaths().MasterySource}/classselection/skills_classselectedimage${enum_}.tex`; // todo form field aTags[i] = `tagSkillClassDescription${enum_}`; }else{ aButtons[i] = aButtons[i] || `placeholder_${i + 1}`; aTexts[i] = aTexts[i] || `placeholder_${i + 1}`; aBitmaps[i] = aBitmaps[i] || `placeholder_${i + 1}`; aTags[i] = aTags[i] || `placeholder_${i + 1}`; } } this.dbr.classSelectionTable.editDBR({ masteryMasteryButtons: aButtons, masteryMasteryText: aTexts, masteryMasterySelectedBitmapNames: aBitmaps, masteryMasterySelectedDescriptionTags: aTags }); // this.formData.Step01.classSelectionButton.wzOut({TYPE: `down`,ENUM: enum_}) //this.dbr.classImage = tempClass; //console.log(this.dbr); this.saveDBR(); }, nav_: function(){ this.dbr.femalepc01 = _cms.Base.aGenderPC01[0]; this.dbr.malepc01 = _cms.Base.aGenderPC01[1]; this.err_ = this.validation(); return [ `Step 1`, `${(this.validSteps.Step01) ? `` : `.`}Step 2`, `${(this.validSteps.Step02) ? `` : `.`}Step 3` ]; } };
define([ 'jquery', 'underscore', 'backbone', 'mustache', 'initView', 'text!templates/categories/categoriesItem.mustache', 'text!templates/categories/categoriesForm.mustache', 'categoryModel', 'categoryCollection', 'storage' ], function( $, _, Backbone, Mustache, InitView, CategoriesItemTemplate, CategoriesFormTemplate, Category, CategoryCollection, storage) { var CategoryFormView = Backbone.View.extend({ el: $("#content"), displayForm: function(categorie){ var categories_actives = storage.categories.enable(); var template = Mustache.render(CategoriesFormTemplate, { 'categorie': categorie, 'categories': new CategoryCollection(categories_actives).toJSON() }); $("#content").html(template); var defaultIcon = "fa-circle-o"; // Put select markup as selected if (categorie) { $("#cat_form select[name='parent']").find('option[value="' + categorie.parent_id + '"]').attr('selected', true); defaultIcon = categorie.icon; } $('#cat_form .iconpicker').iconpicker({ arrowClass: 'btn-primary', arrowPrevIconClass: 'glyphicon glyphicon-chevron-left', arrowNextIconClass: 'glyphicon glyphicon-chevron-right', cols: 5, icon: defaultIcon, iconset: 'fontawesome', labelHeader: '{0} of {1} pages', labelFooter: '{0} - {1} of {2} icons', placement: 'bottom', rows: 5, search: true, searchText: 'Search', selectedClass: 'btn-primary', unselectedClass: '' }); $('#cat_form .colorpicker').colorpicker(); // User validate form $("#cat_form").on("submit", function() { var array = $("#cat_form").serializeArray(); var dict = {}; for (var i = 0; i < array.length; i++) { dict[array[i]['name']] = array[i]['value'] } dict['user'] = storage.user.get('id'); if (dict.parent && dict.parent !== "") { dict.parent = storage.categories.get(dict.parent).url(); } var category = new Category(dict); Backbone.Validation.bind(this, { model: category, valid: function(view, attr) { // Check if all are required $(view).find('input[name=' + attr + '], select[name=' + attr + ']') .parent() .removeClass('has-error') .addClass('has-success') .prev().html(''); }, invalid: function(view, attr, error) { $(view).find('input[name=' + attr + '], select[name=' + attr + ']') .parent() .addClass('has-error') .removeClass('has-success') .prev().html(error); } }); category.validate(); if (category.isValid()) { category.save(dict, { wait: true, success: function(model, response) { storage.categories.fetch({ success: function(){ Backbone.history.navigate("#/categories", { trigger: true }); } }); }, error: function(model, error) { console.log(model.toJSON()); console.log('error.responseText'); } }); } return false; }); }, render: function(categorie_id) { var initView = new InitView(); if (initView.isLoaded() === false) { initView.render(); } initView.changeSelectedItem("nav_categories"); var view = this; require(['bootstrap-iconpicker', 'bootstrap-colorpicker'], function() { if(categorie_id){ var categorie = new Category({id: categorie_id}); categorie.fetch({ success: function (c) { view.displayForm(categorie.toJSON()); } }); }else{ view.displayForm(); } }); } }); return CategoryFormView; });
exports.html = require('./html'); exports.javascript = require('./javascript'); exports.sass = require('./sass'); exports.misc = require('./misc');
/*jshint esversion: 6 */ import home from './components/home'; import excelTool from './components/excelTool'; const routes = [ { path: '/home', component: home }, { path: '/excelTool', component: excelTool } ]; export default routes;
app.controller('compCtrl', ['flickr'], function(context, flickr) { context.model.photos = []; context.model.refreshPhotos = function() { flickr.getPhotos(function() { context.model.photos = flickr.photos; }); } context.model.refreshPhotos(); });
let fs = require("fs"), path = require("path"), debug = require("debug"), debugBuild = debug("graffito-build"), debugData = debug("graffito-data"), site = require("./plugins/site"), conrefifier = require("./plugins/conrefifier"), datafiles = require("./plugins/datafiles"), renderer = require("./plugins/renderer"), layout = require("./plugins/layout").layout, Metalsmith = require("metalsmith"), ignore = require("metalsmith-ignore"), watch = require("metalsmith-watch"), yaml = require("js-yaml"), walk = require("walk-promise"), _ = require("lodash"); module.exports = async function(options, buildOptions) { let startTime = new Date(); if (!_.isObject(options)) { return new Promise(function(resolve, reject) { return reject(new TypeError("Your initial options are not an object!")); }); } if (_.isEmpty(options)) { return new Promise(function(resolve, reject) { return reject(new TypeError("Your initial options are empty!")); }); } if (_.isUndefined(options.base)) { return new Promise(function(resolve, reject) { return reject(new TypeError("You're missing the `base` key in the initial options!")); }); } if (!_.isArray(buildOptions)) { return new Promise(function(resolve, reject) { return reject(new TypeError("Your build options are not an array!")); }); } if (_.isEmpty(buildOptions)) { return new Promise(function(resolve, reject) { return reject(new TypeError("Your build options are empty!")); }); } const CONFIG_PATH = path.join(options.base, "_graffito.yml"); site.config = {}; // First, parse the main site config data try { if (fs.lstatSync(CONFIG_PATH)) { site.config = yaml.safeLoad(fs.readFileSync(CONFIG_PATH, "utf8")); site.config = conrefifier.convertVariables(site.config); } } catch(e) { /* file doesn't exist */ } // Next, iterate on the data folder, picking up YML files if (process.env.SKIP_DATA != "true") { const DATA_PATH = path.join(options.base, "data"); debugData("Start data"); try { if (fs.lstatSync(DATA_PATH)) { let dataFiles = await walk(DATA_PATH); for (let dataFile of dataFiles) { await datafiles.process(site.config, dataFile); } } } catch(e) { /* directory doesn't exist */ } debugData("End data"); } // Store data files at the site level site.data = datafiles.data; // process each build! debugBuild("Start build"); for (let build of buildOptions) { await processBuild(build); } debugBuild("End build"); return new Promise(function (resolve) { let endTime = new Date(); let timeDiff = endTime - startTime; if (!process.env.JASMINE_TEST) { console.log(`Finished in ${timeDiff / 1000}s`); } return resolve(); }); function processBuild(build) { return new Promise(function (resolve) { // someone is being a jerk if (!_.isObject(build) || _.isEmpty(build)) { return resolve(); } let smith = Metalsmith(__dirname) .source(path.join(options.base, build.source)) .destination(path.join(options.destination, build.destination)) .clean(false) .frontmatter(false) // disabling for frontmatter manipulation in renderer .use(ignore(site.config.exclude)) .use(renderer({ type: 'markdown' })) .use(layout({ "directory": path.join(options.base, "layouts"), "template": build.template })); if (process.env.JASMINE_TEST != "true") { smith = smith.use( watch({ paths: { "${source}/**/*": true }, livereload: false }) ); } if (build.plugins) { for (let plugin of build.plugins) { smith = smith.use(plugin()); } } smith.build(function (err) { if (err) { console.error(`Error processing build: ${err}`); throw err; } return resolve(); }); }); } }
'use strict'; angular.module('plankApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ui.router', 'ui.bootstrap' ]) .config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) { $urlRouterProvider.otherwise('/'); $locationProvider.html5Mode(true); // true mean drop the # on urls $httpProvider.interceptors.push('authInterceptor'); }) .factory('authInterceptor', function ($rootScope, $q, $cookieStore, $location) { return { // Add authorization token to headers request: function (config) { config.headers = config.headers || {}; if ($cookieStore.get('token')) { config.headers.Authorization = 'Bearer ' + $cookieStore.get('token'); } return config; }, // Intercept 401s and redirect you to login responseError: function(response) { if(response.status === 401) { $location.path('/login'); // remove any stale tokens $cookieStore.remove('token'); return $q.reject(response); } else { return $q.reject(response); } } }; }) .run(function ($rootScope, $location, Auth, $state) { // Redirect to login if route requires auth and you're not logged in $rootScope.$on('$stateChangeStart', function (event, next) { Auth.isLoggedInAsync(function(loggedIn) { if (next.authenticate && !loggedIn) { $location.path('/login'); } }); }); $rootScope.isLoggedIn = Auth.isLoggedIn; $rootScope.isAdmin = Auth.isAdmin; $rootScope.getCurrentUser = Auth.getCurrentUser; $rootScope.logout = function() { Auth.logout(); $location.path('/login'); }; $rootScope.state = function() { return $state.$current.name; }; });
var transform = (function() { var properties = [ 'oTransform', // Opera 11.5 'msTransform', // IE 9 'mozTransform', 'webkitTransform', 'transform' ]; var style = document.createElement('div').style; for (var i = 0; i < properties.length; i++) { /* istanbul ignore else */ if (properties[i] in style) { return properties[i]; } } /* istanbul ignore next */ return 'transform'; }()); function createCommentNode(cmt) { var node = document.createElement('div'); node.style.cssText = 'position:absolute;'; if (typeof cmt.render === 'function') { var $el = cmt.render(); if ($el instanceof HTMLElement) { node.appendChild($el); return node; } } node.textContent = cmt.text; if (cmt.style) { for (var key in cmt.style) { node.style[key] = cmt.style[key]; } } return node; } function init() { var stage = document.createElement('div'); stage.style.cssText = 'overflow:hidden;white-space:nowrap;transform:translateZ(0);'; return stage; } function clear(stage) { var lc = stage.lastChild; while (lc) { stage.removeChild(lc); lc = stage.lastChild; } } function resize(stage) { stage.style.width = stage.width + 'px'; stage.style.height = stage.height + 'px'; } function framing() { // } function setup(stage, comments) { var df = document.createDocumentFragment(); var i = 0; var cmt = null; for (i = 0; i < comments.length; i++) { cmt = comments[i]; cmt.node = cmt.node || createCommentNode(cmt); df.appendChild(cmt.node); } if (comments.length) { stage.appendChild(df); } for (i = 0; i < comments.length; i++) { cmt = comments[i]; cmt.width = cmt.width || cmt.node.offsetWidth; cmt.height = cmt.height || cmt.node.offsetHeight; } } function render(stage, cmt) { cmt.node.style[transform] = 'translate(' + cmt.x + 'px,' + cmt.y + 'px)'; } /* eslint no-invalid-this: 0 */ function remove(stage, cmt) { stage.removeChild(cmt.node); /* istanbul ignore else */ if (!this.media) { cmt.node = null; } } var domEngine = { name: 'dom', init: init, clear: clear, resize: resize, framing: framing, setup: setup, render: render, remove: remove, }; /* eslint no-invalid-this: 0 */ function allocate(cmt) { var that = this; var ct = this.media ? this.media.currentTime : Date.now() / 1000; var pbr = this.media ? this.media.playbackRate : 1; function willCollide(cr, cmt) { if (cmt.mode === 'top' || cmt.mode === 'bottom') { return ct - cr.time < that._.duration; } var crTotalWidth = that._.stage.width + cr.width; var crElapsed = crTotalWidth * (ct - cr.time) * pbr / that._.duration; if (cr.width > crElapsed) { return true; } // (rtl mode) the right end of `cr` move out of left side of stage var crLeftTime = that._.duration + cr.time - ct; var cmtTotalWidth = that._.stage.width + cmt.width; var cmtTime = that.media ? cmt.time : cmt._utc; var cmtElapsed = cmtTotalWidth * (ct - cmtTime) * pbr / that._.duration; var cmtArrival = that._.stage.width - cmtElapsed; // (rtl mode) the left end of `cmt` reach the left side of stage var cmtArrivalTime = that._.duration * cmtArrival / (that._.stage.width + cmt.width); return crLeftTime > cmtArrivalTime; } var crs = this._.space[cmt.mode]; var last = 0; var curr = 0; for (var i = 1; i < crs.length; i++) { var cr = crs[i]; var requiredRange = cmt.height; if (cmt.mode === 'top' || cmt.mode === 'bottom') { requiredRange += cr.height; } if (cr.range - cr.height - crs[last].range >= requiredRange) { curr = i; break; } if (willCollide(cr, cmt)) { last = i; } } var channel = crs[last].range; var crObj = { range: channel + cmt.height, time: this.media ? cmt.time : cmt._utc, width: cmt.width, height: cmt.height }; crs.splice(last + 1, curr - last - 1, crObj); if (cmt.mode === 'bottom') { return this._.stage.height - cmt.height - channel % this._.stage.height; } return channel % (this._.stage.height - cmt.height); } /* eslint no-invalid-this: 0 */ function createEngine(framing, setup, render, remove) { return function() { framing(this._.stage); var dn = Date.now() / 1000; var ct = this.media ? this.media.currentTime : dn; var pbr = this.media ? this.media.playbackRate : 1; var cmt = null; var cmtt = 0; var i = 0; for (i = this._.runningList.length - 1; i >= 0; i--) { cmt = this._.runningList[i]; cmtt = this.media ? cmt.time : cmt._utc; if (ct - cmtt > this._.duration) { remove(this._.stage, cmt); this._.runningList.splice(i, 1); } } var pendingList = []; while (this._.position < this.comments.length) { cmt = this.comments[this._.position]; cmtt = this.media ? cmt.time : cmt._utc; if (cmtt >= ct) { break; } // when clicking controls to seek, media.currentTime may changed before // `pause` event is fired, so here skips comments out of duration, // see https://github.com/weizhenye/Danmaku/pull/30 for details. if (ct - cmtt > this._.duration) { ++this._.position; continue; } if (this.media) { cmt._utc = dn - (this.media.currentTime - cmt.time); } pendingList.push(cmt); ++this._.position; } setup(this._.stage, pendingList); for (i = 0; i < pendingList.length; i++) { cmt = pendingList[i]; cmt.y = allocate.call(this, cmt); if (cmt.mode === 'top' || cmt.mode === 'bottom') { cmt.x = (this._.stage.width - cmt.width) >> 1; } this._.runningList.push(cmt); } for (i = 0; i < this._.runningList.length; i++) { cmt = this._.runningList[i]; var totalWidth = this._.stage.width + cmt.width; var elapsed = totalWidth * (dn - cmt._utc) * pbr / this._.duration; if (cmt.mode === 'ltr') cmt.x = (elapsed - cmt.width + .5) | 0; if (cmt.mode === 'rtl') cmt.x = (this._.stage.width - elapsed + .5) | 0; render(this._.stage, cmt); } }; } var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(cb) { return setTimeout(cb, 50 / 3); }; var caf = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || clearTimeout; function binsearch(arr, prop, key) { var mid = 0; var left = 0; var right = arr.length; while (left < right - 1) { mid = (left + right) >> 1; if (key >= arr[mid][prop]) { left = mid; } else { right = mid; } } if (arr[left] && key < arr[left][prop]) { return left; } return right; } function formatMode(mode) { if (!/^(ltr|top|bottom)$/i.test(mode)) { return 'rtl'; } return mode.toLowerCase(); } function collidableRange() { var max = 9007199254740991; return [ { range: 0, time: -max, width: max, height: 0 }, { range: max, time: max, width: 0, height: 0 } ]; } function resetSpace(space) { space.ltr = collidableRange(); space.rtl = collidableRange(); space.top = collidableRange(); space.bottom = collidableRange(); } /* eslint no-invalid-this: 0 */ function play() { if (!this._.visible || !this._.paused) { return this; } this._.paused = false; if (this.media) { for (var i = 0; i < this._.runningList.length; i++) { var cmt = this._.runningList[i]; cmt._utc = Date.now() / 1000 - (this.media.currentTime - cmt.time); } } var that = this; var engine = createEngine( this._.engine.framing.bind(this), this._.engine.setup.bind(this), this._.engine.render.bind(this), this._.engine.remove.bind(this) ); function frame() { engine.call(that); that._.requestID = raf(frame); } this._.requestID = raf(frame); return this; } /* eslint no-invalid-this: 0 */ function pause() { if (!this._.visible || this._.paused) { return this; } this._.paused = true; caf(this._.requestID); this._.requestID = 0; return this; } /* eslint no-invalid-this: 0 */ function seek() { if (!this.media) { return this; } this.clear(); resetSpace(this._.space); var position = binsearch(this.comments, 'time', this.media.currentTime); this._.position = Math.max(0, position - 1); return this; } /* eslint no-invalid-this: 0 */ function bindEvents(_) { _.play = play.bind(this); _.pause = pause.bind(this); _.seeking = seek.bind(this); this.media.addEventListener('play', _.play); this.media.addEventListener('pause', _.pause); this.media.addEventListener('playing', _.play); this.media.addEventListener('waiting', _.pause); this.media.addEventListener('seeking', _.seeking); } /* eslint no-invalid-this: 0 */ function unbindEvents(_) { this.media.removeEventListener('play', _.play); this.media.removeEventListener('pause', _.pause); this.media.removeEventListener('playing', _.play); this.media.removeEventListener('waiting', _.pause); this.media.removeEventListener('seeking', _.seeking); _.play = null; _.pause = null; _.seeking = null; } /* eslint-disable no-invalid-this */ function init$1(opt) { this._ = {}; this.container = opt.container || document.createElement('div'); this.media = opt.media; this._.visible = true; /* eslint-disable no-undef */ /* istanbul ignore next */ { this.engine = 'dom'; this._.engine = domEngine; } /* eslint-enable no-undef */ this._.requestID = 0; this._.speed = Math.max(0, opt.speed) || 144; this._.duration = 4; this.comments = opt.comments || []; this.comments.sort(function(a, b) { return a.time - b.time; }); for (var i = 0; i < this.comments.length; i++) { this.comments[i].mode = formatMode(this.comments[i].mode); } this._.runningList = []; this._.position = 0; this._.paused = true; if (this.media) { this._.listener = {}; bindEvents.call(this, this._.listener); } this._.stage = this._.engine.init(this.container); this._.stage.style.cssText += 'position:relative;pointer-events:none;'; this.resize(); this.container.appendChild(this._.stage); this._.space = {}; resetSpace(this._.space); if (!this.media || !this.media.paused) { seek.call(this); play.call(this); } return this; } /* eslint-disable no-invalid-this */ function destroy() { if (!this.container) { return this; } pause.call(this); this.clear(); this.container.removeChild(this._.stage); if (this.media) { unbindEvents.call(this, this._.listener); } for (var key in this) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(this, key)) { this[key] = null; } } return this; } var properties = ['mode', 'time', 'text', 'render', 'style']; /* eslint-disable no-invalid-this */ function emit(obj) { if (!obj || Object.prototype.toString.call(obj) !== '[object Object]') { return this; } var cmt = {}; for (var i = 0; i < properties.length; i++) { if (obj[properties[i]] !== undefined) { cmt[properties[i]] = obj[properties[i]]; } } cmt.text = (cmt.text || '').toString(); cmt.mode = formatMode(cmt.mode); cmt._utc = Date.now() / 1000; if (this.media) { var position = 0; if (cmt.time === undefined) { cmt.time = this.media.currentTime; position = this._.position; } else { position = binsearch(this.comments, 'time', cmt.time); if (position < this._.position) { this._.position += 1; } } this.comments.splice(position, 0, cmt); } else { this.comments.push(cmt); } return this; } /* eslint-disable no-invalid-this */ function show() { if (this._.visible) { return this; } this._.visible = true; if (this.media && this.media.paused) { return this; } seek.call(this); play.call(this); return this; } /* eslint-disable no-invalid-this */ function hide() { if (!this._.visible) { return this; } pause.call(this); this.clear(); this._.visible = false; return this; } /* eslint-disable no-invalid-this */ function clear$1() { this._.engine.clear(this._.stage, this._.runningList); this._.runningList = []; return this; } /* eslint-disable no-invalid-this */ function resize$1() { this._.stage.width = this.container.offsetWidth; this._.stage.height = this.container.offsetHeight; this._.engine.resize(this._.stage); this._.duration = this._.stage.width / this._.speed; return this; } var speed = { get: function() { return this._.speed; }, set: function(s) { if (typeof s !== 'number' || isNaN(s) || !isFinite(s) || s <= 0) { return this._.speed; } this._.speed = s; if (this._.stage.width) { this._.duration = this._.stage.width / s; } return s; } }; function Danmaku(opt) { opt && init$1.call(this, opt); } Danmaku.prototype.destroy = function() { return destroy.call(this); }; Danmaku.prototype.emit = function(cmt) { return emit.call(this, cmt); }; Danmaku.prototype.show = function() { return show.call(this); }; Danmaku.prototype.hide = function() { return hide.call(this); }; Danmaku.prototype.clear = function() { return clear$1.call(this); }; Danmaku.prototype.resize = function() { return resize$1.call(this); }; Object.defineProperty(Danmaku.prototype, 'speed', speed); export default Danmaku;
var vm = require("vm"); var path = require('path'); var _ = require('underscore'); var iv = require(path.normalize(__dirname + '/../helpers/inputsValidation')); var response = { success: function(data){ process.send({ type: "success", data: data }); }, error: function(err, code){ process.send({ type: "error", err: err, code: code }); }, progress: function(progress, message){ process.send({ type: "progress", progress: progress, message: message }); }, log: function(data){ process.send({ type: "log", message: data }); }, logObject: function(){ process.send({ type: "logObject", object: logObject }); } }; var component = process.argv[2]; var script = vm.createScript(component); var subscription = process.argv[5]; var logObject = JSON.parse(process.argv[6]); var incrementUsageUser = function(){ process.send({ type: "incrementUsageUser" }); } var dependencies = {}; dependencies.mailgun = require('mailgun-js'); dependencies.twilio = require('twilio'); dependencies.xero = require('xero'); dependencies.crypto = require('crypto'); dependencies.Lazy = require('lazy'); dependencies._l = require('lodash'); dependencies.IFTTTMaker = require('iftttmaker'); dependencies.clearbit = require('clearbit'); dependencies.stripe = require('stripe'); dependencies.mysql = require('mysql'); dependencies.request = require('request'); dependencies.Promise = require('promise'); // Promise library dependencies._ = _; // Underscore library dependencies.Buffer = Buffer; // Format the parameters var parameters = JSON.parse(process.argv[3]); var component_inputs = JSON.parse(process.argv[4]); var component_outputs = JSON.parse(process.argv[7]); var bypassVM = process.argv[8]; var missingParameters = []; var incorrectTypeParameters = []; for(var i = 0; i < component_inputs.length; i++) { var input = component_inputs[i]; if(!parameters.hasOwnProperty(input.name) && !input.is_optional){ missingParameters.push(input); }else{ if(parameters.hasOwnProperty(input.name)){ if(!iv.isValid(parameters[input.name], input.type) && !input.is_optional){ incorrectTypeParameters.push(input); }else{ parameters[input.name] = iv.format(parameters[input.name], input.type); } } } } var errorString; if(missingParameters.length){ errorString = "Missing Inputs "; for (var i = 0; i < missingParameters.length; i++) { var row = missingParameters[i]; if(i !== 0){ errorString += ", "; } errorString += "(" + row.type[row.type.length-1] + ")"+row.name; } logObject.log += errorString + "\n"; response.error({ error: errorString, missing: missingParameters, code: 102 }, 102); process.send(logObject); process.exit(1); }else if(incorrectTypeParameters.length){ errorString = "Incorrect type Inputs"; for (var i = 0; i < incorrectTypeParameters.length; i++) { var row = incorrectTypeParameters[i]; if(index !== 0){ errorString += ", "; } errorString += "(" + typeof(parameters[row.name]) + ")" + row.name + " - Expected: (" + row.type[row.type.length-1] + ")" + row.name; } logObject.log += errorString + "\n"; response.error({ error: errorString, incorrect : _.map(incorrectTypeParameters, function(row){ return { given: { name: row.name, value: parameters[row.name], type: typeof(parameters[row.name]) }, expected: row }; }), code: 101 }, 101); process.send(logObject); process.exit(1); }else{ // Everything is fine, we can execute var succeeded = false; var failed = false; var Output = {}; var sandbox = { success: function(data){ if(!succeeded){ if(typeof(data) === "object"){ Output = _.extend(data, Output); } // Save the usage of the FREE plan if(subscription == "earth"){ incrementUsageUser(); } // Verify that we have all of the expected Outputs and that their type is correct var missingParameters = []; var incorrectTypeParameters = []; for (var i = 0; i < component_outputs.length; i++) { var output = component_outputs[i]; if(!Output.hasOwnProperty(output.name)){ missingParameters.push(output); }else{ if(!iv.isValid(Output[output.name], output.type)){ incorrectTypeParameters.push(output); }else{ Output[output.name] = iv.format(Output[output.name], output.type); } } } var errorString; if(missingParameters.length){ failed = true; errorString = "Missing Outputs "; for (var i = 0; i < missingParameters.length; i++) { var row = missingParameters[i]; if(i !== 0){ errorString += ", "; } errorString += "(" + row.type[row.type.length-1] + ")"+row.name; } logObject.log += errorString + "\n"; response.error({ error: errorString, missing: missingParameters, code: 107 }, 107); response.logObject(); process.exit(1); }else if(incorrectTypeParameters.length){ failed = true; errorString = "Incorrect type Outputs"; for (var i = 0; i < incorrectTypeParameters.length; i++) { var row = incorrectTypeParameters[i]; if(i !== 0){ errorString += ", "; } errorString += "(" + typeof(Output[row.name]) + ")" + row.name + " - Expected: (" + row.type[row.type.length-1] + ")" + row.name; } logObject.log += errorString + "\n"; response.error({ error: errorString, incorrect : _.map(incorrectTypeParameters, function(row){ return { given: { name: row.name, value: Output[row.name], type: typeof(Output[row.name]) }, expected: row }; }), code: 106 }, 106); response.logObject(); process.exit(1); }else{ succeeded = true; var dataToAnswer = {}; if(typeof(data) == "object"){ dataToAnswer = _.extend(data, Output); }else if(typeof(data) == "undefined"){ dataToAnswer = Output; }else{ dataToAnswer = data; } response.success(dataToAnswer); response.logObject(); process.exit(1); } }else{ logObject.log += "success() has been called multiple times. Only one time is allowed!" + "\n"; response.log("success() has been called multiple times. Only one time is allowed!"); response.logObject(); } }, error: function(err, code){ if(!failed){ // Save the usage of the FREE plan if(subscription == "earth"){ incrementUsageUser(); } if(typeof(err) == "undefined"){ logObject.log += "No error message provided on call of error();" + "\n"; response.log("No error message provided on call of error();"); }else if(typeof(code) == "undefined"){ logObject.log += "No error code provided on call of error(); You must pass an error code as an integer as the second parameter of error(message, errorCode);" + "\n"; response.log("No error code provided on call of error();"); }else if(typeof(code) !== "number"){ logObject.log += "The error code passed to error(); must be an integer" + "\n"; response.log("The error code passed to error(); must be an integer"); }else if(code.toString().charAt(0) === "1" || code.toString().charAt(0) === "0"){ logObject.log += "The error code cannot start by a 1 or a 0, these are reserved numbers for Synchronise messages." + "\n"; response.log("The error code cannot start by a 1 or a 0, these are reserved numbers for Synchronise messages."); }else{ failed = true; logObject.log += err + "\n"; response.error(err, code); response.logObject(); process.exit(1); } }else{ logObject.log += "error() has been called multiple times. Only one time is allowed!" + "\n"; response.log("error() has been called multiple times. Only one time is allowed!"); response.logObject(); process.exit(1); } }, progress: function(progress, message){ logObject.log += "Progress: " + progress.toString() + " - Message: " + message.toString() + "\n"; response.progress(progress, message); }, console: { log : function(){ // Encapsulation of log for (var i = 0; i < arguments.length; i++) { var row = arguments[i]; if(typeof(row) == "object"){ row = JSON.stringify(row); } logObject.log += row + "\n"; response.log(row); } } }, Input: parameters, // Parameters coming from the client Output: Output }; if(!bypassVM){ script.runInNewContext(_.extend(dependencies, sandbox)); }else{ var success = sandbox.success; var error = sandbox.error; var progress = sandbox.progress; var console = sandbox.console; var Input = parameters; var Output = Output; var keysDeps = Object.keys(dependencies); for (var i = 0; i < keysDeps.length; i++) { global[keysDeps[i]] = dependencies[keysDeps[i]]; } eval(component); } process.on('uncaughtException', function(err) { response.log(err); logObject.log += err + "\n"; process.send(logObject); process.exit(1); }); }
/* jshint browser:true */ /* global angular */ angular.module('griddy', ['griddy.models', 'griddy.services', 'griddy.controllers', 'griddy.directives']); //, 'templates-main' angular.module('griddy.models', []); angular.module('griddy.services', []); angular.module('griddy.controllers', []); angular.module('griddy.directives', []);
'use strict'; describe('Directive: indexEntry', function () { // load the directive's module beforeEach(module('godocApp')); var element, scope; beforeEach(inject(function ($rootScope) { scope = $rootScope.$new(); })); it('should make hidden element visible', inject(function ($compile) { element = angular.element('<index-entry></index-entry>'); element = $compile(element)(scope); expect(element.text()).toBe('this is the indexEntry directive'); })); });
/* YOLOFly */ var posX = 320; var posY = 448; var deg = 0; var lastX = 0; var cursorX = 320; var fireballs = []; var ships = []; var expl = []; var stars = []; var ePosX = 320; var chargeLevel = 0; var HP = 100; var charging = false; var points = 0; var shield = 100; var shotNumber = 1; var difficulty = 1; var shots = 0; var lock = 9; var addedDiff = 0; var exp = 0; var pause = false; var mode = ''; var bgPos = 0; var kills = 0; var evolution = { } //Upgrades var upgrade = { 'hp': 0, 'shield': 0, 'speed': 0, 'damage': 0, 'points': 0, 'charge': 0, 'bomb': 0, 'shots': 0, 'shotSpeed': 0, 'shotSize': 0, }; function resetStats() { HP = 100; shield = 100; HP += upgrade.hp; shield += upgrade.shield; } resetStats(); function calculateAngle(fromX, fromY, toX, toY) { var angle = Math.atan2((toY - fromY), (toX - fromX)); return (angle * 180 / Math.PI) + 90; } function moveStuff() { starfield(); if (pause) { echo('energy', 'GAME PAUSED. HIT \'P\' TO RESUME'); doc('pause').style.display = 'inline'; } if (!pause) doc('pause').style.display = 'none'; if (HP <= 0 && doc('gameover').style.display != 'inline') { shopList(); sship.style.opacity = 0; var gover = setTimeout(function() { for (fb in fireballs) kill(fb); for (fb in ships) kill(fb, 'sp'); doc('gameover').style.display = 'inline'; },3000); } if (HP <= 0 || pause) return; if (HP > 0) { //Move spaceship sship.style.opacity = 1; var realPosX = posX + 16; var diff = Math.abs(realPosX - cursorX); diff = Math.floor(diff/5)+1; diff += upgrade.speed; sship.className = 'spaceship'; var scal = 0.5; if (position == 'outside') scal = 1.0; if (position == 'home') scal = 2.0; sship.style.transform = 'scale('+scal+') rotate('+deg+'deg)'; if (realPosX != cursorX) { sship.className = 'spaceship flying'; posX = (realPosX < cursorX) ? posX + diff : posX - diff; } if (posX < 0) posX = 0; if (posX > 640) posX = 640; sship.style.left = posX+'px'; lastX = cursorX; if (!posY) posY = 0; var realPosY = posY + 16; var diff = Math.abs(realPosY - cursorY); diff = Math.floor(diff/5)+1; diff += upgrade.speed; if (realPosY != cursorY) { sship.className = 'spaceship flying'; posY = (realPosY < cursorY) ? parseInt(posY) + parseInt(diff) : parseInt(posY) - parseInt(diff); } if (posY < 0) posY = 0; if (posY > 480) posY = 480; sship.style.top = posY+'px'; lastY = cursorY; var a = calculateAngle(realPosX, realPosY, cursorX, cursorY); if (a != 90) { var dir = deg - a; deg = a; } } var me = { 'xx': posX, 'yy': posY, 'weight': 32, } //Move fireballs for (x in fireballs) { var fb = fireballs[x]; var el = fb.element; fb.age = (!fb.age) ? 1 : fb.age++; //fb.motionY += 0.005; fb.xx += fb.motionX*3; fb.yy += fb.motionY*3; var mot = fb.age / 10; el.style.top = fb.yy+'px'; el.style.left = fb.xx+'px'; if (fb.xx >= 740 || fb.xx <= -100) kill(x, 'fb'); if (fb.yy >= 580 || fb.yy <= -100) kill(x, 'fb'); var ali = el.className; if (ali == 'enemyBullet' && HP <= 0) continue; if (ali == 'powerup' && collision(fb, me)) { var targ = fb.id; shop(targ, 0, 1); kill(x); } if (ali == 'enemyBullet' && collision(fb, me)) { if (shield > 0) { shield -= Math.floor(fb.weight*2); if (shield <= 0) shield = 0; playSound('sound/shield.wav'); } else { HP -= Math.floor(fb.weight); playSound('sound/shot1.wav'); } var ccc = setTimeout(function() { }, 500); me.weight = 16; if (HP <= 0) explode(me.xx, me.yy); kill(x); } if (mode == 'firework' && ali == 'superChargedAllyBullet' && fb.yy <= 8) { bomb(fb, 5, 'dark', 1); kill(x); } if (ali == 'allyBullet' || ali == 'chargedAllyBullet' || ali == 'superChargedAllyBullet' || ali == 'nightmareAllyBullet') { for (c in ships) { ships[c].lifespan += 1; if (collision(ships[c], fb)) { var dmg = (ali == 'allyBullet') ? 10*Math.random() : fb.weight; dmg += upgrade.damage; ships[c].hp -= dmg; if (ships[c].hp <= 0) { //Ship killed kills += 1; playSound('sound/explode2.wav'); var bonus = ships[c].hpx; kill(c, 'sp'); dmg += (bonus + upgrade.points + difficulty)/3; points += Math.ceil(dmg); exp += Math.floor(dmg/10); } if (ali == 'superChargedAllyBullet' && fb.weight > 4) { var fireworks = (mode == 'firework'); if (!fireworks) bomb(fb, 5); if (fireworks) bomb(fb, 5, 'dark', fireworks); } if (ali == 'chargedAllyBullet' || ali == 'nightmareAllyBullet') { fb.motionX *= 1.1; fb.motionY *= 1.1; } else { kill(x); } } } for (c in fireballs) { if (fireballs[c].element.className != 'enemyBullet') continue; if (collision(fireballs[c], fb)) { var cc = (difficulty > 2) ? difficulty/2 : 1; if (rand(1,cc) == 1 && fb.weight >= fireballs[c].weight) kill(c); } } } } for (s in ships) { var sp = ships[s]; var el = sp.element; var me = { 'xx': posX, 'yy': posY, 'weight': 32, } if (sp.gps == true) { gps(sp, me); } if (collision(sp, me)) kill(s, 'sp'); if (sp.xx <= 0) sp.xx = 0; if (sp.xx >= 640) sp.xx = 640; sp.motionY += 0.012; var motionY = sp.motionY; var movez = motionY/sp.heavy if (sp.yy >= 192 && movez > 0) sp.motionY -= 0.0055; if (sp.yy >= 288 && movez > 0) sp.motionY -= 0.012; if (sp.yy >= 384) sp.motionY += 0.025; if (sp.fixed) { if (sp.yy > 240) movez *= -1.4; if (sp.yy < 240) movez *= 1.4; if (sp.xx > 320) { sp.motionR *= 1+(Math.random()*0.01); sp.motionL *= 1-(Math.random()*0.01); } if (sp.xx < 320) { sp.motionR *= 1-(Math.random()*0.01); sp.motionL *= 1+(Math.random()*0.01); } } sp.yy += movez; el.style.top = sp.yy+'px'; el.style.left = sp.xx+'px'; var rmax = 100+(100/difficulty); //No wall collision if (sp.xx >= 512) sp.motionR += 0.1; if (sp.xx <= 128) sp.motionL += 0.1; if (sp.xx >= 640 || sp.xx <= 0) kill(s, 'sp', 1); if (sp.yy >= 480 || sp.yy <= 0) kill(s, 'sp', 1); } var rmax = 35+(58/difficulty); if (rand(1,rmax) == 1) autoSpawn(); charge(); if (chargeLevel < 10) { beam = realDrawBar(Math.floor(chargeLevel), 10)+' SHOT' } if (chargeLevel >= 10 && chargeLevel < 30) { beam = realDrawBar(Math.floor(chargeLevel)-10, 20)+' MISSILE' } if (chargeLevel >= 30) { beam = realDrawBar(Math.floor(chargeLevel)-30, 20)+' BURST' } if (chargeLevel >= 50) { beam = realDrawBar(50,50)+' NUKE' } if (shield > 0) ene = 'SHIELD'; if (shield <= 0) ene = 'ENERGY'; left = (shield > 0) ? shield+'/'+(100 + parseInt(upgrade.shield)) : HP+'/'+(100 + parseInt(upgrade.hp)); //echo('energy', left+realDrawBar(HP,100+upgrade.hp)+realDrawBar(shield,100+upgrade.shield)+' '+ene+' | '+beam+' | '+points+' POINTS<br><br>ENEMY RANK '+difficulty.toString(36).toUpperCase()); } function gps(from, to) { var value = 0.01; if (from.xx > to.xx) from.motionR += (value*Math.random())/from.heavy; if (from.xx < to.xx) from.motionL += (value*Math.random())/from.heavy; } function charge() { var ch = 0.12; ch += upgrade.charge*5; if (charging) chargeLevel += ch; if (lock == 0 && chargeLevel >= 10) chargeLevel = 9.9; if (lock == 1 && chargeLevel >= 30) chargeLevel = 29.9; if (lock == 2 && chargeLevel >= 50) chargeLevel = 49.9; var cL = Math.round(chargeLevel*10)/10 % 5; if (charging && cL == 0) playSound('sound/load.wav'); } function laser(from) { for (var i = 0; i < 100; i++) { fireballs[fireballs.length] = new fireball('dark', from, 'laser'); } } function bomb(fromy, strength, variation, fwork) { var strength = 3; strength = (variation == 'dark' || variation == 'harmless') ? rand(6,13) : 3; if (fromy.type == 'bomb2') strength += rand(1,8); if (fromy.type == 'bomb3') strength += rand(2,16); if (fromy.type == 'test') strength += 500; if (!variation) { var add = rand(0,(upgrade.bomb/10)); strength+= rand(0,add); var strength = rand(3,strength); } if (fwork) strength += rand(4,8) + upgrade.bomb; for (i = 0; i < strength; i++) { if (fromy.weight == 1 && !fromy.dark) break; var vare = (variation == 'dark' || fromy.dark) ? 'dark' : 'bomb'; if (variation == 'harmless' || fwork) vare = 'harmless'; fireballs[fireballs.length] = new fireball(vare, fromy, fromy.strength, fwork); } } function explosionPhase(source, phase) { for (ep in expl) { var eee = expl[ep]; var elz = eee.element; eee.span -= 10; if (eee.span <= 99) { elz.style.opacity = 0.5; elz.style.boxShadow = '0 0 10px #fc8'; } if (eee.span <= 50) { elz.style.opacity = 0.1; elz.style.boxShadow = '0 0 100px #fff'; } if (eee.span <= 25) { elz.style.opacity = 0; } if (eee.span <= 0) { doc('container').removeChild(elz); expl.splice(ep, 1); } } } function kill(id, arr, silent) { if (arr == 'star') { doc('container').removeChild(stars[id].element); stars.splice(id, 1); return; } if (arr == 'sp') { if (!evolution[ships[id].type] || ships[id].lifespan > evolution[ships[id].type].lifespan) { //Ship evolves var tip = ships[id].type; if (rand(1,difficulty) == 1) addedDiff += 1; evolution[tip] = { 'customValueV': ships[id].customValueV, 'customValueW': ships[id].customValueW, 'customValueX': ships[id].customValueX, 'hpx': ships[id].hpx, 'motionL': ships[id].motionL, 'motionR': ships[id].motionR, 'motionY': ships[id].motionY, 'lifespan': ships[id].lifespan, 'strength': ships[id].strength, 'generation': ships[id].generation, } } if (!silent) { var hx = ships[id].xx; var hy = ships[id].yy; var ht = ships[id].fixed; var nu = expl.length; if (ht) { var xxx = setTimeout(function() { explode(hx, hy, 16) },500); var yyy = setTimeout(function() { explode(hx, hy, 24) },1000); var zzz = setTimeout(function() { explode(hx, hy, 32) },2000); } //expl[nu] = new explosion(ships[id].xx, ships[id].yy); } doc('container').removeChild(ships[id].element); ships.splice(id, 1); return; } if (!fireballs[id]) return; if (fireballs[id].element) doc('container').removeChild(fireballs[id].element); fireballs.splice(id, 1); } function randie() { return Math.random()*red(-1,1); } function spawn(type) { return; ships[ships.length] = new ship(type); } function autoSpawn() { //Backup enemy if (ships.length < 2) spawn('enemy'); if (rand(1,2) == 1 && difficulty < 12) spawn('bomb'); if (rand(1,4) == 1 && difficulty > 1) spawn('enemy'); if (rand(1,8) == 1 && difficulty > 2) spawn('croissant'); if (rand(1,16) == 1 && difficulty > 3) spawn('bomber'); if (rand(1,13) == 1 && difficulty > 5 && difficulty < 12) spawn('sat'); //Tier 8 if (rand(1,20) == 1 && difficulty > 12 && difficulty < 140) spawn('sat2'); if (rand(1,128) == 1 && difficulty > 18) spawn('boss'); if (rand(1,9) == 1 && difficulty > 27 && difficulty < 62) spawn('bomb2'); //Tier 41 if (rand(1,41) == 1 && difficulty > 62) spawn('bomb3'); //Tier 93 if (rand(1,30) == 1 && difficulty > 140) spawn('sat3'); } function ship(type, whereX, whereY) { if (!type) type = read([ 'enemy', 'croissant', 'bomb', 'bomber', 'sat', 'sat2', 'boss', 'bomb2', 'bomb3', 'sat3', ]); var arrayHP = { 'enemy': 4, 'croissant': 8, 'bomb': 2, 'bomber': 16, 'sat': 13, 'sat2': 20, 'boss': 128, 'bomb2': 9, 'bomb3': 41, 'sat3': 30, //Testing stuff 'test': 0, } var baseHP = arrayHP[type]; this.lifespan = 0; this.type = type; //Evolving stats this.customValueX = 128*Math.random()+128; this.customValueV = 128*Math.random()+128; this.customValueW = 128*Math.random()+128; this.hpx = baseHP * (kills/10 + (difficulty*Math.random())); this.motionL = Math.random()*0.8; this.motionR = Math.random()*0.8; this.motionY = 5; this.strength = 4 + (difficulty*Math.random()); this.generation = 1; //Mutate var ev = evolution[this.type]; if (ev) { this.customValueX = (this.customValueX + ev.customValueX) / 2; this.customValueV = (this.customValueV + ev.customValueV) / 2; this.customValueW = (this.customValueW + ev.customValueW) / 2; this.hpx = (this.hpx + ev.hpx) / 2; this.motionL = (this.motionL + ev.motionL) / 2; this.motionR = (this.motionR + ev.motionR) / 2; this.motionY = (this.motionY + ev.motionY) / 2; this.strength = (this.strength + ev.strength) / 2; this.generation = ev.generation + 1; } this.hp = this.hpx; this.weight = 32; if (type == 'bomber' || type == 'boss') this.weight = 64; this.xx = rand(0,640); this.yy = 0; if (type == 'test') { this.xx = 320; this.yy = 240; } this.heavy = 1; if (type == 'bomb2') this.strength += 3; if (type == 'bomb3') this.strength += 6; if (type == 'bomber') { this.motionL /= 3; this.motionR /= 3; this.strength = 16; this.heavy = 3; } //Peaceful mode: Ship doesn't attack this.peace = false; //Powerup chance this.pchance = 1; if (type == 'sat' || type == 'sat2' || type == 'sat3') { this.peace = true; if (type == 'sat') this.pchance = 2; if (type == 'sat2') this.pchance = 3; if (type == 'sat3') this.pchance = 4; this.motionL /= 4; this.motionR /= 4; this.heavy = 4; } if (type == 'boss') { this.strength = 8; this.heavy = 1.5; this.fixed = 1; } this.bomb = (type == 'bomb' || type == 'bomb2' || type == 'bomb3' || type == 'test') ? 1 : 0; if (rand(1,10) == 1) this.gps = true; if (type == 'bomb' || type == 'bomb2' || type == 'bomb3') this.gps = true; this.element = document.createElement('div'); this.element.className = 'enemyShip'; this.element.style.backgroundImage = 'url("img/enemy.png")'; this.element.style.top = this.yy+'px'; this.element.style.left = this.xx+'px'; if (type == 'bomber' || type == 'boss') { this.element.style.width = '64px'; this.element.style.height = '64px'; } doc('container').appendChild(this.element); } function explosion(whereX, whereY, force) { this.span = 100; this.xx = whereX; this.yy = whereY; this.element = document.createElement('div'); this.element.className = 'explosion'; this.element.style.top = this.yy+'px'; this.element.style.left = this.xx+'px'; var f = 24; if (force) f += force; if (!force) var f = rand(12,32); this.element.style.width = f+'px'; this.element.style.height = f+'px'; doc('container').appendChild(this.element); } function explode(whereX, whereY, force) { var exmax = rand(3,6); for (exx = 0; exx < exmax; exx++) { expl[expl.length] = new explosion(whereX+rand(-32,32), whereY+rand(-32,32), force); } } function spiro(cv, cw, cx) { HP = (HP + 50) * 1.5; shield = (shield + 50) * 1.5; var ll = ships.length; spawn('test', 320, 240); sh = ships[ll]; sh.customValueV = cv; sh.customValueW = cw; sh.customValueX = cx; kill(ll, 'sp'); } function fireball(type, from, strength, fworkMode) { if (type == 'customEnemy') { type = 'enemy'; var custom = 1; } if (type != 'enemy') shots += 1; var chargeVariation = (chargeLevel/5)+1; this.weight = 4; this.xx = posX+16; this.yy = posY+16; this.motionX = Math.random()*rand(-0.15,0.15); this.motionY = -4; this.customValueV = Math.random()*100; this.customValueW = Math.random()*100; this.customValueX = Math.random()*100; this.element = document.createElement('div'); this.element.className = 'allyBullet'; if (chargeLevel > 10 && !from) { this.motionY = -8; this.element.className = 'chargedAllyBullet'; this.weight = 16; } if (chargeLevel >= 30 && !from) { this.element.className = 'superChargedAllyBullet'; this.weight = 32; this.motionY = -2; } if (chargeLevel >= 50 && !from) { this.element.className = 'nightmareAllyBullet'; this.weight = 8; this.element.width = '8px'; } if (type == 'enemy' || type == 'dark' || type == 'harmless') { if (strength) { this.weight = strength; } if (from.strength > strength) this.weight = from.strength; this.element.className = 'enemyBullet'; this.motionY = 2+Math.random(); this.motionX *= Math.random(); if (type == 'dark' || type == 'harmless') { this.motionX = ((Math.random()*rand(-1,1))+0.01)*3; this.motionY = ((Math.random()*rand(-1,1))+0.01)*3; /* if (strength == 'laser') { this.yy = from.yy + fireballs.length/50; this.motionX = 0; this.motionY = 6+(fireballs.length/50); this.weight = 1; this.element.style.backgroundColor = '#fee'; this.element.style.boxShadow = '0 0 8px #faa'; } */ } if (strength > 4) { var motStre = strength / 4; this.motionX /= motStre; this.motionY /= motStre; } var lev = Math.floor(from.hp/10); if (!lev || lev == NaN) lev = 0; //this.weight = 4+(lev*Math.random()); this.xx = from.xx+16; if (strength != 'laser') this.yy = from.yy; if (!this.xx) this.xx = rand(0,640); if (!this.yy) this.yy = rand(0,480); if (type == 'harmless') { this.motionX *= 3; this.motionY *= 3; this.element.className = 'explosionFireball'; } var fidd = (posX - this.xx) / 100; this.motionX = fidd+(Math.random()*red(-0.1, 0.1)); var fidd = (posY - this.yy) / 100; this.motionY = fidd+(Math.random()*red(-0.1, 0.1)); } if (type == 'bomb') { this.motionY = Math.sin(fireballs.length); this.motionX = Math.cos(fireballs.length); if (this.motionY > 0) this.motionY *= -1; var speedMod = (upgrade.shotSpeed/10)+1; this.motionY *= speedMod; this.motionX *= speedMod; this.xx = from.xx; this.yy = from.yy; var originalWeight = from.weight; this.weight = from.weight / 3; this.weight += 2; this.element.className = 'superChargedAllyBullet'; } if (type == 'dark') { this.dark = true; this.element.style.backgroundColor = '#f40'; this.element.style.boxShadow = '0 0 8px #f30'; } if (type == 'powerup') { this.xx = from.xx; this.yy = from.yy; this.id = rand(0,9); this.motionX = 0; this.motionY = 0.05; this.element.className = 'powerup'; var img = 'powerup.png'; if (this.id == 1) var img = 'powerup1.png'; if (this.id == 2) var img = 'powerup2.png'; if (this.id == 3) var img = 'powerup3.png'; if (this.id == 4) var img = 'powerup4.png'; if (this.id == 5) var img = 'powerup5.png'; if (this.id == 6) var img = 'powerup6.png'; if (this.id == 7) var img = 'powerup7.png'; if (this.id == 8) var img = 'powerup8.png'; if (this.id == 9) var img = 'powerup9.png'; this.element.style.backgroundImage = 'url("img/'+img+'")'; this.weight = 16; } if (type == 'nightmare') { this.motionX = Math.sin(fireballs.length)*4; this.motionY = Math.cos(fireballs.length)*4; this.weight = 8; } if (this.element.className == 'allyBullet' || this.element.className == 'chargedAllyBullet' || this.element.className == 'superChargedAllyBullet') { var base = 2; if (this.element.className == 'chargedAllyBullet') base = 4; base += upgrade.shotSize/2; var we = 2; we += upgrade.shotSize/2; base *= chargeVariation; base = Math.ceil(base); we *= chargeVariation; if (type != 'bomb' && type != 'harmless') this.weight = Math.ceil(we); var speedMod = (upgrade.shotSpeed/10)+1; this.motionY *= speedMod; } if (this.element.className == 'allyBullet' && shotNumber) { this.motionX *= shotNumber; } this.element.style.top = this.yy+'px'; this.element.style.left = this.xx+'px'; this.element.style.width = this.weight+'px'; this.element.style.height = this.weight+'px'; if (fworkMode || type == 'firework') { console.log('fireworks'); this.element.className = 'allyBullet'; var rrr = rand(0,255); var ggg = rand(0,255); var bbb = rand(0,255); var col = 'rgb('+rrr+','+ggg+','+bbb+')' this.weight = 4; var hhh = rand(1,8); this.element.style.width = hhh+'px'; this.element.style.height = hhh+'px'; this.element.style.backgroundColor = col; this.element.style.boxShadow = '0 0 16px '+col; } if (from && this.element.className == 'enemyBullet' && from.customValueV) { var rrr = Math.floor(from.customValueV); var ggg = Math.floor(from.customValueW); var bbb = Math.floor(from.customValueX); var col = 'rgb('+rrr+','+ggg+','+bbb+')'; this.element.style.backgroundColor = col; this.element.style.boxShadow = '0 0 8px '+col; } if (mode == 'firework' && this.element.className == 'superChargedAllyBullet') { this.element.style.width = '4px'; this.element.style.height = '16px'; this.element.style.backgroundColor = '#fc0'; this.element.style.boxShadow = '0 0 32px #f80' } if (type == 'harmless' || custom || type == 'dark' || (type == 'firework' || fworkMode)) { var t = fireballs.length; //Default: 0.8, 1, 0.02 if (from.customValueW) { var p = 0.1; var R = from.customValueW/20; var r = from.customValueX/20; } this.motionX = (R-r)*Math.cos(t) + p*Math.cos((R-r)*t/r) //(W-X)*cos(t) + V*cos((W-X)*t/X) this.motionY = (R-r)*Math.sin(t) - p*Math.sin((R-r)*t/r) } if (strength == 'laser') { this.yy = from.yy + fireballs.length/50; this.motionX = 0; this.motionY = 6+(fireballs.length/50); this.weight = 1; this.element.style.backgroundColor = '#fee'; this.element.style.boxShadow = '0 0 8px #faa'; } doc('container').appendChild(this.element); } function collision(from, to) { var c1 = from.xx < to.xx + to.weight; var c2 = from.xx + from.weight > to.xx; var c3 = from.yy < to.yy + to.weight; var c4 = from.yy + from.weight > to.yy; if (c1 && c2 && c3 && c4) return 1; } function moveStars() { if (pause) return; for (ms in stars) { } } function star(randie) { this.weight = Math.random()*3; this.xx = rand(0,640); this.yy = 0; if (randie) this.yy = rand(0,480); this.motionX = Math.random()*rand(-0.1,0.1); this.motionY = 6; this.element = document.createElement('div'); this.element.className = 'ambientStar'; this.element.style.top = this.yy+'px'; this.element.style.left = this.xx+'px'; this.element.style.opacity = 1*Math.random(); this.element.style.width = this.weight+'px'; this.element.style.height = this.weight+'px'; doc('container').appendChild(this.element); } function starfield() { //stars[stars.length] = new star(); } function playSound(path) { return; var eez = document.createElement('audio'); eez.innerHTML = '<source src="'+path+'">'; doc('aud').appendChild(eez); eez.play(); //var t4 = setTimeout(function() {aud.innerHTML = '';}, 10000); } function shop(item, peek, power) { var upgradez = [ {'name': 'More ENERGY', 'tip': 'Increases your spaceship max ENERGY when the shield wears out.', 'price': 25, 'increase': 30, 'stat': 'hp'}, {'name': 'More SHIELD', 'tip': 'Increases the strength of the SHIELD that protects the spaceship against enemy fire.', 'price': 20, 'increase': 50, 'stat': 'shield'}, {'name': 'Fast Flight', 'tip': 'Increases your flight speed. Caution! Higher speeds may be unsafe!', 'price': 15, 'increase': 0.5, 'stat': 'speed'}, {'name': 'Empowered Shots', 'tip': 'Your shots, missiles and bursts deal more damage.', 'price': 25, 'increase': 0.4, 'stat': 'damage'}, {'name': 'Fortune Hunter', 'tip': 'Gets more points when destroying enemy ships.', 'price': 50, 'increase': 3, 'stat': 'points'}, {'name': 'Fast Charge', 'tip': 'Your weapon charges faster, decreasing time needed to shot missiles and bursts.', 'price': 25, 'increase': 0.05, 'stat': 'charge'}, {'name': 'Unavoidable Explosion', 'tip': 'Your bursts release more explosive particles, thus dealing more damage in a wide area.', 'price': 100, 'increase': 1, 'stat': 'bomb'}, {'name': 'Double-Shot', 'tip': 'Increases the number of shots your spaceship will launch on each attack, only valid for SHOT.', 'price': 80, 'increase': 1, 'stat': 'shots'}, {'name': 'Quantum Speed', 'tip': 'All of your projectiles move faster.', 'price': 30, 'increase': 2, 'stat': 'shotSpeed'}, {'name': 'Energy Overflow', 'tip': 'Increases average size and area of effect of your SHOTS and MISSILES.', 'price': 40, 'increase': 1, 'stat': 'shotSize'}, ]; if (peek == 'len') return upgradez.length; var ii = upgradez[item]; var priceLevel = (upgrade[ii.stat] / ii.increase)+1; if (peek == 'lev') return priceLevel; var price = Math.floor(ii.price * Math.pow(1.5, priceLevel)); if (peek) { return [ii.name, ii.tip, price]; } if (points >= price || power) { if (!power) points -= price; upgrade[ii.stat] += upgradez[item].increase; if (item == 0) HP += upgradez[item].increase; if (item == 1) shield += upgradez[item].increase; shopList(); } if (power) { echo('extra', 'POWER UP! '+ii.name+' '+'('+ii.tip+')'); var lll = setTimeout(function() {echo('extra', '')}, 8000); } } function shopList() { var le = '<br><br>'; for (li = 0; li < shop(0, 'len'); li++) { var sli = shop(li, 1); var op = (points >= sli[2]) ? 1 : 0.1; if (points < sli[2] || rand(0,1) == 1) continue; le += '<div class="button" style="opacity: '+op+'" onclick="shop('+li+')">'+sli[0]+'('+sli[2]+' points)<br>'+sli[1]+'</div>'; } difficulty = 1+addedDiff; updateStats(); echo('shoppie', le); } function updateStats() { var stuff = [ ['Max ENERGY: ', 100+upgrade.hp], ['Max SHIELD: ', 100+upgrade.shield], ['Max Speed (px/sec): ', (upgrade.speed+13.8)*100], ['Additional Damage per Shot: ', upgrade.damage], ['Additional Points per Kill: ', upgrade.points/3], ['Charge Multiplier: ', upgrade.charge*5], ['Number of Burst Particles: ', 3+(upgrade.bomb/10)], ['Shots per attack: ', upgrade.shots+1], ['Projectile Acceleration (px/sec): ', (upgrade.shotSpeed/10)+1], ['Projectile Size Modifier: ', upgrade.shotSize/2] ]; var l = 'Points: '+points+'<br><br>'; for (var uss = 0; uss < stuff.length; uss++) { l += '<li>'+stuff[uss][0]+' '+stuff[uss][1].toFixed(3)+' '+'<span class="button" '; l += 'onclick="shop('+uss+')">+</span>'+'('+shop(uss, 1)[2]+' points)<br><br>'; } l += 'Secondary Weapon: <br>'; l += '<span class="button" onclick="lock = 0">None</span>'; l += '<span class="button" onclick="lock = 1">Missile</span>'; l += '<span class="button" onclick="lock = 2; mode = 0">Burst</span>'; l += '<span class="button" onclick="lock = 2; mode = \'firework\'">Fireworks</span>'; l += '<span class="button" onclick="lock = 3">Nuke</span>'; echo('statList', l); } function powerUp(from) { fireballs[fireballs.length] = new fireball('powerup', from); } //Key press function toKeyCode(key) { var key = key || window.event; var cCode = key.charCode || key.which; return cCode; } document.onkeypress = function(key) { var key = key || window.event; var cCode = key.charCode || key.which; var keyPress = String.fromCharCode(cCode); var kee = String.fromCharCode(toKeyCode(key)); if (kee == 'p' || kee == 'P') { warpToWorldMap(); } if (kee.toLowerCase() == 'm') { maggotCare(); } } starfield(); var t = setInterval(moveStuff, 30); var t2 = setInterval(explosionPhase, 100); var t3 = setInterval(moveStars, 180);
var helper = require('../spec_helper'), request = require('request'); describe('Cloudscraper', function() { var sandbox, url = 'http://example-site.dev/path/', requestedPage = helper.getFixture('requested_page.html'), headers = {'User-Agent': 'Chrome'}, // Since request.jar returns new cookie jar instance, create one global instance and then stub it in beforeEach jar = request.jar(), // Since request.defaults returns new wrapper, create one global instance and then stub it in beforeEach requestDefault = request.defaults({jar: jar}), cloudscraper; before(function() { helper.dropCache(); }); beforeEach(function () { sandbox = sinon.sandbox.create(); sandbox.stub(request, 'jar').returns(jar); sandbox.stub(request, 'defaults').returns(requestDefault); cloudscraper = require('../../index'); // since cloudflare requires timeout, the module relies on setTimeout. It should be proprely stubbed to avoid ut running for too long this.clock = sinon.useFakeTimers(); }); afterEach(function () { sandbox.restore(); this.clock.restore(); }); it('should return requested page, if cloudflare is disabled for page', function(done) { var expectedResponse = { statusCode: 200 }; // Stub first call, which request makes to page. It should return requested page sandbox.stub(requestDefault, 'get') .withArgs({method: 'GET', url: url, headers: headers, encoding: null, realEncoding: 'utf8'}) .callsArgWith(1, null, expectedResponse, requestedPage); cloudscraper.get(url, function(error, response, body) { expect(error).to.be.null(); expect(body).to.be.equal(requestedPage); expect(response).to.be.equal(expectedResponse); done(); }, headers); }); it('should not trigged any error if recaptcha is present in page not protected by CF', function(done) { var expectedResponse = { statusCode: 200 }; var pageWithCaptcha = helper.getFixture('page_with_recaptcha.html'); sandbox.stub(requestDefault, 'get') .withArgs({method: 'GET', url: url, headers: headers, encoding: null, realEncoding: 'utf8'}) .callsArgWith(1, null, expectedResponse, pageWithCaptcha); cloudscraper.get(url, function(error, response, body) { expect(error).to.be.null(); expect(body).to.be.equal(pageWithCaptcha); expect(response).to.be.equal(expectedResponse); done(); }, headers); }); it('should resolve challenge (version as on 21.05.2015) and then return page', function(done) { var jsChallengePage = helper.getFixture('js_challenge_21_05_2015.html'), response = helper.fakeResponseObject(503, headers, jsChallengePage, url), stubbed; // Cloudflare is enabled for site. It returns a page with js challenge stubbed = sandbox.stub(requestDefault, 'get') .withArgs({method: 'GET', url: url, headers: headers, encoding: null, realEncoding: 'utf8'}) .callsArgWith(1, null, response, jsChallengePage); // Second call to request.get will have challenge solution // It should contain url, answer, headers with Referer stubbed.withArgs({ method: 'GET', url: 'http://example-site.dev/cdn-cgi/l/chk_jschl', qs: { 'jschl_vc': '89cdff5eaa25923e0f26e29e5195dce9', 'jschl_answer': 633 + 'example-site.dev'.length, // 633 is a answer to cloudflares js challenge in this particular case 'pass': '1432194174.495-8TSfc235EQ' }, headers: { 'User-Agent': 'Chrome', 'Referer': 'http://example-site.dev/path/' }, encoding: null, realEncoding: 'utf8' }) .callsArgWith(1, null, response, requestedPage); cloudscraper.get(url, function(error, response, body) { expect(error).to.be.null(); expect(body).to.be.equal(requestedPage); expect(response).to.be.equal(response); done(); }, headers); this.clock.tick(7000); // tick the timeout }); it('should resolve challenge (version as on 09.06.2016) and then return page', function(done) { var jsChallengePage = helper.getFixture('js_challenge_09_06_2016.html'), response = helper.fakeResponseObject(503, headers, jsChallengePage, url), stubbed; // Cloudflare is enabled for site. It returns a page with js challenge stubbed = sandbox.stub(requestDefault, 'get') .withArgs({method: 'GET', url: url, headers: headers, encoding: null, realEncoding: 'utf8'}) .callsArgWith(1, null, response, jsChallengePage); // Second call to request.get will have challenge solution // It should contain url, answer, headers with Referer stubbed.withArgs({ method: 'GET', url: 'http://example-site.dev/cdn-cgi/l/chk_jschl', qs: { 'jschl_vc': '346b959db0cfa38f9938acc11d6e1e6e', 'jschl_answer': 6632 + 'example-site.dev'.length, // 6632 is a answer to cloudflares js challenge in this particular case 'pass': '1465488330.6-N/NbGTg+IM' }, headers: { 'User-Agent': 'Chrome', 'Referer': 'http://example-site.dev/path/' }, encoding: null, realEncoding: 'utf8' }) .callsArgWith(1, null, response, requestedPage); cloudscraper.get(url, function(error, response, body) { expect(error).to.be.null(); expect(body).to.be.equal(requestedPage); expect(response).to.be.equal(response); done(); }, headers); this.clock.tick(7000); // tick the timeout }); it('should make post request with body as string', function(done) { var expectedResponse = { statusCode: 200 }, body = 'form-data-body', postHeaders = headers; postHeaders['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; postHeaders['Content-Length'] = body.length; // Stub first call, which request makes to page. It should return requested page sandbox.stub(requestDefault, 'post') .withArgs({method: 'POST', url: url, headers: postHeaders, body: body, encoding: null, realEncoding: 'utf8'}) .callsArgWith(1, null, expectedResponse, requestedPage); cloudscraper.post(url, body, function(error, response, body) { expect(error).to.be.null(); expect(body).to.be.equal(requestedPage); expect(response).to.be.equal(expectedResponse); done(); }, headers); }); it('should make post request with body as object', function(done) { var expectedResponse = { statusCode: 200 }, rawBody = {a: '1', b: 2}, encodedBody = 'a=1&b=2', postHeaders = headers; postHeaders['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; postHeaders['Content-Length'] = encodedBody.length; // Stub first call, which request makes to page. It should return requested page sandbox.stub(requestDefault, 'post') .withArgs({method: 'POST', url: url, headers: postHeaders, body: encodedBody, encoding: null, realEncoding: 'utf8'}) .callsArgWith(1, null, expectedResponse, requestedPage); cloudscraper.post(url, rawBody, function(error, response, body) { expect(error).to.be.null(); expect(body).to.be.equal(requestedPage); expect(response).to.be.equal(expectedResponse); done(); }, headers); }); it('should return raw data when encoding is null', function(done) { var expectedResponse = { statusCode: 200 }; var requestedData = new Buffer('R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==', 'base64'); sandbox.stub(requestDefault, 'get') .withArgs({method: 'GET', url: url, headers: headers, encoding: null, realEncoding: null}) .callsArgWith(1, null, expectedResponse, requestedData); var options = { method: 'GET', url: url, encoding: null, headers: headers }; cloudscraper.request(options, function(error, response, body) { expect(error).to.be.null(); expect(response).to.be.equal(expectedResponse); expect(body).to.be.equal(requestedData); done(); }); }); it('should set the given cookie and then return page', function(done) { var jsChallengePage = helper.getFixture('js_challenge_cookie.html'), response = helper.fakeResponseObject(200, headers, jsChallengePage, url), stubbed; // Cloudflare is enabled for site. // It returns a redirecting page if a (session) cookie is unset. sandbox.stub(requestDefault, 'get', function fakeGet(options, cb) { if (options.url === url) { var cookieString = jar.getCookieString(url); if (cookieString === 'sucuri_cloudproxy_uuid_575ef0f62=16cc0aa4400d9c6961cce3ce380ce11a') { cb(null, response, requestedPage); } else { cb(null, response, jsChallengePage); } } else { cb(new Error("Unexpected request")); } }); cloudscraper.get(url, function(error, response, body) { expect(error).to.be.null(); expect(body).to.be.equal(requestedPage); done(); }, headers); }); });
var events = require('events'); var util = require('util'); var _ = require('lodash'); var extend = require('node.extend'); var serialport = require('serialport'); var commands = require('./commands'); var demos = require('./demos'); var misc = require('./misc'); var sensors = require('./sensors'); var songs = require('./songs'); var Robot = function (device, options) { events.EventEmitter.call(this); if (!_.isString(device)) { var err = new Error('a valid serial device string is required!'); err.invalid_device = device; throw err; } // set up our options. we pull in the device we were given for convenience var defaults = { device: device, baudrate: 57600 }; this.options = extend(defaults, options); // the parsed contents of the most recent streamed data response, kept around // so we can compare subsequent responses for differences. this._sensorData = null; // initiate a serial connection to the robot this.serial = new serialport.SerialPort(this.options.device, { baudrate: this.options.baudrate, databits: 8, stopbits: 1, parity: 'none', // use our custom packet parser parser: this._parseSerialData.bind(this) }); // run our setup function once the serial connection is ready this.serial.on('open', this._init.bind(this)); // handle incoming sensor data whenever we get it this.serial.on('sensordata', this._handleSensorData.bind(this)); // the current state of the power LEDs. all always start at zero, which is // what the create puts them at when the mode is changed to safe or full. // NOTE: if the create is in passive mode, these values will be wrong, but // that case is unlikely so we ignore it. this._ledState = { play: false, advance: false, power_intensity: 0, power_color: 0 }; // where incoming serial data is held until a complete packet is received this._buffer = []; }; util.inherits(Robot, events.EventEmitter); // collect serial data in an internal buffer until we receive an entire packet, // and then emit a 'packet' event so that packet can be specifically parsed. Robot.prototype._parseSerialData = function (emitter, data) { // add the received bytes to our internal buffer in-place Array.prototype.push.apply(this._buffer, data); // attempt to find a valid packet in our stored bytes for (var i = this._buffer.length; i >= 0; i--) { if (this._buffer[i] === sensors.PACKET_HEADER) { // the packet length byte value and the packet end index (exclusive) var packetLength = this._buffer[i + 1]; var endIndex = i + packetLength + 3; // set our indexes if we got a valid packet var packet = this._buffer.slice(i, endIndex); if (sensors.isValidSensorPacket(packet)) { // discard all bytes up to the packet's last byte inclusive this._buffer.splice(0, endIndex); // strip off the header, length, and checksum since we don't need them packet = packet.slice(2, -1); // parse the sensor data and emit an event with it. if we fail, just // alert that we got a bad packet and continue. since there are lots of // packets coming through, some are bound to end up corrupted. try { var parsedData = sensors.parseSensorData(packet); // emit this event using the serial object so it can't be unbound // externally. emitter.emit('sensordata', parsedData); // emit the event externally in case anyone wants to use it this.emit('sensordata', parsedData); } catch (e) { var err = new Error('bad sensor data packet received'); err.parse_error = e; err.packet = packet; this.emit('badpacket', err); } break; } } } return this; }; // handle incoming sensor data and emit events to notify of changes Robot.prototype._handleSensorData = function (newSensorData) { // if there was previous sensor data, emit data change events if (this._sensorData) { // the functions that handle emitting events on data changes var emitFunctions = [ this._detectBump, // bump this._detectButton, // button this._detectCliff, // cliff this._detectIR, // ir this._detectMode, // mode this._detectOvercurrent, // overcurrent this._detectVirtualWall, // virtualwall this._detectWall, // wall this._detectWheelDrop // wheeldrop ]; // call all the functions with our sensor data values and collect results var emittedEvents = _.map(emitFunctions, function (emitFunction) { return emitFunction.call(this, this._sensorData, newSensorData); }, this); // if any of the events returned something truthy, emit the meta event if (_.any(emittedEvents)) { this.emit('change'); } } // update the stored sensor values now that we're done looking at them this._sensorData = newSensorData; return this; }; // run once the serial port reports a connection Robot.prototype._init = function () { // null out the sensor data so we can't be flooded with change events on a // reconnect. this._sensorData = null; // send the required initial start command to the robot this._sendCommand(commands.Start); // enter safe mode by default this.safeMode(); // start streaming all sensor data. we manually specify the packet ids we need // since streaming with the special bytes (id < 7) returns responses that // require special cases to parse correctly. var packets = _.pluck(sensors.ALL_SENSOR_PACKETS, 'id'); this._sendCommand(commands.Stream, packets.length, packets); // give audible feedback that we've connected this.sing(songs.START); // zero the LED values (so we can be sure about what the LED state is), then // turn the power LED green with 100% brightness. this.setLEDs({ play: false, advance: false, power_intensity: 1, power_color: 0 }); // emit an event to alert that we're now ready to receive commands once we've // received the first sensor data. that means that the robot is communicating // with us and ready to go! this.serial.once('sensordata', this.emit.bind(this, 'ready')); return this; }; // emit an event with some data if a value has changed to the specified value. // returns the result of the sensor data comparison. Robot.prototype._emitValueChange = function (keyName, value, oldSensorData, newSensorData, eventName, eventData) { return misc.compare(oldSensorData, newSensorData, keyName, function (v) { if (_.isEqual(v, value)) { this.emit(eventName, eventData); } }, this); }; // emit events if a wheel drop was detected Robot.prototype._detectWheelDrop = function (oldSensorData, newSensorData) { var rightCmp = this._emitValueChange('wheels.right.dropped', true, oldSensorData, newSensorData, 'wheeldrop:right'); var leftCmp = this._emitValueChange('wheels.left.dropped', true, oldSensorData, newSensorData, 'wheeldrop:left'); var casterCmp = this._emitValueChange('wheels.caster.dropped', true, oldSensorData, newSensorData, 'wheeldrop:caster'); // emit an overall event if any of the values changed var data = null; if ((rightCmp.changed && rightCmp.value) || (leftCmp.changed && leftCmp.value) || (casterCmp.changed && casterCmp.value)) { data = { right: rightCmp.value, left: leftCmp.value, caster: casterCmp.value }; this.emit('wheeldrop', data); } return data; }; // emit events if a bumper was bumped Robot.prototype._detectBump = function (oldSensorData, newSensorData) { var rightCmp = this._emitValueChange('bumpers.right.activated', true, oldSensorData, newSensorData, 'bump:right'); var leftCmp = this._emitValueChange('bumpers.left.activated', true, oldSensorData, newSensorData, 'bump:left'); var data = null; if ((rightCmp.changed && rightCmp.value) || (leftCmp.changed && leftCmp.value)) { // emit a virtual event for a 'center' bumper if both bumpers are active if (leftCmp.value && rightCmp.value) { this.emit('bump:both'); } data = { // bumpers mapped to whether they're activated right: rightCmp.value, left: leftCmp.value, both: rightCmp.value && leftCmp.value }; this.emit('bump', data); } return data; }; // emit events if a cliff was detected Robot.prototype._detectCliff = function (oldSensorData, newSensorData) { var leftCmp = this._emitValueChange( 'cliff_sensors.left.detecting', true, oldSensorData, newSensorData, 'cliff:left', _.pick(newSensorData.cliff_sensors.left, 'signal')); var frontLeftCmp = this._emitValueChange( 'cliff_sensors.front_left.detecting', true, oldSensorData, newSensorData, 'cliff:front_left', _.pick(newSensorData.cliff_sensors.front_left, 'signal')); var frontRightCmp = this._emitValueChange( 'cliff_sensors.front_right.detecting', true, oldSensorData, newSensorData, 'cliff:front_right', _.pick(newSensorData.cliff_sensors.front_right, 'signal')); var rightCmp = this._emitValueChange( 'cliff_sensors.right.detecting', true, oldSensorData, newSensorData, 'cliff:right', _.pick(newSensorData.cliff_sensors.right, 'signal')); var data = null; if ((leftCmp.changed && leftCmp.value) || (frontLeftCmp.changed && frontLeftCmp.value) || (frontRightCmp.changed && frontRightCmp.value) || (rightCmp.changed && rightCmp.value)) { data = extend({}, newSensorData.cliff_sensors); this.emit('cliff', data); } return data; }; // emit events if a wall was detected Robot.prototype._detectWall = function (oldSensorData, newSensorData) { var data = _.pick(newSensorData.wall_sensor, 'signal'); var cmp = this._emitValueChange('wall_sensor.detecting', true, oldSensorData, newSensorData, 'wall', data); // return the comparison event data if the event happened if (cmp.changed && cmp.value) { return data; } return null; }; // emit events if a virtual wall was detected Robot.prototype._detectVirtualWall = function (oldSensorData, newSensorData) { var cmp = this._emitValueChange('virtual_wall_sensor.detecting', true, oldSensorData, newSensorData, 'virtualwall'); if (cmp.changed && cmp.value) { return true; } return null; }; // emit events if an IR signal was received Robot.prototype._detectIR = function (oldSensorData, newSensorData) { var data = { value: newSensorData.ir.received_value }; var cmp = this._emitValueChange('ir.receiving', true, oldSensorData, newSensorData, 'ir', data); if (cmp.changed && cmp.value) { return data; } return null; }; // emit events if a button was pressed Robot.prototype._detectButton = function (oldSensorData, newSensorData) { var advanceCmp = this._emitValueChange('buttons.advance.pressed', true, oldSensorData, newSensorData, 'button:advance'); var playCmp = this._emitValueChange('buttons.play.pressed', true, oldSensorData, newSensorData, 'button:play'); var data = null; if ((advanceCmp.changed && advanceCmp.value) || (playCmp.changed && playCmp.value)) { data = { advance: newSensorData.buttons.advance.pressed, play: newSensorData.buttons.play.pressed }; this.emit('button', data); } return data; }; // emit events if the mode changed Robot.prototype._detectMode = function (oldSensorData, newSensorData) { var offCmp = this._emitValueChange('state.mode.off', true, oldSensorData, newSensorData, 'mode:off'); var passiveCmp = this._emitValueChange('state.mode.passive', true, oldSensorData, newSensorData, 'mode:passive'); var safeCmp = this._emitValueChange('state.mode.safe', true, oldSensorData, newSensorData, 'mode:safe'); var fullCmp = this._emitValueChange('state.mode.full', true, oldSensorData, newSensorData, 'mode:full'); var data = null; if ((offCmp.changed && offCmp.value) || (passiveCmp.changed && passiveCmp.value) || (safeCmp.changed && safeCmp.value) || (fullCmp.changed && fullCmp.value)) { data = extend({}, newSensorData.state.mode); this.emit('mode', data); } return data; }; // emit events if an overcurrent warning occurred Robot.prototype._detectOvercurrent = function (oldSensorData, newSensorData) { var leftCmp = this._emitValueChange('wheels.left.overcurrent', true, oldSensorData, newSensorData, 'overcurrent:wheel:left'); var rightCmp = this._emitValueChange('wheels.right.overcurrent', true, oldSensorData, newSensorData, 'overcurrent:wheel:right'); var lsd0Cmp = this._emitValueChange('low_side_drivers.0.overcurrent', true, oldSensorData, newSensorData, 'overcurrent:lowsidedriver:0'); var lsd1Cmp = this._emitValueChange('low_side_drivers.1.overcurrent', true, oldSensorData, newSensorData, 'overcurrent:lowsidedriver:1'); var lsd2Cmp = this._emitValueChange('low_side_drivers.2.overcurrent', true, oldSensorData, newSensorData, 'overcurrent:lowsidedriver:2'); var data = null; if ((leftCmp.changed && leftCmp.value) || (rightCmp.changed && rightCmp.value) || (lsd0Cmp.changed && lsd0Cmp.value) || (lsd1Cmp.changed && lsd1Cmp.value) || (lsd2Cmp.changed && lsd2Cmp.value)) { data = { wheels: { left: leftCmp.value, right: rightCmp.value }, low_side_drivers: [ lsd0Cmp.value, lsd1Cmp.value, lsd2Cmp.value ] }; this.emit('overcurrent', data); } return data; }; // send a command packet to the robot over the serial port, with additional // arguments recursively flattened into individual bytes. Robot.prototype._sendCommand = function (command) { // turn the arguments into a packet of command opcode followed by data bytes. // arrays in arguments after the first are flattened. var packet = _.flatten(Array.prototype.slice.call(arguments, 1)); packet.unshift(command.opcode); var packetBytes = new Buffer(packet); // write the bytes and flush the write to force sending the data immediately this.serial.write(packetBytes); this.serial.flush(); return this; }; // return a copy of the most recently received sensor data Robot.getSensorData = function () { return extend({}, this._sensorData); }; // return the most recently received battery information Robot.prototype.getBatteryInfo = function () { return this.getSensorData().battery; }; // make the robot play a song. notes is an array of arrays, where each item is a // pair of note frequency in Hertz followed by its duration in milliseconds. // non-numeric note values (like null) and out-of-range notes are treated as // pauses. Robot.prototype.sing = function (notes) { if (notes && notes.length > 0) { // create a copy of the notes array so we can modify it at-will notes = notes.slice(); // fill all the available song slots with our segments, and store their // durations away so we can set timeouts to play them in turn. var cumulativeDelay = 0; while (notes.length > 0) { // convert the next song-length segment and reduce the notes array var song = songs.toCreateFormat(notes.splice(0, songs.MAX_SONG_LENGTH)); // schedule this segment for storage and playback setTimeout(this._storeAndPlaySong.bind(this, song), cumulativeDelay); // calculate the delay from the 64ths of second parts, since it will be // more accurate than using the milliseconds, which were lossily converted // to 64ths of a second before being stored on the robot. we use ceil so // we don't accidentally call our callback before the previous segment is // done, which would cause the new requested playback to fail. var duration = 0; for (var j = song.length - 1; j >= 0; j--) { duration += song[j][1]; } cumulativeDelay += Math.ceil(duration * 1000 / 64); } } return this; }; // store a song in the first song slot, then immediately request its playback Robot.prototype._storeAndPlaySong = function (notes) { var slot = 0; this._sendCommand(commands.Song, slot, notes.length, notes); this._sendCommand(commands.PlaySong, slot); }; // put the robot into passive mode Robot.prototype.passiveMode = function () { this._sendCommand(commands.Start); return this; }; // put the robot into safe mode Robot.prototype.safeMode = function () { this._sendCommand(commands.Safe); // reset the LEDs so they'll take on the last values that were set this.setLEDs(); return this; }; // put the robot into full mode Robot.prototype.fullMode = function () { this._sendCommand(commands.Full); this.setLEDs(); return this; }; // run one of the built-in demos specified by the demo id. to stop the demo, // use #halt(). Robot.prototype.demo = function (demoId) { this._sendCommand(commands.Demo, demoId); return this; }; // tell the robot to seek out and mate with its dock. to cancel the docking // maneuver, use #halt(). Robot.prototype.dock = function () { this.demo(demos.CoverAndDock); return this; }; // toggle the play or advance LED by name. defaults the 'enable' value to the // inverse of the last set value. Robot.prototype._toggleLED = function (name, enable) { enable = _.isUndefined(enable) ? !this._ledState[name] : enable; // create and set an LED state object with our key and boolean value var state = {}; state[name] = !!enable; this.setLEDs(state); return this; }; // toggle the state of the 'play' LED, or set it to the value given (true for // on, false for off). Robot.prototype.togglePlayLED = function (enable) { this._toggleLED('play', enable); return this; }; // toggle the state of the 'advance' LED, or set it to the given value (true for // on, false for off). Robot.prototype.toggleAdvanceLED = function (enable) { this._toggleLED('advance', enable); return this; }; // set the intensity and color of the power LED. if intensity is not given, // defaults to 0. if only an intensity is given, the color is left unchanged. // intensity ranges from 0 (off) to 1 (maximum brightness). color ranges from 0 // (green) to 1 (red) with intermediate values being a blend between these // colors (orange, yellow, etc.). Robot.prototype.setPowerLED = function (intensity, color) { // default intensity to 0 intensity = _.isNumber(intensity) ? intensity : 0; this.setLEDs({ power_intensity: intensity, power_color: color }); return this; }; // set the state of all LEDs at once. all parameter values behave as they do in // their individual methods, with the exception that undefined values are filled // in from the last set LED state values. // // this function, or any of the individual functions, will have no effect if the // robot is in passive mode. once the mode is changed from passive to safe or // full, the last set LED state will be restored. // // expects an object like: // { // play: true, // advance: false, // power_color: 0.2, // power_intensity: 0.65 // } Robot.prototype.setLEDs = function (leds) { // copy the object we were sent so we can modify its values leds = extend({}, leds); // turn the play and advance values into bytes of 0 or 1 if (!_.isUndefined(leds.play)) { leds.play = +(!!leds.play); } if (!_.isUndefined(leds.advance)) { leds.advance = +(!!leds.advance); } // turn the power intensity and color values into bytes between 0 and 255 if (!_.isUndefined(leds.power_intensity)) { leds.power_intensity = Math.round( Math.max(0, Math.min(255, 255 * leds.power_intensity))); } if (!_.isUndefined(leds.power_color)) { leds.power_color = Math.round( Math.max(0, Math.min(255, 255 * leds.power_color))); } // fill in missing values from the prior state leds = extend({}, this._ledState, leds); // send the command to update the LEDs this._sendCommand(commands.LEDs, // build the play/advance state byte misc.bitsToByte([false, leds.play, false, leds.advance]), leds.power_color, leds.power_intensity ); // store the state for the next time an LED function is called this._ledState = leds; return this; }; // drive the robot in one of two ways: // - velocity, radius // - { right: velocity, left: velocity } // if radius is left unspecified, 'straight' is assumed. if an individual // velocity is left unspecified, 0 is assumed. Robot.prototype.drive = function (velocity, radius) { var maxVelocity = 500; // millimeters per second var maxRadius = 2000; // millimeters // default the radius to 'straight' radius = radius || 0; // the command we'll eventually run var command = null; // for transforming our numbers into individual bytes var data = new Buffer(4); // handle the two different calling conventions if (_.isNumber(velocity)) { command = commands.Drive; // constrain values velocity = Math.max(-maxVelocity, Math.min(maxVelocity, velocity)); radius = Math.max(-maxRadius, Math.min(maxRadius, radius)); // build the bytes for our velocity numbers data.writeInt16BE(velocity, 0); data.writeInt16BE(radius, 2); } else { command = commands.DriveDirect; // use direct drive, where each wheel gets its own independent velocity var velocityLeft = Math.max(-maxVelocity, Math.min(maxVelocity, velocity.left || 0)); var velocityRight = Math.max(-maxVelocity, Math.min(maxVelocity, velocity.right || 0)); data.writeInt16BE(velocityLeft, 0); data.writeInt16BE(velocityRight, 2); } this._sendCommand(command, data.toJSON()); return this; }; // stop the robot from moving/rotating, and stop any current demo Robot.prototype.halt = function () { this.drive(0, 0); this.demo(demos.Abort); return this; }; module.exports = Robot;
#!/usr/bin/env node --harmony var REPL = require('co-repl'); // var mongoose = require('mongoose'); var fs = require('fs'); var path = require('path') // require('mongoose-q')(mongoose) function CoYongoose(mongoose) { this.mongoose = mongoose; require('mongoose-q')(mongoose); this.connect = function(conn_str) { this.mongoose.connect(conn_str || 'mongodb://localhost/test'); return this; }, this.include = function(model_path) { require(path.resolve(model_path)); return this; }, this.includeDir = function(dir_path) { var self = this; dir_path = path.resolve(dir_path); var files = fs.readdirSync(dir_path); files.forEach(function(file){ self.include(dir_path + '/' + file); }); return this; }, this.start = function() { var self = this; var repl = REPL.start(); var keys = Object.keys(this.mongoose.models); for(var index in keys) { var key = keys[index]; repl.context[key] = self.mongoose.models[key]; console.log('Model loaded: ', key); } repl.displayPrompt(); return this; } } if (!module.parent) { // FIXME: when using as a global tool, it has different mongoose instance. var program = require('commander'); program .version('0.0.1') .option('-i, --include [model]', 'Include models') .option('-d, --dir [model directory]', 'Include model directory') .parse(process.argv); var yongoose = new CoYongoose().connect(program.args[0]) if (program.include) { yongoose.include(program.include) } if (program.dir) { yongoose.includeDir(program.dir) } yongoose.start(); } else { module.exports = CoYongoose }
$dh.Require("util/event"); DHDRAG = new DHEvent(); $dh.extend(DHDRAG, { mouseOffset: null, activeObj: null, mask: null, dragStarted: false, init: function() { $dh.addEv(document, "mousemove", DHDRAG.mouseMove); $dh.addEv(document, "mouseup", DHDRAG.mouseUp); $dh.addEv(document, "mousedown", DHDRAG.mouseDown); $dh.addEv(document, "mouseout", DHDRAG.mouseOut); // Further use as an DHT object $dh.setDrag = DHDRAG.setDrag; $dh.disableDrag = DHDRAG.disableDrag; // Create mask DHDRAG.mask = $dh.$new("div", { id: "_DHDragMask_" }); $dh.css(DHDRAG.mask, { zIndex: 1000000, background: "yellow", opac: 30, position: "absolute", display: "none" }); $dh.addCh(document.body, DHDRAG.mask); }, setDrag: function(obj, dragParams) { //Eg: {mode : "MOVE", dragSource:parent, maskStyle:"", limit:{}, ghostDrag:true} DHDRAG.setDragParams(obj, dragParams); DHDRAG.raise("_oninitdrag", obj); }, setDragTarget: function(src, tar) { src.dragTarget = tar; }, setDragParams: function(obj, dragParams) { var src = dragParams.dragSource || obj; src.canDrag = true; if (src != obj) src.dragTarget = obj; if (dragParams.mode.charAt(dragParams.mode.length - 1) != ",") dragParams.mode += ","; obj.dragParams = dragParams; $dh.preventLeak(obj, "dragParams"); }, disableDrag: function(obj) { obj.canDrag = false; obj.dragParams = null; }, mouseDown: function(ev) { ev = $dh.normEv(ev); var src = ev.target; if (src.canDrag != true) return false; ev.stop(); DHDRAG.activeObj = src.dragTarget || src; DHDRAG.dragSource = src; DHDRAG.dragStarted = false; }, mouseUp: function(ev) { if ($dh.isNone(DHDRAG.activeObj)) return; DHDRAG.dragStarted = false; DHDRAG.raise("_ondragstop", DHDRAG.activeObj, $dh.normEv(ev)); DHDRAG.activeObj = null; }, mouseMove: function(ev) { ev = $dh.normEv(ev); // Raise public mouse move event if (ev.target.canDrag == true && $dh.isNone(DHDRAG.activeObj)) DHDRAG.raise("_onmousemove", ev.target.dragTarget || ev.target, ev); // Raise drag start event if ($dh.isNone(DHDRAG.activeObj)) return; if (DHDRAG.dragStarted != true) { DHDRAG.dragStarted = true; DHDRAG.raise("_ondragstart", DHDRAG.activeObj, ev); } if (DHDRAG.dragStarted) DHDRAG.raise("_ondragging", DHDRAG.activeObj, ev); }, mouseOut: function(ev) { var tar = $dh.normEv(ev).target; if (!DHDRAG.dragStarted && tar.saveSrcCursor) { tar.style.cursor = tar.saveSrcCursor; } if (!DHDRAG.dragStarted) document.body.style.cursor = ""; }, addMode: function(name, modeObj) { if ($dh.isNone(DHDRAG["modes"])) DHDRAG.modes = new Array(); DHDRAG.modes[name] = modeObj; modeObj.name = name; var temp = "function(sender,target, ev) {if (!DHDRAG.hasDragMode(, '" + name + "')) return;abc=123;}"; for (var p in modeObj) { if (p.indexOf("on") == 0) { var func = (modeObj[p] + ""); var header = func.substr(0, func.indexOf("{") + 1); var newFunc = header + "if (!DHDRAG.hasDragMode(arguments[1],'" + name + "')) return false;" + "if (DHDRAG.modes['" + name + "']['" + p + "'].apply(DHDRAG,arguments) != false)" + "DHDRAG.raise('" + p.toLowerCase() + "',arguments[1],arguments[2]);" + "}"; eval("DHDRAG.addEv('_" + p.toLowerCase() + "', " + newFunc + ")"); } } }, hasDragMode: function(obj, mode) { if (!obj.dragParams) return; return obj.dragParams.mode.indexOf(mode + ",") >= 0; }, msOffset: function(ev, obj) { ev = ev || window.event; var objPos = $dh.pos(obj), msPos = $dh.msPos(ev); return { left: msPos.left - objPos.left, top: msPos.top - objPos.top }; } }); // Register DHDRAG to window.onload $dh.addLoader(DHDRAG.init); $dh.addEv(window,"unload",function(){ $dh.rmEv(document,"mousemove",DHDRAG.mouseMove); $dh.rmEv(document,"mouseup",DHDRAG.mouseUp); $dh.rmEv(document, "mousedown", DHDRAG.mouseDown); for (var x in DHDRAG) if (!$dh.isNone(DHDRAG[x])) DHDRAG[x] = null; DHDRAG = null; }); // Register built-in effects DHDRAG.addMode("RESIZE", { onInitDrag: function(sender, target) { var pp = ["width", "height"]; for (var i = 0; i < pp.length; i++) { target.dragParams["min" + pp[i]] = target.dragParams["min" + pp[i]] || 0; target.dragParams["max" + pp[i]] = target.dragParams["max" + pp[i]] || 99999; } }, onMouseMove: function(sender, target, ev) { if (DHDRAG.dragStarted) return false; var dragSource = ev.target; if (!target.saveSrcCursor) dragSource.saveSrcCursor = dragSource.style.cursor || ""; var b = $dh.bounds(target); var pos = ev.pos; var d = target.dragParams.dResize || 6; document.body.style.cursor = ""; var dir = { s: false, n: false, w: false, e: false }; if (Math.abs(pos.left - b.left) <= d) { dir["w"] = true; } if (Math.abs(pos.left - b.left - b.width) <= d) { dir["e"] = true; } if (Math.abs(pos.top - b.top) <= d) { dir["n"] = true; } if (Math.abs(pos.top - b.top - b.height) <= d) { dir["s"] = true; } // Set cursor var csr = ""; for (var p in dir) if (dir[p]) csr += p; if (csr != "") document.body.style.cursor = csr + "-resize"; if (document.body.style.cursor.indexOf("-") > 0) { dragSource.style.cursor = document.body.style.cursor; } else { if (DHDRAG.activeObj == target) dragSource.style.cursor = dragSource.saveSrcCursor; else { dragSource.style.cursor = ""; dragSource.saveSrcCursor = null; } } // document.title += " res = " + target.style.cursor + " while crs='"+ csr+"'"; }, onDragStart: function(sender, target, ev) { if (document.body.style.cursor.indexOf("resize") < 0) { return false; } DHDRAG.mouseOffset = DHDRAG.msOffset(ev, target); DHDRAG.saveBounds = $dh.bounds(target); DHDRAG.saveMousePos = $dh.msPos(ev); if (target.dragParams.noMask != true) DHDRAG.mask.style.display = ""; }, onDragStop: function(sender, target, ev) { target.style.display = ""; if (DHDRAG.mask.style.display == "none") return; var newBounds = $dh.bounds(DHDRAG.mask); $dh.css(target, { display: "", size: [newBounds.width, newBounds.height], pos: [newBounds.left, newBounds.top] }); DHDRAG.mask.style.display = "none"; }, onDragging: function(sender, target, ev) { if (document.body.style.cursor.indexOf("resize") < 0) { return false; } var mousePos = ev.pos; var mb = { left: DHDRAG.saveBounds.left, top: DHDRAG.saveBounds.top, width: DHDRAG.saveBounds.width, height: DHDRAG.saveBounds.height }; var dw = mousePos.left - DHDRAG.mouseOffset.left - DHDRAG.saveBounds.left; var dh = mousePos.top - DHDRAG.mouseOffset.top - DHDRAG.saveBounds.top; var dl = 0, dt = 0, lim = ""; // Set delta for all sides var rsm = document.body.style.cursor; switch (rsm.substr(0, rsm.indexOf("-"))) { case "w": dl = dw; dw = -dw; dh = 0; lim = "left&&width"; break; case "sw": dl = dw; dw = -dw; lim = "left&&width"; break; case "e": dh = 0; lim = "width"; break; case "ne": dt = dh; dh = -dh; lim = "top&&left&&height"; break; case "n": dt = dh; dh = -dh; dw = 0; lim = "top&&height"; break; case "s": dw = 0; lim = "height"; break; case "nw": dl = dw; dw = -dw; dt = dh; dh = -dh; lim = "top&&height&&width&&left"; break; } mb.width = dw + DHDRAG.saveBounds.width; mb.height = dh + DHDRAG.saveBounds.height; mb.top = dt + DHDRAG.saveBounds.top; mb.left = dl + DHDRAG.saveBounds.left; // Recheck limits var xlim = lim.split("&&"); var related = { "width": "left", "height": "top", "top": "height", "left": "width" }; for (var x in mb) { if (mb[x] < target.dragParams["min" + x]) { if (lim.indexOf(x) >= 0) { for (var k = 0; k < xlim.length; k++) if (related[x] == xlim[k]) mb[xlim[k]] += mb[x] - target.dragParams["min" + x]; } mb[x] = target.dragParams["min" + x]; } if (mb[x] > target.dragParams["max" + x]) { if (lim.indexOf(x) >= 0) { for (var k = 0; k < xlim.length; k++) if (related[x] == xlim[k]) mb[xlim[k]] += mb[x] - target.dragParams["max" + x]; ; } mb[x] = target.dragParams["max" + x]; } } if (target.dragParams.ghostDrag != true) { $dh.pos(target, [mb.left, mb.top]); $dh.size(target, [mb.width, mb.height]); } //if (DHDRAG.mask.style.display != "none") { $dh.pos(DHDRAG.mask, [mb.left, mb.top]); $dh.size(DHDRAG.mask, [mb.width, mb.height]); //} } }); // Define drag effects DHDRAG.addMode("MOVE", { onInitDrag: function(sender, target) { var pp = ["left", "top"]; for (var i = 0; i < pp.length; i++) { target.dragParams["min" + pp[i]] = target.dragParams["min" + pp[i]] || -99999; target.dragParams["max" + pp[i]] = target.dragParams["max" + pp[i]] || 99999; } }, onDragStart: function(sender, target, ev) { if (document.body.style.cursor.indexOf("resize") > 0) return false; DHDRAG.mouseOffset = DHDRAG.msOffset(ev, target); if (target.dragParams.noMask != true) { DHDRAG.mask.style.cursor = "move"; DHDRAG.mask.style.display = ""; } var size = $dh.size(target); $dh.size(DHDRAG.mask, [size.width, size.height]); }, onDragStop: function(sender, target, ev) { target.style.display = ""; if (target.dragParams.ghostDrag == true) $dh.css(target, {left: DHDRAG.mask.style.left, top: DHDRAG.mask.style.top}); DHDRAG.mask.style.display = "none"; }, onDragging: function(sender, target, ev) { if (document.body.style.cursor.indexOf("resize") > 0) return false; var mousePos = ev.pos; var newPos = {}; newPos.left = mousePos.left - DHDRAG.mouseOffset.left; newPos.top = mousePos.top - DHDRAG.mouseOffset.top; for (var p in newPos) { if (newPos[p] > target.dragParams["max"+p]) newPos[p] = target.dragParams["max"+p]; if (newPos[p] < target.dragParams["min"+p]) newPos[p] = target.dragParams["min"+p]; } $dh.pos(DHDRAG.mask,[newPos.left, newPos.top]); if (target.dragParams.ghostDrag != true) $dh.pos(target, [newPos.left, newPos.top]); } });
'use strict' const Transport = require('libp2p-tcp') const Muxer = require('libp2p-mplex') const { NOISE: Crypto } = require('libp2p-noise') module.exports = { modules: { transport: [Transport], streamMuxer: [Muxer], connEncryption: [Crypto] }, config: { relay: { enabled: true, hop: { enabled: false } } } }
import { SWITCH_SECTION, TOGGLE_NAV, SET_ACTIVE_SECTION, EXTEND_PORTFOLIO_SECTION, TOGGLE_SKILLS_ROW, LOAD_PORTOFOLIO_IMAGES, UNSET_SCROLL_TRIGGERED } from './types'; export function switchSectionTo(newSection) { return { type: SWITCH_SECTION, payload: newSection } } export function setActiveSection(newSection) { return { type: SET_ACTIVE_SECTION, payload: newSection } } export function toggleNav(setAsOpen) { return { type: TOGGLE_NAV, payload: setAsOpen } } export function extendPortfolio() { return { type: EXTEND_PORTFOLIO_SECTION } } export function toggleSkillsRow(rowName) { return { type: TOGGLE_SKILLS_ROW, payload: rowName } } export function loadPortfolioImages() { return { type: LOAD_PORTOFOLIO_IMAGES, } } export function unsetScrollTriggered() { return { type: UNSET_SCROLL_TRIGGERED, payload: false } }
'use strict'; const frontmatter = require('gulp-front-matter'); const path = require('path'); const processTree = require('../gulp-plugins/process-toc'); const fs = require('fs-extra'); module.exports = (gulp, opts) => { gulp.task('toc', toc); function toc() { return gulp.src('**/*.md', { follow: true, cwd: opts.paths.content }) .pipe(frontmatter()) .pipe(processTree(opts)) .pipe(fs.createWriteStream(path.join(opts.paths.base, 'tree.json'))); } toc.description = 'build table of contents'; }
var express = require('express'); var router = express.Router(); var wechatConfig = require('./wechatConfig'); var wechatSnsHelper = require('./wechatSnsHelper'); router.get('/', function (req, res, next) { console.log(req.cookies); var openid = req.cookies.openid; if(openid){ res.render('user', {errMsg: {}, userInfo: {openid: openid}}); }else { res.redirect('/user/auth'); } }); router.get('/auth', function (req, res, next) { console.log(req.cookies); var openid = req.cookies.openid; if(openid){ res.redirect('/user'); }else { var wechatAuthUrlUserInfo = wechatConfig.wechatAuthUrl(wechatConfig.wechat.redirectUri, wechatConfig.wechat.scopeUserInfo); var wechatAuthUrlBase = wechatConfig.wechatAuthUrl(wechatConfig.wechat.redirectUri, wechatConfig.wechat.scopeBase); res.render('auth', {wechatAuthUrlUserInfo: wechatAuthUrlUserInfo, wechatAuthUrlBase:wechatAuthUrlBase}); } }); router.get('/auth/callback', function (req, res, next) { var query = req.query; wechatSnsHelper.jsAccessToken(query.code, function (error, response, body) { if(body.errcode){ res.render('user', {errMsg: body, userInfo: {}}); }else { wechatSnsHelper.jsUserInfo(body.access_token, body.openid, 'zh_CN', function (error, response, body) { //res.render('user', {errMsg: {}, userInfo: body}); var maxAge = 60 * 60 * 1000; res.cookie('openid', body.openid, {maxAge: maxAge}); res.redirect('/user'); }) } }); }); module.exports = router;
"use strict"; function setup( postal, config, fount ) { config = config || {}; const log = postal.channel( config.logChannel || "log" ); const resolver = postal.configuration.resolver.compare.bind( postal.configuration.resolver ); const Logger = require( "./Logger.js" )( log, resolver ); const adapters = require( "./configParser" )( log, config, fount ); function loggerFactory( namespace ) { return new Logger( namespace, adapters ); } return loggerFactory; } setup.log = require( "./log" )( setup ); module.exports = setup;
(function () { angular .module('directivas') .directive('ejercicioTarjeta2', function (){ const ddo = { }; return ddo; }); }());
module.exports = { SAHtml: require('./lib/sahtml').SAHtml };
Package.describe({ name: 'eahefnawy:accounts-coinbase', summary: 'A Meteor loginWithCoinbase Functionality.', version: '0.0.1-plugins.0', git: 'https://github.com/eahefnawy/accounts-coinbase.git', }); Package.onUse(function(api) { api.use('oauth2@1.1.3', ['client', 'server']); api.use('oauth@1.1.4', ['client', 'server']); api.use('http@1.1.0', ['server']); api.use('underscore@1.0.3', 'server'); api.use('random@1.0.3', 'client'); api.use('service-configuration@1.0.4', ['client', 'server']); api.use('accounts-base@1.2.0', ['client', 'server']); // Export Accounts (etc) to packages using this one. api.imply('accounts-base', ['client', 'server']); api.use('accounts-oauth@1.1.5', ['client', 'server']); api.export('Coinbase'); api.addFiles('coinbase_server.js', 'server'); api.addFiles('coinbase_client.js', 'client'); api.addFiles('coinbase.js'); });
export const FIREBASE_URL = 'https://glowing-torch-886.firebaseio.com'; export const FIREBASE_BACKLOGS_URL = FIREBASE_URL + '/backlogs';
/** * @file Utils */ /** * @module Utils */ import {menu} from '../main/index'; /** * Get menu item by label. * @param label {string} The label of the menu item to search for. * @returns {Electron.MenuItem} - The full menu item. Can change things like checked etc. */ export function getMenuItem (label) { for (let i = 0; i < menu.items.length; i++) { const menuItem = menu.items[i].submenu.items.find(item => item.label === label); if (menuItem) return menuItem } }
define(function() { function ColorTable(params) { this.colors = []; this.errorColor = params.errorColor; } ColorTable.prototype.hasColor = function(r, g, b, a) { return this.lookUpColor(r, g, b, a) >= 0; }; ColorTable.prototype.lookUpColor = function(r, g, b, a) { for(var i = 0; i < this.colors.length; i++) { if(this.colors[i].r === r && this.colors[i].g === g && this.colors[i].b === b && this.colors[i].a === a) { return i; } } return -1; }; ColorTable.prototype.lookUpIndex = function(i) { if(i < this.colors.length) { return this.colors[i]; } else { return null; } }; ColorTable.prototype.addColor = function(r, g, b, a) { this.colors.push({ r: r, g: g, b: b, a: a }); return this.colors.length - 1; }; ColorTable.prototype.lookUpOrAddColor = function(r, g, b, a) { var i = this.lookUpColor(r, g, b, a); if(i >= 0) { return i; } else { return this.addColor(r, g, b, a); } }; return ColorTable; });
var M = require('../message'); /** * 指定したすべての属性が必須である * @method exports * @param {String} requiredAttrs * @return {Function} hasAllAttributes */ module.exports = function (requiredAttrs) { var names = requiredAttrs.split(','); return function hasAllAttributes (node, e) { var attrs = node.attributes; var pass = attrs && names.every(function(name) { return attrs.hasOWnProperty(name); }); if (e && !pass) { e([M.HAS_ALL_ATTRIBUTES, requiredAttrs]); } return pass; }; };
module.exports = { GET : [{ path : '/{{api}}', action : 'GET', // policy : 'authenticated' },{ path : '/{{api}}/:id', action : 'findOne', // policy : 'authenticated' }], POST : [{ path : '/{{api}}', action : 'POST', // policy : 'authenticated' }], PUT : [{ path : '/{{api}}/:id', action : 'PUT', // policy : 'authenticated' }], DELETE : [{ path : '/{{api}}/:id', action : 'DELETE', // policy : 'authenticated' }] }
#!/usr/bin/env node require('babel/register'); require('./src/index');
// flow-typed signature: 5a7cf8685547d9008aad76a276f00233 // flow-typed version: <<STUB>>/chai_v^3.4.1/flow_v0.45.0 /** * This is an autogenerated libdef stub for: * * 'chai' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'chai' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'chai/chai' { declare module.exports: any; } declare module 'chai/karma.conf' { declare module.exports: any; } declare module 'chai/karma.sauce' { declare module.exports: any; } declare module 'chai/lib/chai' { declare module.exports: any; } declare module 'chai/lib/chai/assertion' { declare module.exports: any; } declare module 'chai/lib/chai/config' { declare module.exports: any; } declare module 'chai/lib/chai/core/assertions' { declare module.exports: any; } declare module 'chai/lib/chai/interface/assert' { declare module.exports: any; } declare module 'chai/lib/chai/interface/expect' { declare module.exports: any; } declare module 'chai/lib/chai/interface/should' { declare module.exports: any; } declare module 'chai/lib/chai/utils/addChainableMethod' { declare module.exports: any; } declare module 'chai/lib/chai/utils/addMethod' { declare module.exports: any; } declare module 'chai/lib/chai/utils/addProperty' { declare module.exports: any; } declare module 'chai/lib/chai/utils/expectTypes' { declare module.exports: any; } declare module 'chai/lib/chai/utils/flag' { declare module.exports: any; } declare module 'chai/lib/chai/utils/getActual' { declare module.exports: any; } declare module 'chai/lib/chai/utils/getEnumerableProperties' { declare module.exports: any; } declare module 'chai/lib/chai/utils/getMessage' { declare module.exports: any; } declare module 'chai/lib/chai/utils/getName' { declare module.exports: any; } declare module 'chai/lib/chai/utils/getPathInfo' { declare module.exports: any; } declare module 'chai/lib/chai/utils/getPathValue' { declare module.exports: any; } declare module 'chai/lib/chai/utils/getProperties' { declare module.exports: any; } declare module 'chai/lib/chai/utils/hasProperty' { declare module.exports: any; } declare module 'chai/lib/chai/utils/index' { declare module.exports: any; } declare module 'chai/lib/chai/utils/inspect' { declare module.exports: any; } declare module 'chai/lib/chai/utils/objDisplay' { declare module.exports: any; } declare module 'chai/lib/chai/utils/overwriteChainableMethod' { declare module.exports: any; } declare module 'chai/lib/chai/utils/overwriteMethod' { declare module.exports: any; } declare module 'chai/lib/chai/utils/overwriteProperty' { declare module.exports: any; } declare module 'chai/lib/chai/utils/test' { declare module.exports: any; } declare module 'chai/lib/chai/utils/transferFlags' { declare module.exports: any; } declare module 'chai/sauce.browsers' { declare module.exports: any; } // Filename aliases declare module 'chai/chai.js' { declare module.exports: $Exports<'chai/chai'>; } declare module 'chai/index' { declare module.exports: $Exports<'chai'>; } declare module 'chai/index.js' { declare module.exports: $Exports<'chai'>; } declare module 'chai/karma.conf.js' { declare module.exports: $Exports<'chai/karma.conf'>; } declare module 'chai/karma.sauce.js' { declare module.exports: $Exports<'chai/karma.sauce'>; } declare module 'chai/lib/chai.js' { declare module.exports: $Exports<'chai/lib/chai'>; } declare module 'chai/lib/chai/assertion.js' { declare module.exports: $Exports<'chai/lib/chai/assertion'>; } declare module 'chai/lib/chai/config.js' { declare module.exports: $Exports<'chai/lib/chai/config'>; } declare module 'chai/lib/chai/core/assertions.js' { declare module.exports: $Exports<'chai/lib/chai/core/assertions'>; } declare module 'chai/lib/chai/interface/assert.js' { declare module.exports: $Exports<'chai/lib/chai/interface/assert'>; } declare module 'chai/lib/chai/interface/expect.js' { declare module.exports: $Exports<'chai/lib/chai/interface/expect'>; } declare module 'chai/lib/chai/interface/should.js' { declare module.exports: $Exports<'chai/lib/chai/interface/should'>; } declare module 'chai/lib/chai/utils/addChainableMethod.js' { declare module.exports: $Exports<'chai/lib/chai/utils/addChainableMethod'>; } declare module 'chai/lib/chai/utils/addMethod.js' { declare module.exports: $Exports<'chai/lib/chai/utils/addMethod'>; } declare module 'chai/lib/chai/utils/addProperty.js' { declare module.exports: $Exports<'chai/lib/chai/utils/addProperty'>; } declare module 'chai/lib/chai/utils/expectTypes.js' { declare module.exports: $Exports<'chai/lib/chai/utils/expectTypes'>; } declare module 'chai/lib/chai/utils/flag.js' { declare module.exports: $Exports<'chai/lib/chai/utils/flag'>; } declare module 'chai/lib/chai/utils/getActual.js' { declare module.exports: $Exports<'chai/lib/chai/utils/getActual'>; } declare module 'chai/lib/chai/utils/getEnumerableProperties.js' { declare module.exports: $Exports<'chai/lib/chai/utils/getEnumerableProperties'>; } declare module 'chai/lib/chai/utils/getMessage.js' { declare module.exports: $Exports<'chai/lib/chai/utils/getMessage'>; } declare module 'chai/lib/chai/utils/getName.js' { declare module.exports: $Exports<'chai/lib/chai/utils/getName'>; } declare module 'chai/lib/chai/utils/getPathInfo.js' { declare module.exports: $Exports<'chai/lib/chai/utils/getPathInfo'>; } declare module 'chai/lib/chai/utils/getPathValue.js' { declare module.exports: $Exports<'chai/lib/chai/utils/getPathValue'>; } declare module 'chai/lib/chai/utils/getProperties.js' { declare module.exports: $Exports<'chai/lib/chai/utils/getProperties'>; } declare module 'chai/lib/chai/utils/hasProperty.js' { declare module.exports: $Exports<'chai/lib/chai/utils/hasProperty'>; } declare module 'chai/lib/chai/utils/index.js' { declare module.exports: $Exports<'chai/lib/chai/utils/index'>; } declare module 'chai/lib/chai/utils/inspect.js' { declare module.exports: $Exports<'chai/lib/chai/utils/inspect'>; } declare module 'chai/lib/chai/utils/objDisplay.js' { declare module.exports: $Exports<'chai/lib/chai/utils/objDisplay'>; } declare module 'chai/lib/chai/utils/overwriteChainableMethod.js' { declare module.exports: $Exports<'chai/lib/chai/utils/overwriteChainableMethod'>; } declare module 'chai/lib/chai/utils/overwriteMethod.js' { declare module.exports: $Exports<'chai/lib/chai/utils/overwriteMethod'>; } declare module 'chai/lib/chai/utils/overwriteProperty.js' { declare module.exports: $Exports<'chai/lib/chai/utils/overwriteProperty'>; } declare module 'chai/lib/chai/utils/test.js' { declare module.exports: $Exports<'chai/lib/chai/utils/test'>; } declare module 'chai/lib/chai/utils/transferFlags.js' { declare module.exports: $Exports<'chai/lib/chai/utils/transferFlags'>; } declare module 'chai/sauce.browsers.js' { declare module.exports: $Exports<'chai/sauce.browsers'>; }
(function () { 'use strict'; angular .module('parcels.admin') .controller('ParcelsController', ParcelsController); ParcelsController.$inject = ['$scope', '$state', '$window', 'parcelResolve', 'Authentication']; function ParcelsController($scope, $state, $window, parcel, Authentication) { var vm = this; vm.parcel = parcel; vm.authentication = Authentication; vm.error = null; vm.form = {}; vm.remove = remove; vm.save = save; // Remove existing Parcel function remove() { if ($window.confirm('Are you sure you want to delete?')) { vm.parcel.$remove($state.go('admin.parcels.list')); } } // Save Parcel function save(isValid) { if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'vm.form.parcelForm'); return false; } // Create a new parcel, or update the current instance vm.parcel.createOrUpdate() .then(successCallback) .catch(errorCallback); function successCallback(res) { $state.go('admin.parcels.list'); // should we send the User to the list or the updated Parcel's view? } function errorCallback(res) { vm.error = res.data.message; } } } }());
import '@babel/polyfill' import './app'
import { setData } from '@progress/kendo-angular-intl'; setData({ name: "ro-MD", likelySubtags: { ro: "ro-Latn-RO" }, identity: { language: "ro", territory: "MD" }, territory: "MD", calendar: { patterns: { d: "dd.MM.y", D: "EEEE, d MMMM y", m: "d MMM", M: "d MMMM", y: "MMM y", Y: "MMMM y", F: "EEEE, d MMMM y HH:mm:ss", g: "dd.MM.y HH:mm", G: "dd.MM.y HH:mm:ss", t: "HH:mm", T: "HH:mm:ss", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" }, dateTimeFormats: { full: "{1}, {0}", long: "{1}, {0}", medium: "{1}, {0}", short: "{1}, {0}", availableFormats: { d: "d", E: "ccc", Ed: "E d", Ehm: "E h:mm a", EHm: "E HH:mm", Ehms: "E h:mm:ss a", EHms: "E HH:mm:ss", Gy: "y G", GyMMM: "MMM y G", GyMMMd: "d MMM y G", GyMMMEd: "E, d MMM y G", h: "h a", H: "HH", hm: "h:mm a", Hm: "HH:mm", hms: "h:mm:ss a", Hms: "HH:mm:ss", hmsv: "h:mm:ss a v", Hmsv: "HH:mm:ss v", hmv: "h:mm a v", Hmv: "HH:mm v", M: "L", Md: "dd.MM", MEd: "E, dd.MM", MMdd: "dd.MM", MMM: "LLL", MMMd: "d MMM", MMMEd: "E, d MMM", MMMMd: "d MMMM", MMMMEd: "E, d MMMM", "MMMMW-count-one": "'săptămâna' W 'din' MMM", "MMMMW-count-few": "'săptămâna' W 'din' MMM", "MMMMW-count-other": "'săptămâna' W 'din' MMM", ms: "mm:ss", y: "y", yM: "MM.y", yMd: "dd.MM.y", yMEd: "E, dd.MM.y", yMM: "MM.y", yMMM: "MMM y", yMMMd: "d MMM y", yMMMEd: "E, d MMM y", yMMMM: "MMMM y", yQQQ: "QQQ y", yQQQQ: "QQQQ y", "yw-count-one": "'săptămâna' w 'din' y", "yw-count-few": "'săptămâna' w 'din' y", "yw-count-other": "'săptămâna' w 'din' y" } }, timeFormats: { full: "HH:mm:ss zzzz", long: "HH:mm:ss z", medium: "HH:mm:ss", short: "HH:mm" }, dateFormats: { full: "EEEE, d MMMM y", long: "d MMMM y", medium: "d MMM y", short: "dd.MM.y" }, days: { format: { abbreviated: [ "Dum", "Lun", "Mar", "Mie", "Joi", "Vin", "Sâm" ], narrow: [ "D", "L", "Ma", "Mi", "J", "V", "S" ], short: [ "Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ" ], wide: [ "duminică", "luni", "marți", "miercuri", "joi", "vineri", "sâmbătă" ] }, "stand-alone": { abbreviated: [ "Dum", "Lun", "Mar", "Mie", "Joi", "Vin", "Sâm" ], narrow: [ "D", "L", "Ma", "Mi", "J", "V", "S" ], short: [ "Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ" ], wide: [ "duminică", "luni", "marți", "miercuri", "joi", "vineri", "sâmbătă" ] } }, months: { format: { abbreviated: [ "ian.", "feb.", "mar.", "apr.", "mai", "iun.", "iul.", "aug.", "sept.", "oct.", "nov.", "dec." ], narrow: [ "I", "F", "M", "A", "M", "I", "I", "A", "S", "O", "N", "D" ], wide: [ "ianuarie", "februarie", "martie", "aprilie", "mai", "iunie", "iulie", "august", "septembrie", "octombrie", "noiembrie", "decembrie" ] }, "stand-alone": { abbreviated: [ "ian.", "feb.", "mar.", "apr.", "mai", "iun.", "iul.", "aug.", "sept.", "oct.", "nov.", "dec." ], narrow: [ "I", "F", "M", "A", "M", "I", "I", "A", "S", "O", "N", "D" ], wide: [ "ianuarie", "februarie", "martie", "aprilie", "mai", "iunie", "iulie", "august", "septembrie", "octombrie", "noiembrie", "decembrie" ] } }, quarters: { format: { abbreviated: [ "trim. 1", "trim. 2", "trim. 3", "trim. 4" ], narrow: [ "I", "II", "III", "IV" ], wide: [ "trimestrul 1", "trimestrul 2", "trimestrul 3", "trimestrul 4" ] }, "stand-alone": { abbreviated: [ "Trim. 1", "Trim. 2", "Trim. 3", "Trim. 4" ], narrow: [ "I", "II", "III", "IV" ], wide: [ "Trimestrul 1", "Trimestrul 2", "Trimestrul 3", "Trimestrul 4" ] } }, dayPeriods: { format: { abbreviated: { midnight: "miezul nopții", am: "a.m.", noon: "amiază", pm: "p.m.", morning1: "dimineața", afternoon1: "după-amiaza", evening1: "seara", night1: "noaptea" }, narrow: { midnight: "miezul nopții", am: "a.m.", noon: "amiază", pm: "p.m.", morning1: "dimineață", afternoon1: "după-amiază", evening1: "seară", night1: "noapte" }, wide: { midnight: "miezul nopții", am: "a.m.", noon: "amiază", pm: "p.m.", morning1: "dimineața", afternoon1: "după-amiaza", evening1: "seara", night1: "noaptea" } }, "stand-alone": { abbreviated: { midnight: "miezul nopții", am: "a.m.", noon: "amiază", pm: "p.m.", morning1: "dimineața", afternoon1: "după-amiaza", evening1: "seara", night1: "noaptea" }, narrow: { midnight: "miezul nopții", am: "a.m.", noon: "amiază", pm: "p.m.", morning1: "dimineață", afternoon1: "după-amiază", evening1: "seară", night1: "noapte" }, wide: { midnight: "miezul nopții", am: "a.m.", noon: "amiază", pm: "p.m.", morning1: "dimineața", afternoon1: "după-amiaza", evening1: "seara", night1: "noaptea" } } }, eras: { format: { wide: { 0: "înainte de Hristos", 1: "după Hristos", "0-alt-variant": "înaintea erei noastre", "1-alt-variant": "era noastră" }, abbreviated: { 0: "î.Hr.", 1: "d.Hr.", "0-alt-variant": "î.e.n.", "1-alt-variant": "e.n." }, narrow: { 0: "î.Hr.", 1: "d.Hr.", "0-alt-variant": "î.e.n.", "1-alt-variant": "e.n." } } }, gmtFormat: "GMT{0}", gmtZeroFormat: "GMT", dateFields: { era: { wide: "eră", short: "eră", narrow: "eră" }, year: { wide: "an", short: "an", narrow: "an" }, quarter: { wide: "trimestru", short: "trim.", narrow: "trim." }, month: { wide: "lună", short: "lună", narrow: "lună" }, week: { wide: "săptămână", short: "săpt.", narrow: "săpt." }, weekOfMonth: { wide: "Week Of Month", short: "Week Of Month", narrow: "Week Of Month" }, day: { wide: "zi", short: "zi", narrow: "zi" }, dayOfYear: { wide: "Day Of Year", short: "Day Of Year", narrow: "Day Of Year" }, weekday: { wide: "Zi a săptămânii", short: "Zi a săptămânii", narrow: "Zi a săptămânii" }, weekdayOfMonth: { wide: "Weekday Of Month", short: "Weekday Of Month", narrow: "Weekday Of Month" }, dayperiod: { short: "a.m/p.m.", wide: "a.m/p.m.", narrow: "a.m/p.m." }, hour: { wide: "oră", short: "h", narrow: "h" }, minute: { wide: "minut", short: "min.", narrow: "m" }, second: { wide: "secundă", short: "sec.", narrow: "s" }, zone: { wide: "fus orar", short: "fus orar", narrow: "fus orar" } } }, firstDay: 1 });
/** * Env.js * * Released under LGPL License. * Copyright (c) 1999-2015 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * This class contains various environment constants like browser versions etc. * Normally you don't want to sniff specific browser versions but sometimes you have * to when it's impossible to feature detect. So use this with care. * * @class tinymce.Env * @static */ define("tinymce/Env", [], function() { var nav = navigator, userAgent = nav.userAgent; var opera, webkit, ie, ie11, ie12, gecko, mac, iDevice, android, fileApi, phone, tablet, windowsPhone; function matchMediaQuery(query) { return "matchMedia" in window ? matchMedia(query).matches : false; } opera = window.opera && window.opera.buildNumber; android = /Android/.test(userAgent); webkit = /WebKit/.test(userAgent); ie = !webkit && !opera && (/MSIE/gi).test(userAgent) && (/Explorer/gi).test(nav.appName); ie = ie && /MSIE (\w+)\./.exec(userAgent)[1]; ie11 = userAgent.indexOf('Trident/') != -1 && (userAgent.indexOf('rv:') != -1 || nav.appName.indexOf('Netscape') != -1) ? 11 : false; ie12 = (userAgent.indexOf('Edge/') != -1 && !ie && !ie11) ? 12 : false; ie = ie || ie11 || ie12; gecko = !webkit && !ie11 && /Gecko/.test(userAgent); mac = userAgent.indexOf('Mac') != -1; iDevice = /(iPad|iPhone)/.test(userAgent); fileApi = "FormData" in window && "FileReader" in window && "URL" in window && !!URL.createObjectURL; phone = matchMediaQuery("only screen and (max-device-width: 480px)") && (android || iDevice); tablet = matchMediaQuery("only screen and (min-width: 800px)") && (android || iDevice); windowsPhone = userAgent.indexOf('Windows Phone') != -1; if (ie12) { webkit = false; } // Is a iPad/iPhone and not on iOS5 sniff the WebKit version since older iOS WebKit versions // says it has contentEditable support but there is no visible caret. var contentEditable = !iDevice || fileApi || userAgent.match(/AppleWebKit\/(\d*)/)[1] >= 534; return { /** * Constant that is true if the browser is Opera. * * @property opera * @type Boolean * @final */ opera: opera, /** * Constant that is true if the browser is WebKit (Safari/Chrome). * * @property webKit * @type Boolean * @final */ webkit: webkit, /** * Constant that is more than zero if the browser is IE. * * @property ie * @type Boolean * @final */ ie: ie, /** * Constant that is true if the browser is Gecko. * * @property gecko * @type Boolean * @final */ gecko: gecko, /** * Constant that is true if the os is Mac OS. * * @property mac * @type Boolean * @final */ mac: mac, /** * Constant that is true if the os is iOS. * * @property iOS * @type Boolean * @final */ iOS: iDevice, /** * Constant that is true if the os is android. * * @property android * @type Boolean * @final */ android: android, /** * Constant that is true if the browser supports editing. * * @property contentEditable * @type Boolean * @final */ contentEditable: contentEditable, /** * Transparent image data url. * * @property transparentSrc * @type Boolean * @final */ transparentSrc: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", /** * Returns true/false if the browser can or can't place the caret after a inline block like an image. * * @property noCaretAfter * @type Boolean * @final */ caretAfter: ie != 8, /** * Constant that is true if the browser supports native DOM Ranges. IE 9+. * * @property range * @type Boolean */ range: window.getSelection && "Range" in window, /** * Returns the IE document mode for non IE browsers this will fake IE 10. * * @property documentMode * @type Number */ documentMode: ie && !ie12 ? (document.documentMode || 7) : 10, /** * Constant that is true if the browser has a modern file api. * * @property fileApi * @type Boolean */ fileApi: fileApi, /** * Constant that is true if the browser supports contentEditable=false regions. * * @property ceFalse * @type Boolean */ ceFalse: (ie === false || ie > 8), /** * Constant if CSP mode is possible or not. Meaning we can't use script urls for the iframe. */ canHaveCSP: (ie === false || ie > 11), desktop: !phone && !tablet, windowsPhone: windowsPhone }; });
import React, { Component } from 'react'; import { Form, Text, Select } from 'react-form'; import NotificationSystem from 'react-notification-system'; // eslint-disable-next-line const remote = eval("require('electron').remote"); // eslint-disable-next-line const {ipcRenderer} = eval("require('electron')"); let config = { database: {} }; if (remote) { config = remote.getGlobal('config') || {}; } // import 'react-form/layout.css'; // "host": "192.168.1.222", // "username": "hysios", // "password": "asdfasdf", // // "dbname": "SD11831N_WeiXin", // "dbname": "SD11831N_20161101", // "dialect": "mssql" export default class Settings extends Component { constructor(props) { super(props); let {database} = config; this.state = {database}; } render() { return ( <div> <NotificationSystem ref="notificationSystem" position="tc" /> <Form defaultValues={this.state.database} onSubmit={(values) => { this.refs.notificationSystem.addNotification({ message: '保存成功, 配置重启后生效', level: 'success', dismissible: false }); if (ipcRenderer) { console.log(values); config.database = values; ipcRenderer.send("config:save", config); } }} validate={({ host }) => { return { host: !host ? 'A host is required' : undefined } }} > {({submitForm}) => { return ( <form className="settings-form style-1" onSubmit={submitForm}> <Text key='host' field='host' type='text' placeholder='Host' /> <Text key='username' field='username' type='text' placeholder='Username' /> <Text key='password' field='password' type='password' placeholder='Password' /> <Text key='dbname' field='dbname' type='text' placeholder='DBNAME' /> <Select key='dialect' field='dialect' options={[{ id: 1, label: 'Microsoft SQL Server', value: 'mssql' }]} /> <button type="submit" className="btn">保存</button> </form>) }} </Form> </div>); } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = function (selector, context) { // get NodeList, default to document if no context specified var results = (context || document).querySelectorAll(selector); // cast into Array return Array.prototype.slice.call(results); }; ; module.exports = exports["default"];
var express = require('express'); var router = express.Router(); router.get('/', function(req, res, next) { res.render('index', { title: 'Clark Hinchcliff' }); }); module.exports = router;
import angular from 'angular'; /** * Directive that handles the model arrays */ export default function(sel, sfPath, schemaForm) { return { scope: true, controller: ['$scope', function SFArrayController($scope) { this.key = ($scope.form && $scope.form.key) ? $scope.form.key.splice(0, -2) : []; }], link: function(scope, element, attrs) { scope.min = 0; scope.modelArray = scope.$eval(attrs.sfNewArray); // We need to have a ngModel to hook into validation. It doesn't really play well with // arrays though so we both need to trigger validation and onChange. // So we watch the value as well. But watching an array can be tricky. We wan't to know // when it changes so we can validate, var watchFn = function() { //scope.modelArray = modelArray; scope.modelArray = scope.$eval(attrs.sfNewArray); // validateField method is exported by schema-validate if (scope.ngModel && scope.ngModel.$pristine && scope.firstDigest && (!scope.options || scope.options.validateOnRender !== true)) { return; } else if (scope.validateField) { scope.validateField(); } }; var onChangeFn = function() { if (scope.form && scope.form.onChange) { if (angular.isFunction(scope.form.onChange)) { scope.form.onChange(scope.modelArray, scope.form); } else { scope.evalExpr(scope.form.onChange, { 'modelValue': scope.modelArray, form: scope.form }); } } }; // If model is undefined make sure it gets set. var getOrCreateModel = function() { var model = scope.modelArray; if (!model) { var selection = sfPath.parse(attrs.sfNewArray); model = []; sel(selection, scope, model); scope.modelArray = model; } return model; }; // We need the form definition to make a decision on how we should listen. var once = scope.$watch('form', function(form) { if (!form) { return; } // Always start with one empty form unless configured otherwise. // Special case: don't do it if form has a titleMap if (!form.titleMap && form.startEmpty !== true && (!scope.modelArray || scope.modelArray.length === 0)) { scope.appendToArray(); } // If we have "uniqueItems" set to true, we must deep watch for changes. if (scope.form && scope.form.schema && scope.form.schema.uniqueItems === true) { scope.$watch(attrs.sfNewArray, watchFn, true); // We still need to trigger onChange though. scope.$watch([ attrs.sfNewArray, attrs.sfNewArray + '.length' ], onChangeFn); } else { // Otherwise we like to check if the instance of the array has changed, or if something // has been added/removed. if (scope.$watchGroup) { scope.$watchGroup([ attrs.sfNewArray, attrs.sfNewArray + '.length' ], function() { watchFn(); onChangeFn(); }); } else { // Angular 1.2 support scope.$watch(attrs.sfNewArray, function() { watchFn(); onChangeFn(); }); scope.$watch(attrs.sfNewArray + '.length', function() { watchFn(); onChangeFn(); }); } } // Title Map handling // If form has a titleMap configured we'd like to enable looping over // titleMap instead of modelArray, this is used for intance in // checkboxes. So instead of variable number of things we like to create // a array value from a subset of values in the titleMap. // The problem here is that ng-model on a checkbox doesn't really map to // a list of values. This is here to fix that. if (form.titleMap && form.titleMap.length > 0) { scope.titleMapValues = []; // We watch the model for changes and the titleMapValues to reflect // the modelArray var updateTitleMapValues = function(arr) { scope.titleMapValues = []; arr = arr || []; form.titleMap.forEach(function(item) { scope.titleMapValues.push(arr.indexOf(item.value) !== -1); }); }; //Catch default values updateTitleMapValues(scope.modelArray); // TODO: Refactor and see if we can get rid of this watch by piggy backing on the // validation watch. scope.$watchCollection('modelArray', updateTitleMapValues); //To get two way binding we also watch our titleMapValues scope.$watchCollection('titleMapValues', function(vals, old) { if (vals && vals !== old) { var arr = getOrCreateModel(); form.titleMap.forEach(function(item, index) { var arrIndex = arr.indexOf(item.value); if (arrIndex === -1 && vals[index]) { arr.push(item.value); }; if (arrIndex !== -1 && !vals[index]) { arr.splice(arrIndex, 1); }; }); // Time to validate the rebuilt array. // validateField method is exported by schema-validate if (scope.validateField) { scope.validateField(); } } }); } once(); }); scope.arrayErrors = function() { var regExp = /([^0-9]*)([0-9]*)+(.*)/, error = scope.schemaError(); if( error ) { var match = regExp.exec(error.dataPath); if( match[2] ) { return 'Error in '+ scope.interp(scope.form.title, {$index: parseInt(match[2])+1}) + ' - ' + scope.errorMessage(error) } else { return scope.errorMessage(error); } } else { return null; } }; scope.appendToArray = function() { var empty; // Create and set an array if needed. var model = getOrCreateModel(); // Same old add empty things to the array hack :( if (scope.form && scope.form.schema && scope.form.schema.items) { var items = scope.form.schema.items; if (items.type && items.type.indexOf('object') !== -1) { empty = {}; // Check for possible defaults if (!scope.options || scope.options.setSchemaDefaults !== false) { empty = angular.isDefined(items['default']) ? items['default'] : empty; // Check for defaults further down in the schema. // If the default instance sets the new array item to something falsy, i.e. null // then there is no need to go further down. if (empty) { schemaForm.traverseSchema(items, function(prop, path) { if (angular.isDefined(prop['default'])) { sel(path, empty, prop['default']); } }); } } } else if (items.type && items.type.indexOf('array') !== -1) { empty = []; if (!scope.options || scope.options.setSchemaDefaults !== false) { empty = items['default'] || empty; } } else { // No type? could still have defaults. if (!scope.options || scope.options.setSchemaDefaults !== false) { empty = items['default'] || empty; } } } model.push(empty); return model; }; scope.deleteFromArray = function(index) { var model = scope.modelArray; if (model) { model.splice(index, 1); } return model; }; // For backwards compatability, i.e. when a bootstrap-decorator tag is used // as child to the array. var setIndex = function(index) { return function(form) { if (form.key) { form.key[form.key.indexOf('')] = index; } }; }; var formDefCache = {}; scope.copyWithIndex = function(index) { var form = scope.form; if (!formDefCache[index]) { // To be more compatible with JSON Form we support an array of items // in the form definition of "array" (the schema just a value). // for the subforms code to work this means we wrap everything in a // section. Unless there is just one. var subForm = form.items[0]; if (form.items.length > 1) { subForm = { type: 'section', items: form.items.map(function(item) { item.ngModelOptions = form.ngModelOptions; if (angular.isUndefined(item.readonly)) { item.readonly = form.readonly; } return item; }) }; } if (subForm) { var copy = angular.copy(subForm); copy.arrayIndex = index; schemaForm.traverseForm(copy, setIndex(index)); formDefCache[index] = copy; } } return formDefCache[index]; }; } }; }
define([ "Backbone", "./collections/TasksCollection", "./views/MainView" ], function( Backbone, TasksCollection, MainView ) { return { run: function(viewManager) { var tasksCollection = new TasksCollection(); tasksCollection.fetch({ success: function(collection) { var view = new MainView({ collection: collection }); viewManager.show(view); } }); } }; });
'use strict'; var test = require('tape'); var rewire = require('rewire'); var api = require('./PathStore.api'); var PathStore = rewire('../../../src/core/PathStore'); var PathUtilsStub = require('../path/Path.stub'); var helpers = require('./PathStore.helpers'); PathStore.__set__('PathUtils', PathUtilsStub); helpers.setPathStub(PathUtilsStub); test('PathStore class', function (t) { t.test('PathStore constructor', function (t) { t.equal(PathStore.constructor, Function, 'PathStore should be a function'); t.doesNotThrow(function () { return new PathStore(); }, 'PathStore should be able to be called with new'); t.equal((new PathStore()).constructor, PathStore, 'PathStore should be a constructor function'); var pathStore = new PathStore(); api.forEach(function (method) { t.ok( pathStore[method] && pathStore[method].constructor === Function, 'PathStore should have a ' + method + ' method' ); }); t.end(); }); t.test('.insert method', function (t) { var pathStore = new PathStore(); var a = new helpers.InsertTester(1, 0, 'a'); t.doesNotThrow(function () { pathStore.insert('a', a); }, 'insert should be able to be called with a string and any other argument'); t.equal( pathStore.get('a'), a, 'insert should insert the given item at the given path' + ' such that the path can be used to look it up with the get method' ); t.ok( pathStore.getItems().indexOf(a) > -1, 'insert should insert the given item into the store such' + ' that it can be found in the array returned by the getItems method' ); [ [2, 0, 'b'], [2, 1, 'c'], [2, 2, 'd'], [3, 6, 'e'], [1, 4, 'f'], [2, 4, 'g'], [6, 0, 'h'] ].forEach(function (triple) { pathStore.insert(triple[2], new helpers.InsertTester(triple[0], triple[1], triple[2])); }); pathStore.getItems().forEach(function (item, i, items) { t.equal( pathStore.get(item.path), item, 'insert should insert the given item at the given path' + ' such that the path can be used to look it up with the get method' ); t.ok( pathStore.getItems().indexOf(item) > -1, 'insert should insert the given item into the store' + ' such that it can be found in the array returned by the getItems method' ); if (items[i + 1]) { t.ok( items[i + 1].isAfter(items[i]), 'insert should order items such that they are sorted by depth and ties are broken by index' ); } }); t.end(); }); t.test('.remove method', function (t) { var pathStore = new PathStore(); var index; Array.apply(null, Array(10)).map(function (_, i) { return new helpers.InsertTester(i, 0, String.fromCharCode(97 + i)); }).forEach(function (it) { pathStore.insert(it.path, it); }); // sanity check if (pathStore.getItems().length !== 10) throw new Error('PathStore.insert is broken'); function removeItem (i) { var ch = String.fromCharCode(i + 97); var b = pathStore.get(ch); if (b) { t.doesNotThrow(function () { pathStore.remove(ch); }, 'remove should be able to be called and remove an item by key'); t.equal(pathStore.get(ch), undefined, '.remove should remove the item at the path'); t.equal( pathStore.getItems().indexOf(b), -1, 'removed items should not be available in the array returned by getItems' ); return true; } return false; } function checkOrder () { pathStore.getItems().forEach(function (item, i, items) { if (items[i + 1]) { t.ok( items[i + 1].isAfter(items[i]), 'remove should preserve the sort of the items in PathStore' ); } }); } while (pathStore.getItems().length) { index = (Math.random() * 11)|0; if (removeItem(index)) checkOrder(); } t.end(); }); t.end(); });
module.exports = require('./lib/tls-sip-probe');
/** @module leancloud-realtime */ import d from 'debug'; import uuid from 'uuid/v4'; import IMClient from './im-client'; import { RECONNECT, RECONNECT_ERROR } from './events/core'; import { Conversation } from './conversations'; import { MessageQueryDirection } from './conversations/conversation-base'; import Message, { MessageStatus } from './messages/message'; import BinaryMessage from './messages/binary-message'; import TextMessage from './messages/text-message'; import TypedMessage from './messages/typed-message'; import RecalledMessage from './messages/recalled-message'; import MessageParser from './message-parser'; import { trim, internal, finalize } from './utils'; const debug = d('LC:IMPlugin'); /** * 消息优先级枚举 * @enum {Number} * @since 3.3.0 */ const MessagePriority = { /** 高 */ HIGH: 1, /** 普通 */ NORMAL: 2, /** 低 */ LOW: 3, }; Object.freeze(MessagePriority); /** * 为 Conversation 定义一个新属性 * @param {String} prop 属性名 * @param {Object} [descriptor] 属性的描述符,参见 {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description getOwnPropertyDescriptor#Description - MDN},默认为该属性名对应的 Conversation 自定义属性的 getter/setter * @returns void * @example * * conversation.get('type'); * conversation.set('type', 1); * * // equals to * defineConversationProperty('type'); * conversation.type; * conversation.type = 1; */ const defineConversationProperty = ( prop, descriptor = { get() { return this.get(prop); }, set(value) { this.set(prop, value); }, } ) => { Object.defineProperty(Conversation.prototype, prop, descriptor); }; export { /** * @see Message */ Message, /** * @see BinaryMessage */ BinaryMessage, /** * @see TypedMessage */ TypedMessage, /** * @see TextMessage */ TextMessage, /** * @see RecalledMessage */ RecalledMessage, MessagePriority, MessageStatus, MessageQueryDirection, defineConversationProperty, }; export { /** * decorator,定义消息类的类型常量 * @function * @param {Number} type 自定义类型请使用正整数 * @example @messageType(1) * class CustomMessage extends TypedMessage {} * * // 不支持 decorator 的情况下可以这样使用 * class CustomMessage extends TypedMessage { * //... * } * messageType(1)(CustomMessage); */ messageType, /** * decorator,定义消息类的自定义字段 * @function * @param {String[]} fields 自定义字段 * @example @messageField(['foo']) * class CustomMessage extends TypedMessage { * constructor(foo) { * super(); * this.foo = foo; * } * } * * // 不支持 decorator 的情况下可以这样使用 * class CustomMessage extends TypedMessage { * constructor(foo) { * super(); * this.foo = foo; * } * //... * } * messageField(['foo'])(CustomMessage); */ messageField, IE10Compatible, } from './messages/helpers'; export { ConversationMemberRole } from './conversation-member-info'; export { /** * @see Conversation */ Conversation, /** * @see ChatRoom */ ChatRoom, /** * @see ServiceConversation */ ServiceConversation, /** * @see TemporaryConversation */ TemporaryConversation, } from './conversations'; const onRealtimeCreate = realtime => { /* eslint-disable no-param-reassign */ const deviceId = uuid(); realtime._IMClients = {}; realtime._IMClientsCreationCount = 0; const messageParser = new MessageParser(realtime._plugins); realtime._messageParser = messageParser; const signAVUser = async user => realtime._request({ method: 'POST', path: '/rtm/sign', data: { session_token: user.getSessionToken(), }, }); /** * 注册消息类 * * 在接收消息、查询消息时,会按照消息类注册顺序的逆序依次尝试解析消息内容 * * @memberof Realtime * @instance * @param {Function | Function[]} messageClass 消息类,需要实现 {@link AVMessage} 接口, * 建议继承自 {@link TypedMessage} * @throws {TypeError} 如果 messageClass 没有实现 {@link AVMessage} 接口则抛出异常 */ const register = messageParser.register.bind(messageParser); /** * 创建一个即时通讯客户端,多次创建相同 id 的客户端会返回同一个实例 * @memberof Realtime * @instance * @param {String|AV.User} [identity] 客户端 identity,如果不指定该参数,服务端会随机生成一个字符串作为 identity, * 如果传入一个已登录的 AV.User,则会使用该用户的 id 作为客户端 identity 登录。 * @param {Object} [options] * @param {Function} [options.signatureFactory] open session 时的签名方法 // TODO need details * @param {Function} [options.conversationSignatureFactory] 对话创建、增减成员操作时的签名方法 * @param {Function} [options.blacklistSignatureFactory] 黑名单操作时的签名方法 * @param {String} [options.tag] 客户端类型标记,以支持单点登录功能 * @param {String} [options.isReconnect=false] 单点登录时标记该次登录是不是应用启动时自动重新登录 * @return {Promise.<IMClient>} */ const createIMClient = async ( identity, { tag, isReconnect, ...clientOptions } = {}, lagecyTag ) => { let id; const buildinOptions = {}; if (identity) { if (typeof identity === 'string') { id = identity; } else if (identity.id && identity.getSessionToken) { ({ id } = identity); const sessionToken = identity.getSessionToken(); if (!sessionToken) { throw new Error('User must be authenticated'); } buildinOptions.signatureFactory = signAVUser; } else { throw new TypeError('Identity must be a String or an AV.User'); } if (realtime._IMClients[id] !== undefined) { return realtime._IMClients[id]; } } if (lagecyTag) { console.warn( 'DEPRECATION createIMClient tag param: Use options.tag instead.' ); } const _tag = tag || lagecyTag; const promise = realtime ._open() .then(connection => { const client = new IMClient( id, { ...buildinOptions, ...clientOptions }, { _connection: connection, _request: realtime._request.bind(realtime), _messageParser: messageParser, _plugins: realtime._plugins, _identity: identity, } ); connection.on(RECONNECT, () => client ._open(realtime._options.appId, _tag, deviceId, true) /** * 客户端连接恢复正常,该事件通常在 {@link Realtime#event:RECONNECT} 之后发生 * @event IMClient#RECONNECT * @see Realtime#event:RECONNECT * @since 3.2.0 */ /** * 客户端重新登录发生错误(网络连接已恢复,但重新登录错误) * @event IMClient#RECONNECT_ERROR * @since 3.2.0 */ .then( () => client.emit(RECONNECT), error => client.emit(RECONNECT_ERROR, error) ) ); internal(client)._eventemitter.on( 'beforeclose', () => { delete realtime._IMClients[client.id]; if (realtime._firstIMClient === client) { delete realtime._firstIMClient; } }, realtime ); internal(client)._eventemitter.on( 'close', () => { realtime._deregister(client); }, realtime ); return client ._open(realtime._options.appId, _tag, deviceId, isReconnect) .then(() => { realtime._IMClients[client.id] = client; realtime._IMClientsCreationCount += 1; if (realtime._IMClientsCreationCount === 1) { client._omitPeerId(true); realtime._firstIMClient = client; } else if ( realtime._IMClientsCreationCount > 1 && realtime._firstIMClient ) { realtime._firstIMClient._omitPeerId(false); } realtime._register(client); return client; }) .catch(error => { delete realtime._IMClients[client.id]; throw error; }); }) .then( ...finalize(() => { realtime._deregisterPending(promise); }) ) .catch(error => { delete realtime._IMClients[id]; throw error; }); if (identity) { realtime._IMClients[id] = promise; } realtime._registerPending(promise); return promise; }; Object.assign(realtime, { register, createIMClient, }); /* eslint-enable no-param-reassign */ }; const beforeCommandDispatch = (command, realtime) => { const isIMCommand = command.service === null || command.service === 2; if (!isIMCommand) return true; const targetClient = command.peerId ? realtime._IMClients[command.peerId] : realtime._firstIMClient; if (targetClient) { Promise.resolve(targetClient) .then(client => client._dispatchCommand(command)) .catch(debug); } else { debug( '[WARN] Unexpected message received without any live client match: %O', trim(command) ); } return false; }; export const IMPlugin = { name: 'leancloud-realtime-plugin-im', onRealtimeCreate, beforeCommandDispatch, messageClasses: [Message, BinaryMessage, RecalledMessage, TextMessage], };
import { Router } from 'express' import path from 'path' import React from 'react' import ReactDOMServer from 'react-dom/server' import createApp from 'create-app/lib/server' import util from '../util' const { getFlatList } = util const getModule = module => module.default || module const commonjsLoader = (loadModule, location, context) => { return loadModule(location, context).then(getModule) } /** * controller 里会劫持 React.createElement * server side 场景缺乏恢复机制 * 因此在这里特殊处理,在渲染完后,恢复 React.createElement */ const createElement = React.createElement const renderToNodeStream = (view, controller) => { return new Promise((resolve, reject) => { let stream = ReactDOMServer.renderToNodeStream(view) let buffers = [] stream.on('data', chunk => buffers.push(chunk)) stream.on('end', () => { React.createElement = createElement resolve(Buffer.concat(buffers)) }) stream.on('error', error => { if (!controller) { React.createElement = createElement return reject(error) } if (controller.errorDidCatch) { controller.errorDidCatch(error, 'view') } if (controller.getViewFallback) { let fallbackView = controller.getViewFallback('view') renderToNodeStream(fallbackView).then(resolve, reject) } else { React.createElement = createElement reject(error) } }) }) } const renderToString = (view, controller) => { try { return ReactDOMServer.renderToString(view) } catch (error) { if (!controller) throw error if (controller.errorDidCatch) { controller.errorDidCatch(error, 'view') } if (controller.getViewFallback) { let fallbackView = controller.getViewFallback() return renderToString(fallbackView) } else { throw error } } finally { React.createElement = createElement } } const renderers = { renderToNodeStream, renderToString } export default function createPageRouter(options) { let config = Object.assign({}, options) let routes if (config.useServerBundle) { routes = require(path.join(config.root, config.serverBundleName)) } else { routes = require(path.join(config.root, config.src)) } routes = routes.default || routes if (!Array.isArray(routes)) { routes = Object.values(routes) } routes = getFlatList(routes) let router = Router() let render = renderers[config.renderMode] || renderToNodeStream let serverAppSettings = { loader: commonjsLoader, routes: routes, viewEngine: { render } } let app = createApp(serverAppSettings) let layoutView = config.layout || path.join(__dirname, 'view') // 纯浏览器端渲染模式,用前置中间件拦截所有请求 if (config.SSR === false) { router.all('*', (req, res) => { res.render(layoutView) }) } else if (config.NODE_ENV === 'development') { // 带服务端渲染模式的开发环境,需要动态编译 src/routes var setupDevEnv = require('../build/setup-dev-env') setupDevEnv.setupServer(config, { handleHotModule: $routes => { const routes = getFlatList( Array.isArray($routes) ? $routes : Object.values($routes) ) app = createApp({ ...serverAppSettings, routes }) } }) } // handle page router.all('*', async (req, res, next) => { let { basename, serverPublicPath, publicPath } = req let context = { basename, serverPublicPath, publicPath, restapi: config.serverRestapi || config.restapi || '', ...config.context, preload: {}, isServer: true, isClient: false, req, res } try { let { content, controller } = await app.render(req.url, context) /** * 如果没有返回 content * 不渲染内容,controller 可能通过 context.res 对象做了重定向或者渲染 */ if (!content) { return } // content 可能是异步渲染的 content = await content let initialState = controller.store ? controller.store.getState() : undefined let htmlConfigs = initialState ? initialState.html : undefined let data = { ...htmlConfigs, content, initialState } if (controller.destory) { controller.destory() } // 支持通过 res.locals.layoutView 动态确定 layoutView res.render(res.locals.layoutView || layoutView, data) } catch (error) { next(error) } }) return router }
import env from '../../src/util/env'; import gtTimer from '../../src/graviton/timer'; describe('timer', () => { let window; beforeEach(() => { window = jasmine.createSpyObj('window', [ 'requestAnimationFrame', 'cancelAnimationFrame', 'setInterval', 'clearInterval' ]); window.performance = jasmine.createSpyObj('performance', ['now']); spyOn(env, 'getWindow').and.returnValue(window); }); describe('animation', () => { let spy, timer; beforeEach(() => { spy = jasmine.createSpy('callback'); timer = new gtTimer(spy); }); it('should not begin animation immediately', () => { expect(window.requestAnimationFrame).not.toHaveBeenCalled(); expect(spy).not.toHaveBeenCalled(); }); it('should begin animating when start is called', () => { timer.start(); expect(window.requestAnimationFrame).toHaveBeenCalled(); expect(window.setInterval).not.toHaveBeenCalled(); }); it('should call the target with the elapsed time', () => { let called = false; window.requestAnimationFrame.and.callFake(fn => { if (!called) { called = true; fn(500); } }); window.performance.now.and.returnValue(100); timer.start(); expect(window.performance.now).toHaveBeenCalled(); expect(spy).toHaveBeenCalledWith(400); }); it('should clear the animation when stopped', () => { window.requestAnimationFrame.and.returnValue(5); timer.start(); timer.stop(); expect(window.cancelAnimationFrame).toHaveBeenCalledWith(5); }); it('should toggle between start and stopped', () => { timer.toggle(); expect(window.requestAnimationFrame).toHaveBeenCalled(); expect(window.cancelAnimationFrame).not.toHaveBeenCalled(); window.requestAnimationFrame.calls.reset(); window.cancelAnimationFrame.calls.reset(); timer.toggle(); expect(window.requestAnimationFrame).not.toHaveBeenCalled(); expect(window.cancelAnimationFrame).toHaveBeenCalled(); }); }); describe('interval', () => { let spy, timer; beforeEach(() => { spy = jasmine.createSpy('callback'); timer = new gtTimer(spy, 60); }); it('should not begin the interval immediately', () => { expect(window.setInterval).not.toHaveBeenCalled(); }); it('should call setInterval with the appropriate timeout', () => { timer.start(); // Expect 60 fps, meaning a timeout of 16ms expect(window.setInterval).toHaveBeenCalledWith(jasmine.any(Function), 16); }); it('should clear the interval when stopped', () => { window.setInterval.and.returnValue(5); timer.start(); timer.stop(); expect(window.clearInterval).toHaveBeenCalledWith(5); }); it('should toggle between start and stopped', () => { timer.toggle(); expect(window.setInterval).toHaveBeenCalled(); expect(window.clearInterval).not.toHaveBeenCalled(); window.setInterval.calls.reset(); window.clearInterval.calls.reset(); timer.toggle(); expect(window.setInterval).not.toHaveBeenCalled(); expect(window.clearInterval).toHaveBeenCalled(); }); }); });
import React from 'react'; import ReactDOM from'react-dom'; import {Paper} from 'material-ui'; import ReactQuill from 'react-quill'; import PostSkeleton from './PostSkeleton'; const style= {margin: '1em', height: '100px', overflow: 'scroll'}; class TextEdit extends React.Component { constructor(props) { super(props); this.state = { value: 'dfgdg' }; } render() { return ( <PostSkeleton edit='true'> <ReactQuill value={this.state.value} theme="snow"/ > </PostSkeleton> )} }; export default TextEdit;
"use strict"; (function(exports){ function setAttributes(e, map){ for(var key in map){ e.setAttribute(key, map[key]); } } function setStyles(e, map){ for(var key in map){ e.style[key] = map[key]; } } function getOpt(opts, key, defaultValue){ if( opts && key in opts ){ return opts[key]; } else { return defaultValue; } } function createScreen(zIndex, opacity){ var screen = document.createElement("div"); setStyles(screen, { position:"fixed", backgroundColor:"#999", width:"100%", height:"100%", left:0, top:0, opacity: opacity, filter:"alpha(opacity=" + Math.round(opacity*100) + ")", zIndex: zIndex, //display:"none" }) return screen; } function createDialog(zIndex){ var dialog = document.createElement("div"); setStyles(dialog, { //position:"absolute", position:"absolute", left:"100px", top:"50px", padding:"10px", border:"2px solid gray", backgroundColor:"white", opacity:1.0, filter:"alpha(opacity=100)", zIndex: zIndex, overflow: "auto" }) return dialog; } function Header(title){ var header = document.createElement("table"); setAttributes(header, { width: "100%", cellpadding: "0", cellspacing: "0" }); setStyles(header, { margin: "0", padding: "0" }); var tbody = document.createElement("tbody"); header.appendChild(tbody); var tr = document.createElement("tr"); tbody.appendChild(tr); var titleDom = document.createElement("td"); titleDom.setAttribute("width", "*"); titleDom.appendChild(createTitle(title)); tr.appendChild(titleDom); var td = document.createElement("td"); td.setAttribute("width", "auto"); setStyles(td, { width:"16px", verticalAlign:"middle" }); var closeBox = createCloseBox(); td.appendChild(closeBox); tr.appendChild(td); return { dom: header, handle: titleDom, closeBox: closeBox } } function bindHandle(handler, dialog){ handler.addEventListener("mousedown", function(event){ event.preventDefault(); event.stopPropagation(); var startX = event.pageX; var startY = event.pageY; var offsetX = dialog.offsetLeft; var offsetY = dialog.offsetTop; document.addEventListener("mousemove", mousemoveHandler); document.addEventListener("mouseup", function(event){ document.removeEventListener("mousemove", mousemoveHandler); }); function mousemoveHandler(event){ var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; var dialogWidth = dialog.offsetWidth; var dialogHeight = dialog.offsetHeight; var currX = event.pageX; var currY = event.pageY; var newLeft = offsetX + (currX - startX); if( newLeft + dialogWidth > windowWidth ){ newLeft = windowWidth - dialogWidth; } if( newLeft < 0 ){ newLeft = 0; } var newTop = offsetY + (currY - startY); if( newTop + dialogHeight > windowHeight ){ newTop = windowHeight - dialogHeight; } if( newTop < 0 ){ newTop = 0; } dialog.style.left = newLeft + "px"; dialog.style.top = newTop + "px"; } }) } function createTitle(titleLabel){ var handle = document.createElement("div"); var title = document.createElement("div"); setStyles(title, { cursor:"move", backgroundColor:"#ccc", fontWeight:"bold", padding:"6px 4px 4px 4px" }); title.appendChild(document.createTextNode(titleLabel)); handle.appendChild(title); return handle; } function createCloseBox(){ var closeBox = document.createElement("a"); closeBox.setAttribute("href", "javascript:void(0)"); setStyles(closeBox, { fontSize:"13px", fontWeight:"bold", margin:"4px 0 4px 4px", padding:0, textDecoration:"none", color:"#333" }); closeBox.appendChild(document.createTextNode("×")); return closeBox; } function createContent(){ var content = document.createElement("div"); content.style.marginTop = "10px"; return content; } function ModalDialog(opts){ this.screenZIndex = getOpt(opts, "scrrenZIndex", 10); this.screenOpacity = getOpt(opts, "screenOpacity", 0.5); this.dialogZIndex = getOpt(opts, "dialogZIndex", 11); this.title = getOpt(opts, "title", "Untitled"); this.onCloseClick = getOpt(opts, "onCloseClick", null); this.position = opts.position; this.maxHeight = opts.maxHeight; } ModalDialog.prototype.open = function(){ var screen = createScreen(this.screenZIndex, this.screenOpacity); //screen.style.display = "block"; document.body.appendChild(screen); var dialog = createDialog(this.dialogZIndex); if( this.position ){ dialog.style.position = this.position; if( this.position === "fixed" ){ dialog.style.maxHeight = (window.innerHeight - 90) + "px"; dialog.style.overflowY = "auto"; } } document.body.appendChild(dialog); var header = new Header(this.title); dialog.appendChild(header.dom); bindHandle(header.handle, dialog); header.closeBox.addEventListener("click", onClose.bind(this)); var content = createContent(this.content); dialog.appendChild(content); this.screen = screen; this.dialog = dialog; this.content = content; this.reposition(); function onClose(event){ event.preventDefault(); if( this.onCloseClick && this.onCloseClick() === false ){ return; } this.close(); } }; ModalDialog.prototype.reposition = function(){ if( !this.dialog ){ return; } var dialog = this.dialog; var space = window.innerWidth - dialog.offsetWidth; if( space > 0 ){ dialog.style.left = Math.floor(space / 2) + "px"; } } ModalDialog.prototype.close = function(){ document.body.removeChild(this.dialog); document.body.removeChild(this.screen); } // Example ---------------------------------------------- // // startModal({ // title: "Test", // init: function(content, close){ // var a = document.createElement("button"); // a.setAttribute("href", "javascript:void(0)"); // a.addEventListener("click", function(event){ // close(); // }); // a.appendChild(document.createTextNode("Close")); // content.innerHTML = "Hello, world!"; // content.appendChild(a); // console.log(this.screenZIndex); // }, // onCloseClick: function(){ // console.log("close box clicked"); // // return false // if not to close dialog // } // }); // exports.startModal = function(opts){ if( !opts ){ opts = {}; } var modalDialog = new ModalDialog(opts); modalDialog.open({ position: opts.position }); if( opts.init ){ opts.init.call(modalDialog, modalDialog.content, function(){ modalDialog.close(); }); modalDialog.reposition(); } } })(typeof exports !== "undefined" ? exports : window);
version https://git-lfs.github.com/spec/v1 oid sha256:4c2353b8e357b6697089c454867613efd7e0b8a0b510d97497ca256ee94086ac size 113530
const { convertSlashesInPath } = require("./projectHelpers"); module.exports = function (source, map) { this.cacheable(); const { modules } = this.query; const imports = modules.map(convertSlashesInPath) .map(m => `require("${m}");`).join("\n"); const augmentedSource = ` const isAndroid = require("@nativescript/core").isAndroid; if (isAndroid && !global["__snapshot"]) { ${imports} } ${source} `; this.callback(null, augmentedSource, map); };
var entity = function() { this.width = 0; this.height = 0; this.scale = 1; this.x = 0; this.y = 0; this.image = null; this.imageWidth = 0; this.imageHeight = 0; }; entity.prototype = entity; entity.prototype.init = function(width, height, scale) { this.width = width; this.height = height; this.scale = scale; this.x = 0; this.y = 0; } entity.prototype.draw = function(ctx) { alert("this is base entity"); } entity.prototype.setImage = function(img, imgWidth, imgHeight) { this.image = img; this.imageWidth = imgWidth; this.imageHeight = imgHeight; } entity.prototype.setPos = function(x,y) { this.x = x; this.y = y; } entity.prototype.moveRight = function(shift) { this.x += shift; } entity.prototype.moveLeft = function(shift) { this.x -= shift; } entity.prototype.moveUp = function(shift) { this.y -= shift; } entity.prototype.moveDown = function(shift) { this.y += shift; }
var React = require('react'); var flickrLiveStore = require('../stores/flickrLiveStore'); var flickrSearchStore = require('../stores/flickrSearchStore'); var flickrSaveStore = require('../stores/flickrSaveStore'); var Flickr = require('./Flickr'); var FlickrControl = require('./FlickrControl'); var flickrActions = require('../actions/flickrActions'); var ImageSave = require('./ImageSave'); var LoadLive = require('./LoadLive'); var LoadSaved = require('./LoadSaved'); var ShowMsg = require('./ShowMsg'); var AutoPlay = require('./AutoPlay'); var FlickrSearch = require('./FlickrSearch'); var keepAliveActions = require('../actions/keepAliveActions'); var loadConstants = require('../constants/loadConstants'); var fetchCount = 100; //*******Utility functions******* function fetchSearch(count, searchText, page) { flickrActions.flickrSearchAction(count, searchText, page+1); } function clearMsg() { flickrActions.saveImageMsgClear(); } function saveIndex(mode, storage, index) { if (mode == 'live') { storage.live = index; } if (mode == 'saved') { storage.saved = index; } if (mode == 'search') { storage.search = index; } } //*******End - Utility functions******* var FlickrContainer = React.createClass({ getInitialState: function () { this.rightClicked = false; this.currentUrls = []; this.mode = "live"; this.savedIndex = {live: 0, saved: 0, search: 0}; this.liveIndex = 0; this.searchIndex = 0; this.searchOpt = {page: 0, text: ''}; var okIcon = [false, false, false]; okIcon[loadConstants.indexLoadLive] = true; return { urls: flickrLiveStore.getUrls(), imageIndex: 0, maxIndex: fetchCount, saveMsg: flickrSaveStore.getMsg(), okIcon: okIcon }; }, componentDidMount: function () { flickrLiveStore.addFlickrListener(this._onChange); flickrLiveStore.addRestoreLiveListener(this._onRestoreLiveChange); flickrSearchStore.addFlickrListener(this._onSearchChange); flickrSearchStore.addRestoreSearchListener(this._onRestoreSearchChange); flickrSaveStore.addSaveListener(this._onSaveChange); flickrSaveStore.addLoadListener(this._onLoadChange); flickrActions.flickrFetchAction(fetchCount); document.body.background = 'src/leaf-green-background.jpg'; }, componentWillUnmount: function () { flickrLiveStore.removeFlickrListener(this._onChange); flickrLiveStore.removeRestoreLiveListener(this._onRestoreLiveChange); flickrSearchStore.removeFlickrListener(this._onSearchChange); flickrSearchStore.removeRestoreSearchListener(this._onRestoreSearchChange); flickrSaveStore.removeSaveListener(this._onSaveChange); flickrSaveStore.removeLoadListener(this._onLoadChange); }, setMaxIndex: function(val) { this.setState({ maxIndex: val }); }, //*******Store Events******* _onChange: function () { var moreUrls = flickrLiveStore.getUrls(); this.setState({ urls: moreUrls }); this.setMaxIndex(this.state.urls.length); if (this.rightClicked) { this.rightClicked = false; this.incrementIndex(); } }, _onSearchChange: function() { var searchUrls = flickrSearchStore.getUrls(); this.setState({ urls: searchUrls }); //new search item if (this.searchOpt.page == 0) { this.setIndex(0); } this.setMaxIndex(this.state.urls.length); if (this.rightClicked) { this.rightClicked = false; this.incrementIndex(); } }, _onSaveChange: function() { var msg = flickrSaveStore.getMsg(); this.setState({ saveMsg: msg }); }, _onLoadChange: function() { var savedUrls = flickrSaveStore.getUrls(); this.setMaxIndex(savedUrls.length); this.setState({ urls: savedUrls, imageIndex: this.savedIndex.saved }) }, _onRestoreLiveChange: function() { var urls = flickrLiveStore.getUrls(); this.setMaxIndex(urls.length); this.setState({ urls: urls, imageIndex: this.savedIndex.live }); }, _onRestoreSearchChange: function() { var urls = flickrSearchStore.getUrls(); this.setMaxIndex(urls.length); this.setState({ urls: urls, imageIndex: this.savedIndex.search }); }, //*******End - Store Events******* //*******Index setting and navigation****** setIndex: function(val) { this.setState({ imageIndex: val }); }, incrementIndex: function() { var index = this.state.imageIndex + 1; this.setIndex(index); }, decrementIndex: function() { var index = this.state.imageIndex - 1; this.setIndex(index); }, leftClick: function() { keepAliveActions.keepAlive(); flickrActions.autoPlayStop(); if (this.state.imageIndex == 0) return; clearMsg(); this.decrementIndex(); }, rightClick: function() { keepAliveActions.keepAlive(); //without this, same images will be fetched twice if (this.rightClicked) return; if (this.state.imageIndex == this.state.maxIndex-1) { //this prevents loading of more images. if (this.mode=='saved') return; if (this.mode=='live') flickrActions.flickrFetchAction(fetchCount); if (this.mode=='search') { var text = this.searchOpt.text; var page = ++this.searchOpt.page; fetchSearch(fetchCount, text, page); } this.rightClicked = true; return; } clearMsg(); this.incrementIndex(); }, //*******End - Index setting and navigation****** //*******View event callbacks******* indexHandler: function(value) { value -= 1; if (value < 0) value = 0; if (value >= this.state.maxIndex-1) value = this.state.maxIndex-1; this.setIndex(value); }, saveImage: function() { if (this.mode == 'saved') return; var currentUrl = this.state.urls[this.state.imageIndex]; flickrActions.saveImage(currentUrl); }, loadLive: function() { if (this.mode == 'live') return; saveIndex(this.mode, this.savedIndex, this.state.imageIndex); this.mode = 'live'; flickrActions.loadLiveImages(); this.setOkIcon(loadConstants.indexLoadLive); }, loadSaved: function() { if (this.mode == 'saved') return; saveIndex(this.mode, this.savedIndex, this.state.imageIndex); this.mode = 'saved'; flickrActions.loadSavedImages(); this.setOkIcon(loadConstants.indexLoadSaved); }, searchText: function(value) { if (this.mode == 'search' && value == this.searchOpt.text) return; saveIndex(this.mode, this.savedIndex, this.state.imageIndex); this.mode = 'search'; if (value != this.searchOpt.text) { console.log('doing new search'); this.searchOpt.page = 0; this.searchOpt.text = value; flickrActions.flickrNewSearchAction(fetchCount, value, 1); } else { console.log('same search found'); flickrActions.loadSearchImages(); } this.setOkIcon(loadConstants.indexLoadSearch); }, autoPlay: function() { //console.log('auto play'); this.rightClick(); }, setOkIcon: function(index) { var icons = [false, false, false]; icons[index] = true; this.setState({ okIcon: icons }); }, //*******End - View event callbacks******* render: function () { return ( <div> <FlickrControl left={this.leftClick} right={this.rightClick} index={this.state.imageIndex+1} max={this.state.maxIndex} handler={this.indexHandler}></FlickrControl> <br/> <div className="container-fluid"> <div className="row"> <div className="col-md-6"> <Flickr image={this.state.urls[this.state.imageIndex]}></Flickr> </div> <div className="col-md-5 col-md-offset-1"> <div className="list-group"> <ImageSave save={this.saveImage}></ImageSave> <LoadSaved handler={this.loadSaved} ok={this.state.okIcon}></LoadSaved> <LoadLive handler={this.loadLive} ok={this.state.okIcon}></LoadLive> <FlickrSearch handler={this.searchText} ok={this.state.okIcon}></FlickrSearch> </div> <AutoPlay handler={this.autoPlay}></AutoPlay> </div> </div> </div> <br/> <ShowMsg msg={this.state.saveMsg.msg} error={this.state.saveMsg.error}></ShowMsg> </div> ); } }); module.exports = FlickrContainer;
/** * videojs-contrib-media-sources * @version 3.1.0 * @copyright 2016 Brightcove, Inc. * @license Apache-2.0 */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojsContribMediaSources = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * mux.js * * Copyright (c) 2016 Brightcove * All rights reserved. * * A stream-based aac to mp4 converter. This utility can be used to * deliver mp4s to a SourceBuffer on platforms that support native * Media Source Extensions. */ 'use strict'; var Stream = require('../utils/stream.js'); // Constants var AacStream; /** * Splits an incoming stream of binary data into ADTS and ID3 Frames. */ AacStream = function() { var everything = new Uint8Array(), receivedTimeStamp = false, timeStamp = 0; AacStream.prototype.init.call(this); this.setTimestamp = function (timestamp) { timeStamp = timestamp; }; this.parseId3TagSize = function(header, byteIndex) { var returnSize = (header[byteIndex + 6] << 21) | (header[byteIndex + 7] << 14) | (header[byteIndex + 8] << 7) | (header[byteIndex + 9]), flags = header[byteIndex + 5], footerPresent = (flags & 16) >> 4; if (footerPresent) { return returnSize + 20; } return returnSize + 10; }; this.parseAdtsSize = function(header, byteIndex) { var lowThree = (header[byteIndex + 5] & 0xE0) >> 5, middle = header[byteIndex + 4] << 3, highTwo = header[byteIndex + 3] & 0x3 << 11; return (highTwo | middle) | lowThree; }; this.push = function(bytes) { var frameSize = 0, byteIndex = 0, bytesLeft, chunk, packet, tempLength; // If there are bytes remaining from the last segment, prepend them to the // bytes that were pushed in if (everything.length) { tempLength = everything.length; everything = new Uint8Array(bytes.byteLength + tempLength); everything.set(everything.subarray(0, tempLength)); everything.set(bytes, tempLength); } else { everything = bytes; } while (everything.length - byteIndex >= 3) { if ((everything[byteIndex] === 'I'.charCodeAt(0)) && (everything[byteIndex + 1] === 'D'.charCodeAt(0)) && (everything[byteIndex + 2] === '3'.charCodeAt(0))) { // Exit early because we don't have enough to parse // the ID3 tag header if (everything.length - byteIndex < 10) { break; } // check framesize frameSize = this.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer // to emit a full packet if (frameSize > everything.length) { break; } chunk = { type: 'timed-metadata', data: everything.subarray(byteIndex, byteIndex + frameSize) }; this.trigger('data', chunk); byteIndex += frameSize; continue; } else if ((everything[byteIndex] & 0xff === 0xff) && ((everything[byteIndex + 1] & 0xf0) === 0xf0)) { // Exit early because we don't have enough to parse // the ADTS frame header if (everything.length - byteIndex < 7) { break; } frameSize = this.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer // to emit a full packet if (frameSize > everything.length) { break; } packet = { type: 'audio', data: everything.subarray(byteIndex, byteIndex + frameSize), pts: timeStamp, dts: timeStamp, }; this.trigger('data', packet); byteIndex += frameSize; continue; } byteIndex++; } bytesLeft = everything.length - byteIndex; if (bytesLeft > 0) { everything = everything.subarray(byteIndex); } else { everything = new Uint8Array(); } }; }; AacStream.prototype = new Stream(); module.exports = AacStream; },{"../utils/stream.js":20}],2:[function(require,module,exports){ 'use strict'; var Stream = require('../utils/stream.js'); var AdtsStream; var ADTS_SAMPLING_FREQUENCIES = [ 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 ]; /* * Accepts a ElementaryStream and emits data events with parsed * AAC Audio Frames of the individual packets. Input audio in ADTS * format is unpacked and re-emitted as AAC frames. * * @see http://wiki.multimedia.cx/index.php?title=ADTS * @see http://wiki.multimedia.cx/?title=Understanding_AAC */ AdtsStream = function() { var self, buffer; AdtsStream.prototype.init.call(this); self = this; this.push = function(packet) { var i = 0, frameNum = 0, frameLength, protectionSkipBytes, frameEnd, oldBuffer, numFrames, sampleCount, adtsFrameDuration; if (packet.type !== 'audio') { // ignore non-audio data return; } // Prepend any data in the buffer to the input data so that we can parse // aac frames the cross a PES packet boundary if (buffer) { oldBuffer = buffer; buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength); buffer.set(oldBuffer); buffer.set(packet.data, oldBuffer.byteLength); } else { buffer = packet.data; } // unpack any ADTS frames which have been fully received // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS while (i + 5 < buffer.length) { // Loook for the start of an ADTS header.. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) { // If a valid header was not found, jump one forward and attempt to // find a valid ADTS header starting at the next byte i++; continue; } // The protection skip bit tells us if we have 2 bytes of CRC data at the // end of the ADTS header protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the // end of the sync sequence frameLength = ((buffer[i + 3] & 0x03) << 11) | (buffer[i + 4] << 3) | ((buffer[i + 5] & 0xe0) >> 5); sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024; adtsFrameDuration = (sampleCount * 90000) / ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2]; frameEnd = i + frameLength; // If we don't have enough data to actually finish this ADTS frame, return // and wait for more data if (buffer.byteLength < frameEnd) { return; } // Otherwise, deliver the complete AAC frame this.trigger('data', { pts: packet.pts + (frameNum * adtsFrameDuration), dts: packet.dts + (frameNum * adtsFrameDuration), sampleCount: sampleCount, audioobjecttype: ((buffer[i + 2] >>> 6) & 0x03) + 1, channelcount: ((buffer[i + 2] & 1) << 3) | ((buffer[i + 3] & 0xc0) >>> 6), samplerate: ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2], samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2, // assume ISO/IEC 14496-12 AudioSampleEntry default of 16 samplesize: 16, data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd) }); // If the buffer is empty, clear it and return if (buffer.byteLength === frameEnd) { buffer = undefined; return; } frameNum++; // Remove the finished frame from the buffer and start the process again buffer = buffer.subarray(frameEnd); } }; this.flush = function() { this.trigger('done'); }; }; AdtsStream.prototype = new Stream(); module.exports = AdtsStream; },{"../utils/stream.js":20}],3:[function(require,module,exports){ 'use strict'; var Stream = require('../utils/stream.js'); var ExpGolomb = require('../utils/exp-golomb.js'); var H264Stream, NalByteStream; /** * Accepts a NAL unit byte stream and unpacks the embedded NAL units. */ NalByteStream = function() { var syncPoint = 0, i, buffer; NalByteStream.prototype.init.call(this); this.push = function(data) { var swapBuffer; if (!buffer) { buffer = data.data; } else { swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength); swapBuffer.set(buffer); swapBuffer.set(data.data, buffer.byteLength); buffer = swapBuffer; } // Rec. ITU-T H.264, Annex B // scan for NAL unit boundaries // a match looks like this: // 0 0 1 .. NAL .. 0 0 1 // ^ sync point ^ i // or this: // 0 0 1 .. NAL .. 0 0 0 // ^ sync point ^ i // advance the sync point to a NAL start, if necessary for (; syncPoint < buffer.byteLength - 3; syncPoint++) { if (buffer[syncPoint + 2] === 1) { // the sync point is properly aligned i = syncPoint + 5; break; } } while (i < buffer.byteLength) { // look at the current byte to determine if we've hit the end of // a NAL unit boundary switch (buffer[i]) { case 0: // skip past non-sync sequences if (buffer[i - 1] !== 0) { i += 2; break; } else if (buffer[i - 2] !== 0) { i++; break; } // deliver the NAL unit if it isn't empty if (syncPoint + 3 !== i - 2) { this.trigger('data', buffer.subarray(syncPoint + 3, i - 2)); } // drop trailing zeroes do { i++; } while (buffer[i] !== 1 && i < buffer.length); syncPoint = i - 2; i += 3; break; case 1: // skip past non-sync sequences if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) { i += 3; break; } // deliver the NAL unit this.trigger('data', buffer.subarray(syncPoint + 3, i - 2)); syncPoint = i - 2; i += 3; break; default: // the current byte isn't a one or zero, so it cannot be part // of a sync sequence i += 3; break; } } // filter out the NAL units that were delivered buffer = buffer.subarray(syncPoint); i -= syncPoint; syncPoint = 0; }; this.flush = function() { // deliver the last buffered NAL unit if (buffer && buffer.byteLength > 3) { this.trigger('data', buffer.subarray(syncPoint + 3)); } // reset the stream state buffer = null; syncPoint = 0; this.trigger('done'); }; }; NalByteStream.prototype = new Stream(); /** * Accepts input from a ElementaryStream and produces H.264 NAL unit data * events. */ H264Stream = function() { var nalByteStream = new NalByteStream(), self, trackId, currentPts, currentDts, discardEmulationPreventionBytes, readSequenceParameterSet, skipScalingList; H264Stream.prototype.init.call(this); self = this; this.push = function(packet) { if (packet.type !== 'video') { return; } trackId = packet.trackId; currentPts = packet.pts; currentDts = packet.dts; nalByteStream.push(packet); }; nalByteStream.on('data', function(data) { var event = { trackId: trackId, pts: currentPts, dts: currentDts, data: data }; switch (data[0] & 0x1f) { case 0x05: event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr'; break; case 0x06: event.nalUnitType = 'sei_rbsp'; event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1)); break; case 0x07: event.nalUnitType = 'seq_parameter_set_rbsp'; event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1)); event.config = readSequenceParameterSet(event.escapedRBSP); break; case 0x08: event.nalUnitType = 'pic_parameter_set_rbsp'; break; case 0x09: event.nalUnitType = 'access_unit_delimiter_rbsp'; break; default: break; } self.trigger('data', event); }); nalByteStream.on('done', function() { self.trigger('done'); }); this.flush = function() { nalByteStream.flush(); }; /** * Advance the ExpGolomb decoder past a scaling list. The scaling * list is optionally transmitted as part of a sequence parameter * set and is not relevant to transmuxing. * @param count {number} the number of entries in this scaling list * @param expGolombDecoder {object} an ExpGolomb pointed to the * start of a scaling list * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1 */ skipScalingList = function(count, expGolombDecoder) { var lastScale = 8, nextScale = 8, j, deltaScale; for (j = 0; j < count; j++) { if (nextScale !== 0) { deltaScale = expGolombDecoder.readExpGolomb(); nextScale = (lastScale + deltaScale + 256) % 256; } lastScale = (nextScale === 0) ? lastScale : nextScale; } }; /** * Expunge any "Emulation Prevention" bytes from a "Raw Byte * Sequence Payload" * @param data {Uint8Array} the bytes of a RBSP from a NAL * unit * @return {Uint8Array} the RBSP without any Emulation * Prevention Bytes */ discardEmulationPreventionBytes = function(data) { var length = data.byteLength, emulationPreventionBytesPositions = [], i = 1, newLength, newData; // Find all `Emulation Prevention Bytes` while (i < length - 2) { if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) { emulationPreventionBytesPositions.push(i + 2); i += 2; } else { i++; } } // If no Emulation Prevention Bytes were found just return the original // array if (emulationPreventionBytesPositions.length === 0) { return data; } // Create a new array to hold the NAL unit data newLength = length - emulationPreventionBytesPositions.length; newData = new Uint8Array(newLength); var sourceIndex = 0; for (i = 0; i < newLength; sourceIndex++, i++) { if (sourceIndex === emulationPreventionBytesPositions[0]) { // Skip this byte sourceIndex++; // Remove this position index emulationPreventionBytesPositions.shift(); } newData[i] = data[sourceIndex]; } return newData; }; /** * Read a sequence parameter set and return some interesting video * properties. A sequence parameter set is the H264 metadata that * describes the properties of upcoming video frames. * @param data {Uint8Array} the bytes of a sequence parameter set * @return {object} an object with configuration parsed from the * sequence parameter set, including the dimensions of the * associated video frames. */ readSequenceParameterSet = function(data) { var frameCropLeftOffset = 0, frameCropRightOffset = 0, frameCropTopOffset = 0, frameCropBottomOffset = 0, sarScale = 1, expGolombDecoder, profileIdc, levelIdc, profileCompatibility, chromaFormatIdc, picOrderCntType, numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1, picHeightInMapUnitsMinus1, frameMbsOnlyFlag, scalingListCount, sarRatio, aspectRatioIdc, i; expGolombDecoder = new ExpGolomb(data); profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8) expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id // some profiles have more optional data we don't need if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128 || profileIdc === 138 || profileIdc === 139 || profileIdc === 134) { chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb(); if (chromaFormatIdc === 3) { expGolombDecoder.skipBits(1); // separate_colour_plane_flag } expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8 expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8 expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag if (expGolombDecoder.readBoolean()) { // seq_scaling_matrix_present_flag scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12; for (i = 0; i < scalingListCount; i++) { if (expGolombDecoder.readBoolean()) { // seq_scaling_list_present_flag[ i ] if (i < 6) { skipScalingList(16, expGolombDecoder); } else { skipScalingList(64, expGolombDecoder); } } } } } expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4 picOrderCntType = expGolombDecoder.readUnsignedExpGolomb(); if (picOrderCntType === 0) { expGolombDecoder.readUnsignedExpGolomb(); //log2_max_pic_order_cnt_lsb_minus4 } else if (picOrderCntType === 1) { expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb(); for(i = 0; i < numRefFramesInPicOrderCntCycle; i++) { expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ] } } expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb(); picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb(); frameMbsOnlyFlag = expGolombDecoder.readBits(1); if (frameMbsOnlyFlag === 0) { expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag } expGolombDecoder.skipBits(1); // direct_8x8_inference_flag if (expGolombDecoder.readBoolean()) { // frame_cropping_flag frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb(); frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb(); frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb(); frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb(); } if (expGolombDecoder.readBoolean()) { // vui_parameters_present_flag if (expGolombDecoder.readBoolean()) { // aspect_ratio_info_present_flag aspectRatioIdc = expGolombDecoder.readUnsignedByte(); switch (aspectRatioIdc) { case 1: sarRatio = [1,1]; break; case 2: sarRatio = [12,11]; break; case 3: sarRatio = [10,11]; break; case 4: sarRatio = [16,11]; break; case 5: sarRatio = [40,33]; break; case 6: sarRatio = [24,11]; break; case 7: sarRatio = [20,11]; break; case 8: sarRatio = [32,11]; break; case 9: sarRatio = [80,33]; break; case 10: sarRatio = [18,11]; break; case 11: sarRatio = [15,11]; break; case 12: sarRatio = [64,33]; break; case 13: sarRatio = [160,99]; break; case 14: sarRatio = [4,3]; break; case 15: sarRatio = [3,2]; break; case 16: sarRatio = [2,1]; break; case 255: { sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte() ]; break; } } if (sarRatio) { sarScale = sarRatio[0] / sarRatio[1]; } } } return { profileIdc: profileIdc, levelIdc: levelIdc, profileCompatibility: profileCompatibility, width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale), height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - (frameCropTopOffset * 2) - (frameCropBottomOffset * 2) }; }; }; H264Stream.prototype = new Stream(); module.exports = { H264Stream: H264Stream, NalByteStream: NalByteStream, }; },{"../utils/exp-golomb.js":19,"../utils/stream.js":20}],4:[function(require,module,exports){ module.exports = { adts: require('./adts'), h264: require('./h264'), }; },{"./adts":2,"./h264":3}],5:[function(require,module,exports){ /** * An object that stores the bytes of an FLV tag and methods for * querying and manipulating that data. * @see http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf */ 'use strict'; var FlvTag; // (type:uint, extraData:Boolean = false) extends ByteArray FlvTag = function(type, extraData) { var // Counter if this is a metadata tag, nal start marker if this is a video // tag. unused if this is an audio tag adHoc = 0, // :uint // The default size is 16kb but this is not enough to hold iframe // data and the resizing algorithm costs a bit so we create a larger // starting buffer for video tags bufferStartSize = 16384, // checks whether the FLV tag has enough capacity to accept the proposed // write and re-allocates the internal buffers if necessary prepareWrite = function(flv, count) { var bytes, minLength = flv.position + count; if (minLength < flv.bytes.byteLength) { // there's enough capacity so do nothing return; } // allocate a new buffer and copy over the data that will not be modified bytes = new Uint8Array(minLength * 2); bytes.set(flv.bytes.subarray(0, flv.position), 0); flv.bytes = bytes; flv.view = new DataView(flv.bytes.buffer); }, // commonly used metadata properties widthBytes = FlvTag.widthBytes || new Uint8Array('width'.length), heightBytes = FlvTag.heightBytes || new Uint8Array('height'.length), videocodecidBytes = FlvTag.videocodecidBytes || new Uint8Array('videocodecid'.length), i; if (!FlvTag.widthBytes) { // calculating the bytes of common metadata names ahead of time makes the // corresponding writes faster because we don't have to loop over the // characters // re-test with test/perf.html if you're planning on changing this for (i = 0; i < 'width'.length; i++) { widthBytes[i] = 'width'.charCodeAt(i); } for (i = 0; i < 'height'.length; i++) { heightBytes[i] = 'height'.charCodeAt(i); } for (i = 0; i < 'videocodecid'.length; i++) { videocodecidBytes[i] = 'videocodecid'.charCodeAt(i); } FlvTag.widthBytes = widthBytes; FlvTag.heightBytes = heightBytes; FlvTag.videocodecidBytes = videocodecidBytes; } this.keyFrame = false; // :Boolean switch(type) { case FlvTag.VIDEO_TAG: this.length = 16; // Start the buffer at 256k bufferStartSize *= 6; break; case FlvTag.AUDIO_TAG: this.length = 13; this.keyFrame = true; break; case FlvTag.METADATA_TAG: this.length = 29; this.keyFrame = true; break; default: throw("Error Unknown TagType"); } this.bytes = new Uint8Array(bufferStartSize); this.view = new DataView(this.bytes.buffer); this.bytes[0] = type; this.position = this.length; this.keyFrame = extraData; // Defaults to false // presentation timestamp this.pts = 0; // decoder timestamp this.dts = 0; // ByteArray#writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0) this.writeBytes = function(bytes, offset, length) { var start = offset || 0, end; length = length || bytes.byteLength; end = start + length; prepareWrite(this, length); this.bytes.set(bytes.subarray(start, end), this.position); this.position += length; this.length = Math.max(this.length, this.position); }; // ByteArray#writeByte(value:int):void this.writeByte = function(byte) { prepareWrite(this, 1); this.bytes[this.position] = byte; this.position++; this.length = Math.max(this.length, this.position); }; // ByteArray#writeShort(value:int):void this.writeShort = function(short) { prepareWrite(this, 2); this.view.setUint16(this.position, short); this.position += 2; this.length = Math.max(this.length, this.position); }; // Negative index into array // (pos:uint):int this.negIndex = function(pos) { return this.bytes[this.length - pos]; }; // The functions below ONLY work when this[0] == VIDEO_TAG. // We are not going to check for that because we dont want the overhead // (nal:ByteArray = null):int this.nalUnitSize = function() { if (adHoc === 0) { return 0; } return this.length - (adHoc + 4); }; this.startNalUnit = function() { // remember position and add 4 bytes if (adHoc > 0) { throw new Error("Attempted to create new NAL wihout closing the old one"); } // reserve 4 bytes for nal unit size adHoc = this.length; this.length += 4; this.position = this.length; }; // (nal:ByteArray = null):void this.endNalUnit = function(nalContainer) { var nalStart, // :uint nalLength; // :uint // Rewind to the marker and write the size if (this.length === adHoc + 4) { // we started a nal unit, but didnt write one, so roll back the 4 byte size value this.length -= 4; } else if (adHoc > 0) { nalStart = adHoc + 4; nalLength = this.length - nalStart; this.position = adHoc; this.view.setUint32(this.position, nalLength); this.position = this.length; if (nalContainer) { // Add the tag to the NAL unit nalContainer.push(this.bytes.subarray(nalStart, nalStart + nalLength)); } } adHoc = 0; }; /** * Write out a 64-bit floating point valued metadata property. This method is * called frequently during a typical parse and needs to be fast. */ // (key:String, val:Number):void this.writeMetaDataDouble = function(key, val) { var i; prepareWrite(this, 2 + key.length + 9); // write size of property name this.view.setUint16(this.position, key.length); this.position += 2; // this next part looks terrible but it improves parser throughput by // 10kB/s in my testing // write property name if (key === 'width') { this.bytes.set(widthBytes, this.position); this.position += 5; } else if (key === 'height') { this.bytes.set(heightBytes, this.position); this.position += 6; } else if (key === 'videocodecid') { this.bytes.set(videocodecidBytes, this.position); this.position += 12; } else { for (i = 0; i < key.length; i++) { this.bytes[this.position] = key.charCodeAt(i); this.position++; } } // skip null byte this.position++; // write property value this.view.setFloat64(this.position, val); this.position += 8; // update flv tag length this.length = Math.max(this.length, this.position); ++adHoc; }; // (key:String, val:Boolean):void this.writeMetaDataBoolean = function(key, val) { var i; prepareWrite(this, 2); this.view.setUint16(this.position, key.length); this.position += 2; for (i = 0; i < key.length; i++) { // if key.charCodeAt(i) >= 255, handle error prepareWrite(this, 1); this.bytes[this.position] = key.charCodeAt(i); this.position++; } prepareWrite(this, 2); this.view.setUint8(this.position, 0x01); this.position++; this.view.setUint8(this.position, val ? 0x01 : 0x00); this.position++; this.length = Math.max(this.length, this.position); ++adHoc; }; // ():ByteArray this.finalize = function() { var dtsDelta, // :int len; // :int switch(this.bytes[0]) { // Video Data case FlvTag.VIDEO_TAG: this.bytes[11] = ((this.keyFrame || extraData) ? 0x10 : 0x20 ) | 0x07; // We only support AVC, 1 = key frame (for AVC, a seekable frame), 2 = inter frame (for AVC, a non-seekable frame) this.bytes[12] = extraData ? 0x00 : 0x01; dtsDelta = this.pts - this.dts; this.bytes[13] = (dtsDelta & 0x00FF0000) >>> 16; this.bytes[14] = (dtsDelta & 0x0000FF00) >>> 8; this.bytes[15] = (dtsDelta & 0x000000FF) >>> 0; break; case FlvTag.AUDIO_TAG: this.bytes[11] = 0xAF; // 44 kHz, 16-bit stereo this.bytes[12] = extraData ? 0x00 : 0x01; break; case FlvTag.METADATA_TAG: this.position = 11; this.view.setUint8(this.position, 0x02); // String type this.position++; this.view.setUint16(this.position, 0x0A); // 10 Bytes this.position += 2; // set "onMetaData" this.bytes.set([0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x44, 0x61, 0x74, 0x61], this.position); this.position += 10; this.bytes[this.position] = 0x08; // Array type this.position++; this.view.setUint32(this.position, adHoc); this.position = this.length; this.bytes.set([0, 0, 9], this.position); this.position += 3; // End Data Tag this.length = this.position; break; } len = this.length - 11; // write the DataSize field this.bytes[ 1] = (len & 0x00FF0000) >>> 16; this.bytes[ 2] = (len & 0x0000FF00) >>> 8; this.bytes[ 3] = (len & 0x000000FF) >>> 0; // write the Timestamp this.bytes[ 4] = (this.dts & 0x00FF0000) >>> 16; this.bytes[ 5] = (this.dts & 0x0000FF00) >>> 8; this.bytes[ 6] = (this.dts & 0x000000FF) >>> 0; this.bytes[ 7] = (this.dts & 0xFF000000) >>> 24; // write the StreamID this.bytes[ 8] = 0; this.bytes[ 9] = 0; this.bytes[10] = 0; // Sometimes we're at the end of the view and have one slot to write a // uint32, so, prepareWrite of count 4, since, view is uint8 prepareWrite(this, 4); this.view.setUint32(this.length, this.length); this.length += 4; this.position += 4; // trim down the byte buffer to what is actually being used this.bytes = this.bytes.subarray(0, this.length); this.frameTime = FlvTag.frameTime(this.bytes); // if bytes.bytelength isn't equal to this.length, handle error return this; }; }; FlvTag.AUDIO_TAG = 0x08; // == 8, :uint FlvTag.VIDEO_TAG = 0x09; // == 9, :uint FlvTag.METADATA_TAG = 0x12; // == 18, :uint // (tag:ByteArray):Boolean { FlvTag.isAudioFrame = function(tag) { return FlvTag.AUDIO_TAG === tag[0]; }; // (tag:ByteArray):Boolean { FlvTag.isVideoFrame = function(tag) { return FlvTag.VIDEO_TAG === tag[0]; }; // (tag:ByteArray):Boolean { FlvTag.isMetaData = function(tag) { return FlvTag.METADATA_TAG === tag[0]; }; // (tag:ByteArray):Boolean { FlvTag.isKeyFrame = function(tag) { if (FlvTag.isVideoFrame(tag)) { return tag[11] === 0x17; } if (FlvTag.isAudioFrame(tag)) { return true; } if (FlvTag.isMetaData(tag)) { return true; } return false; }; // (tag:ByteArray):uint { FlvTag.frameTime = function(tag) { var pts = tag[ 4] << 16; // :uint pts |= tag[ 5] << 8; pts |= tag[ 6] << 0; pts |= tag[ 7] << 24; return pts; }; module.exports = FlvTag; },{}],6:[function(require,module,exports){ module.exports = { tag: require('./flv-tag'), Transmuxer: require('./transmuxer'), tools: require('../tools/flv-inspector'), }; },{"../tools/flv-inspector":17,"./flv-tag":5,"./transmuxer":7}],7:[function(require,module,exports){ 'use strict'; var Stream = require('../utils/stream.js'); var FlvTag = require('./flv-tag.js'); var m2ts = require('../m2ts/m2ts.js'); var AdtsStream = require('../codecs/adts.js'); var H264Stream = require('../codecs/h264').H264Stream; var MetadataStream, Transmuxer, VideoSegmentStream, AudioSegmentStream, CoalesceStream, collectTimelineInfo, metaDataTag, extraDataTag; /** * Store information about the start and end of the tracka and the * duration for each frame/sample we process in order to calculate * the baseMediaDecodeTime */ collectTimelineInfo = function (track, data) { if (typeof data.pts === 'number') { if (track.timelineStartInfo.pts === undefined) { track.timelineStartInfo.pts = data.pts; } else { track.timelineStartInfo.pts = Math.min(track.timelineStartInfo.pts, data.pts); } } if (typeof data.dts === 'number') { if (track.timelineStartInfo.dts === undefined) { track.timelineStartInfo.dts = data.dts; } else { track.timelineStartInfo.dts = Math.min(track.timelineStartInfo.dts, data.dts); } } }; metaDataTag = function(track, pts) { var tag = new FlvTag(FlvTag.METADATA_TAG); // :FlvTag tag.dts = pts; tag.pts = pts; tag.writeMetaDataDouble("videocodecid", 7); tag.writeMetaDataDouble("width", track.width); tag.writeMetaDataDouble("height", track.height); return tag; }; extraDataTag = function(track, pts) { var i, tag = new FlvTag(FlvTag.VIDEO_TAG, true); tag.dts = pts; tag.pts = pts; tag.writeByte(0x01);// version tag.writeByte(track.profileIdc);// profile tag.writeByte(track.profileCompatibility);// compatibility tag.writeByte(track.levelIdc);// level tag.writeByte(0xFC | 0x03); // reserved (6 bits), NULA length size - 1 (2 bits) tag.writeByte(0xE0 | 0x01 ); // reserved (3 bits), num of SPS (5 bits) tag.writeShort( track.sps[0].length ); // data of SPS tag.writeBytes( track.sps[0] ); // SPS tag.writeByte(track.pps.length); // num of PPS (will there ever be more that 1 PPS?) for (i = 0 ; i < track.pps.length ; ++i) { tag.writeShort(track.pps[i].length); // 2 bytes for length of PPS tag.writeBytes(track.pps[i]); // data of PPS } return tag; }; /** * Constructs a single-track, media segment from AAC data * events. The output of this stream can be fed to flash. */ AudioSegmentStream = function(track) { var adtsFrames = [], adtsFramesLength = 0, sequenceNumber = 0, earliestAllowedDts = 0, oldExtraData; AudioSegmentStream.prototype.init.call(this); this.push = function(data) { collectTimelineInfo(track, data); if (track && track.channelcount === undefined) { track.audioobjecttype = data.audioobjecttype; track.channelcount = data.channelcount; track.samplerate = data.samplerate; track.samplingfrequencyindex = data.samplingfrequencyindex; track.samplesize = data.samplesize; track.extraData = (track.audioobjecttype << 11) | (track.samplingfrequencyindex << 7) | (track.channelcount << 3); } data.pts = Math.round(data.pts / 90); data.dts = Math.round(data.dts / 90); // buffer audio data until end() is called adtsFrames.push(data); }; this.flush = function() { var currentFrame, adtsFrame, deltaDts,lastMetaPts, tags = []; // return early if no audio data has been observed if (adtsFrames.length === 0) { this.trigger('done'); return; } lastMetaPts = -Infinity; while (adtsFrames.length) { currentFrame = adtsFrames.shift(); // write out metadata tags every 1 second so that the decoder // is re-initialized quickly after seeking into a different // audio configuration if (track.extraData !== oldExtraData || currentFrame.pts - lastMetaPts >= 1000) { adtsFrame = new FlvTag(FlvTag.METADATA_TAG); adtsFrame.pts = currentFrame.pts; adtsFrame.dts = currentFrame.dts; // AAC is always 10 adtsFrame.writeMetaDataDouble("audiocodecid", 10); adtsFrame.writeMetaDataBoolean("stereo", 2 === track.channelcount); adtsFrame.writeMetaDataDouble ("audiosamplerate", track.samplerate); // Is AAC always 16 bit? adtsFrame.writeMetaDataDouble ("audiosamplesize", 16); tags.push(adtsFrame); oldExtraData = track.extraData; adtsFrame = new FlvTag(FlvTag.AUDIO_TAG, true); // For audio, DTS is always the same as PTS. We want to set the DTS // however so we can compare with video DTS to determine approximate // packet order adtsFrame.pts = currentFrame.pts; adtsFrame.dts = currentFrame.dts; adtsFrame.view.setUint16(adtsFrame.position, track.extraData); adtsFrame.position += 2; adtsFrame.length = Math.max(adtsFrame.length, adtsFrame.position); tags.push(adtsFrame); lastMetaPts = currentFrame.pts; } adtsFrame = new FlvTag(FlvTag.AUDIO_TAG); adtsFrame.pts = currentFrame.pts; adtsFrame.dts = currentFrame.dts; adtsFrame.writeBytes(currentFrame.data); tags.push(adtsFrame); } oldExtraData = null; this.trigger('data', {track: track, tags: tags}); this.trigger('done'); }; }; AudioSegmentStream.prototype = new Stream(); /** * Store FlvTags for the h264 stream * @param track {object} track metadata configuration */ VideoSegmentStream = function(track) { var sequenceNumber = 0, nalUnits = [], nalUnitsLength = 0, config, h264Frame; VideoSegmentStream.prototype.init.call(this); this.finishFrame = function(tags, frame) { if (!frame) { return; } // Check if keyframe and the length of tags. // This makes sure we write metadata on the first frame of a segment. if (config && track && track.newMetadata && (frame.keyFrame || tags.length === 0)) { // Push extra data on every IDR frame in case we did a stream change + seek tags.push(metaDataTag(config, frame.pts)); tags.push(extraDataTag(track, frame.pts)); track.newMetadata = false; } frame.endNalUnit(); tags.push(frame); }; this.push = function(data) { collectTimelineInfo(track, data); data.pts = Math.round(data.pts / 90); data.dts = Math.round(data.dts / 90); // buffer video until flush() is called nalUnits.push(data); }; this.flush = function() { var currentNal, tags = []; // Throw away nalUnits at the start of the byte stream until we find // the first AUD while (nalUnits.length) { if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') { break; } nalUnits.shift(); } // return early if no video data has been observed if (nalUnits.length === 0) { this.trigger('done'); return; } while (nalUnits.length) { currentNal = nalUnits.shift(); // record the track config if (currentNal.nalUnitType === 'seq_parameter_set_rbsp') { track.newMetadata = true; config = currentNal.config; track.width = config.width; track.height = config.height; track.sps = [currentNal.data]; track.profileIdc = config.profileIdc; track.levelIdc = config.levelIdc; track.profileCompatibility = config.profileCompatibility; h264Frame.endNalUnit(); } else if (currentNal.nalUnitType === 'pic_parameter_set_rbsp') { track.newMetadata = true; track.pps = [currentNal.data]; h264Frame.endNalUnit(); } else if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') { if (h264Frame) { this.finishFrame(tags, h264Frame); } h264Frame = new FlvTag(FlvTag.VIDEO_TAG); h264Frame.pts = currentNal.pts; h264Frame.dts = currentNal.dts; } else { if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') { // the current sample is a key frame h264Frame.keyFrame = true; } h264Frame.endNalUnit(); } h264Frame.startNalUnit(); h264Frame.writeBytes(currentNal.data); } if (h264Frame) { this.finishFrame(tags, h264Frame); } this.trigger('data', {track: track, tags: tags}); // Continue with the flush process now this.trigger('done'); }; }; VideoSegmentStream.prototype = new Stream(); /** * The final stage of the transmuxer that emits the flv tags * for audio, video, and metadata. Also tranlates in time and * outputs caption data and id3 cues. */ CoalesceStream = function(options) { // Number of Tracks per output segment // If greater than 1, we combine multiple // tracks into a single segment this.numberOfTracks = 0; this.metadataStream = options.metadataStream; this.videoTags = []; this.audioTags = []; this.videoTrack = null; this.audioTrack = null; this.pendingCaptions = []; this.pendingMetadata = []; this.pendingTracks = 0; CoalesceStream.prototype.init.call(this); // Take output from multiple this.push = function(output) { // buffer incoming captions until the associated video segment // finishes if (output.text) { return this.pendingCaptions.push(output); } // buffer incoming id3 tags until the final flush if (output.frames) { return this.pendingMetadata.push(output); } if (output.track.type === 'video') { this.videoTrack = output.track; this.videoTags = output.tags; this.pendingTracks++; } if (output.track.type === 'audio') { this.audioTrack = output.track; this.audioTags = output.tags; this.pendingTracks++; } }; }; CoalesceStream.prototype = new Stream(); CoalesceStream.prototype.flush = function() { var id3, caption, i, timelineStartPts, event = { tags: {}, captions: [], metadata: [] }; if (this.pendingTracks < this.numberOfTracks) { return; } if (this.videoTrack) { timelineStartPts = this.videoTrack.timelineStartInfo.pts; } else if (this.audioTrack) { timelineStartPts = this.audioTrack.timelineStartInfo.pts; } event.tags.videoTags = this.videoTags; event.tags.audioTags = this.audioTags; // Translate caption PTS times into second offsets into the // video timeline for the segment for (i = 0; i < this.pendingCaptions.length; i++) { caption = this.pendingCaptions[i]; caption.startTime = caption.startPts - timelineStartPts; caption.startTime /= 90e3; caption.endTime = caption.endPts - timelineStartPts; caption.endTime /= 90e3; event.captions.push(caption); } // Translate ID3 frame PTS times into second offsets into the // video timeline for the segment for (i = 0; i < this.pendingMetadata.length; i++) { id3 = this.pendingMetadata[i]; id3.cueTime = id3.pts - timelineStartPts; id3.cueTime /= 90e3; event.metadata.push(id3); } // We add this to every single emitted segment even though we only need // it for the first event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state this.videoTrack = null; this.audioTrack = null; this.videoTags = []; this.audioTags = []; this.pendingCaptions.length = 0; this.pendingMetadata.length = 0; this.pendingTracks = 0; // Emit the final segment this.trigger('data', event); this.trigger('done'); }; /** * An object that incrementally transmuxes MPEG2 Trasport Stream * chunks into an FLV. */ Transmuxer = function(options) { var self = this, videoTrack, audioTrack, packetStream, parseStream, elementaryStream, adtsStream, h264Stream, videoSegmentStream, audioSegmentStream, captionStream, coalesceStream; Transmuxer.prototype.init.call(this); options = options || {}; // expose the metadata stream this.metadataStream = new m2ts.MetadataStream(); options.metadataStream = this.metadataStream; // set up the parsing pipeline packetStream = new m2ts.TransportPacketStream(); parseStream = new m2ts.TransportParseStream(); elementaryStream = new m2ts.ElementaryStream(); adtsStream = new AdtsStream(); h264Stream = new H264Stream(); coalesceStream = new CoalesceStream(options); // disassemble MPEG2-TS packets into elementary streams packetStream .pipe(parseStream) .pipe(elementaryStream); // !!THIS ORDER IS IMPORTANT!! // demux the streams elementaryStream .pipe(h264Stream); elementaryStream .pipe(adtsStream); elementaryStream .pipe(this.metadataStream) .pipe(coalesceStream); // if CEA-708 parsing is available, hook up a caption stream captionStream = new m2ts.CaptionStream(); h264Stream.pipe(captionStream) .pipe(coalesceStream); // hook up the segment streams once track metadata is delivered elementaryStream.on('data', function(data) { var i, videoTrack, audioTrack; if (data.type === 'metadata') { i = data.tracks.length; // scan the tracks listed in the metadata while (i--) { if (data.tracks[i].type === 'video') { videoTrack = data.tracks[i]; } else if (data.tracks[i].type === 'audio') { audioTrack = data.tracks[i]; } } // hook up the video segment stream to the first track with h264 data if (videoTrack && !videoSegmentStream) { coalesceStream.numberOfTracks++; videoSegmentStream = new VideoSegmentStream(videoTrack); // Set up the final part of the video pipeline h264Stream .pipe(videoSegmentStream) .pipe(coalesceStream); } if (audioTrack && !audioSegmentStream) { // hook up the audio segment stream to the first track with aac data coalesceStream.numberOfTracks++; audioSegmentStream = new AudioSegmentStream(audioTrack); // Set up the final part of the audio pipeline adtsStream .pipe(audioSegmentStream) .pipe(coalesceStream); } } }); // feed incoming data to the front of the parsing pipeline this.push = function(data) { packetStream.push(data); }; // flush any buffered data this.flush = function() { // Start at the top of the pipeline and flush all pending work packetStream.flush(); }; // Re-emit any data coming from the coalesce stream to the outside world coalesceStream.on('data', function (event) { self.trigger('data', event); }); // Let the consumer know we have finished flushing the entire pipeline coalesceStream.on('done', function () { self.trigger('done'); }); // For information on the FLV format, see // http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf. // Technically, this function returns the header and a metadata FLV tag // if duration is greater than zero // duration in seconds // @return {object} the bytes of the FLV header as a Uint8Array this.getFlvHeader = function(duration, audio, video) { // :ByteArray { var headBytes = new Uint8Array(3 + 1 + 1 + 4), head = new DataView(headBytes.buffer), metadata, result, metadataLength; // default arguments duration = duration || 0; audio = audio === undefined? true : audio; video = video === undefined? true : video; // signature head.setUint8(0, 0x46); // 'F' head.setUint8(1, 0x4c); // 'L' head.setUint8(2, 0x56); // 'V' // version head.setUint8(3, 0x01); // flags head.setUint8(4, (audio ? 0x04 : 0x00) | (video ? 0x01 : 0x00)); // data offset, should be 9 for FLV v1 head.setUint32(5, headBytes.byteLength); // init the first FLV tag if (duration <= 0) { // no duration available so just write the first field of the first // FLV tag result = new Uint8Array(headBytes.byteLength + 4); result.set(headBytes); result.set([0, 0, 0, 0], headBytes.byteLength); return result; } // write out the duration metadata tag metadata = new FlvTag(FlvTag.METADATA_TAG); metadata.pts = metadata.dts = 0; metadata.writeMetaDataDouble("duration", duration); metadataLength = metadata.finalize().length; result = new Uint8Array(headBytes.byteLength + metadataLength); result.set(headBytes); result.set(head.byteLength, metadataLength); return result; }; }; Transmuxer.prototype = new Stream(); // forward compatibility module.exports = Transmuxer; },{"../codecs/adts.js":2,"../codecs/h264":3,"../m2ts/m2ts.js":11,"../utils/stream.js":20,"./flv-tag.js":5}],8:[function(require,module,exports){ 'use strict'; var muxjs = { codecs: require('./codecs'), mp4: require('./mp4'), flv: require('./flv'), mp2t: require('./m2ts'), }; module.exports = muxjs; },{"./codecs":4,"./flv":6,"./m2ts":10,"./mp4":14}],9:[function(require,module,exports){ /** * mux.js * * Copyright (c) 2015 Brightcove * All rights reserved. * * Reads in-band caption information from a video elementary * stream. Captions must follow the CEA-708 standard for injection * into an MPEG-2 transport streams. * @see https://en.wikipedia.org/wiki/CEA-708 */ 'use strict'; // ----------------- // Link To Transport // ----------------- // Supplemental enhancement information (SEI) NAL units have a // payload type field to indicate how they are to be // interpreted. CEAS-708 caption content is always transmitted with // payload type 0x04. var USER_DATA_REGISTERED_ITU_T_T35 = 4, RBSP_TRAILING_BITS = 128, Stream = require('../utils/stream'); /** * Parse a supplemental enhancement information (SEI) NAL unit. * Stops parsing once a message of type ITU T T35 has been found. * * @param bytes {Uint8Array} the bytes of a SEI NAL unit * @return {object} the parsed SEI payload * @see Rec. ITU-T H.264, 7.3.2.3.1 */ var parseSei = function(bytes) { var i = 0, result = { payloadType: -1, payloadSize: 0, }, payloadType = 0, payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message while (i < bytes.byteLength) { // stop once we have hit the end of the sei_rbsp if (bytes[i] === RBSP_TRAILING_BITS) { break; } // Parse payload type while (bytes[i] === 0xFF) { payloadType += 255; i++; } payloadType += bytes[i++]; // Parse payload size while (bytes[i] === 0xFF) { payloadSize += 255; i++; } payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break // there can only ever be one caption message in a frame's sei if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) { result.payloadType = payloadType; result.payloadSize = payloadSize; result.payload = bytes.subarray(i, i + payloadSize); break; } // skip the payload and parse the next message i += payloadSize; payloadType = 0; payloadSize = 0; } return result; }; // see ANSI/SCTE 128-1 (2013), section 8.1 var parseUserData = function(sei) { // itu_t_t35_contry_code must be 181 (United States) for // captions if (sei.payload[0] !== 181) { return null; } // itu_t_t35_provider_code should be 49 (ATSC) for captions if (((sei.payload[1] << 8) | sei.payload[2]) !== 49) { return null; } // the user_identifier should be "GA94" to indicate ATSC1 data if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') { return null; } // finally, user_data_type_code should be 0x03 for caption data if (sei.payload[7] !== 0x03) { return null; } // return the user_data_type_structure and strip the trailing // marker bits return sei.payload.subarray(8, sei.payload.length - 1); }; // see CEA-708-D, section 4.4 var parseCaptionPackets = function(pts, userData) { var results = [], i, count, offset, data; // if this is just filler, return immediately if (!(userData[0] & 0x40)) { return results; } // parse out the cc_data_1 and cc_data_2 fields count = userData[0] & 0x1f; for (i = 0; i < count; i++) { offset = i * 3; data = { type: userData[offset + 2] & 0x03, pts: pts }; // capture cc data when cc_valid is 1 if (userData[offset + 2] & 0x04) { data.ccData = (userData[offset + 3] << 8) | userData[offset + 4]; results.push(data); } } return results; }; var CaptionStream = function() { var self = this; CaptionStream.prototype.init.call(this); this.captionPackets_ = []; this.field1_ = new Cea608Stream(); // forward data and done events from field1_ to this CaptionStream this.field1_.on('data', this.trigger.bind(this, 'data')); this.field1_.on('done', this.trigger.bind(this, 'done')); }; CaptionStream.prototype = new Stream(); CaptionStream.prototype.push = function(event) { var sei, userData, captionPackets; // only examine SEI NALs if (event.nalUnitType !== 'sei_rbsp') { return; } // parse the sei sei = parseSei(event.escapedRBSP); // ignore everything but user_data_registered_itu_t_t35 if (sei.payloadType !== USER_DATA_REGISTERED_ITU_T_T35) { return; } // parse out the user data payload userData = parseUserData(sei); // ignore unrecognized userData if (!userData) { return; } // parse out CC data packets and save them for later this.captionPackets_ = this.captionPackets_.concat(parseCaptionPackets(event.pts, userData)); }; CaptionStream.prototype.flush = function () { // make sure we actually parsed captions before proceeding if (!this.captionPackets_.length) { this.field1_.flush(); return; } // sort caption byte-pairs based on their PTS values this.captionPackets_.sort(function(a, b) { return a.pts - b.pts; }); // Push each caption into Cea608Stream this.captionPackets_.forEach(this.field1_.push, this.field1_); this.captionPackets_.length = 0; this.field1_.flush(); return; }; // ---------------------- // Session to Application // ---------------------- var BASIC_CHARACTER_TRANSLATION = { 0x2a: 0xe1, 0x5c: 0xe9, 0x5e: 0xed, 0x5f: 0xf3, 0x60: 0xfa, 0x7b: 0xe7, 0x7c: 0xf7, 0x7d: 0xd1, 0x7e: 0xf1, 0x7f: 0x2588 }; var getCharFromCode = function(code) { if(code === null) { return ''; } code = BASIC_CHARACTER_TRANSLATION[code] || code; return String.fromCharCode(code); }; // Constants for the byte codes recognized by Cea608Stream. This // list is not exhaustive. For a more comprehensive listing and // semantics see // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf var PADDING = 0x0000, // Pop-on Mode RESUME_CAPTION_LOADING = 0x1420, END_OF_CAPTION = 0x142f, // Roll-up Mode ROLL_UP_2_ROWS = 0x1425, ROLL_UP_3_ROWS = 0x1426, ROLL_UP_4_ROWS = 0x1427, RESUME_DIRECT_CAPTIONING = 0x1429, CARRIAGE_RETURN = 0x142d, // Erasure BACKSPACE = 0x1421, ERASE_DISPLAYED_MEMORY = 0x142c, ERASE_NON_DISPLAYED_MEMORY = 0x142e; // the index of the last row in a CEA-608 display buffer var BOTTOM_ROW = 14; // CEA-608 captions are rendered onto a 34x15 matrix of character // cells. The "bottom" row is the last element in the outer array. var createDisplayBuffer = function() { var result = [], i = BOTTOM_ROW + 1; while (i--) { result.push(''); } return result; }; var Cea608Stream = function() { Cea608Stream.prototype.init.call(this); this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will // actually display captions. If a caption is shifted to a row // with a lower index than this, it is cleared from the display // buffer this.topRow_ = 0; this.startPts_ = 0; this.displayed_ = createDisplayBuffer(); this.nonDisplayed_ = createDisplayBuffer(); this.lastControlCode_ = null; this.push = function(packet) { // Ignore other channels if (packet.type !== 0) { return; } var data, swap, char0, char1; // remove the parity bits data = packet.ccData & 0x7f7f; // ignore duplicate control codes if (data === this.lastControlCode_) { this.lastControlCode_ = null; return; } // Store control codes if ((data & 0xf000) === 0x1000) { this.lastControlCode_ = data; } else { this.lastControlCode_ = null; } switch (data) { case PADDING: break; case RESUME_CAPTION_LOADING: this.mode_ = 'popOn'; break; case END_OF_CAPTION: // if a caption was being displayed, it's gone now this.flushDisplayed(packet.pts); // flip memory swap = this.displayed_; this.displayed_ = this.nonDisplayed_; this.nonDisplayed_ = swap; // start measuring the time to display the caption this.startPts_ = packet.pts; break; case ROLL_UP_2_ROWS: this.topRow_ = BOTTOM_ROW - 1; this.mode_ = 'rollUp'; break; case ROLL_UP_3_ROWS: this.topRow_ = BOTTOM_ROW - 2; this.mode_ = 'rollUp'; break; case ROLL_UP_4_ROWS: this.topRow_ = BOTTOM_ROW - 3; this.mode_ = 'rollUp'; break; case CARRIAGE_RETURN: this.flushDisplayed(packet.pts); this.shiftRowsUp_(); this.startPts_ = packet.pts; break; case BACKSPACE: if (this.mode_ === 'popOn') { this.nonDisplayed_[BOTTOM_ROW] = this.nonDisplayed_[BOTTOM_ROW].slice(0, -1); } else { this.displayed_[BOTTOM_ROW] = this.displayed_[BOTTOM_ROW].slice(0, -1); } break; case ERASE_DISPLAYED_MEMORY: this.flushDisplayed(packet.pts); this.displayed_ = createDisplayBuffer(); break; case ERASE_NON_DISPLAYED_MEMORY: this.nonDisplayed_ = createDisplayBuffer(); break; default: char0 = data >>> 8; char1 = data & 0xff; // Look for a Channel 1 Preamble Address Code if (char0 >= 0x10 && char0 <= 0x17 && char1 >= 0x40 && char1 <= 0x7F && (char0 !== 0x10 || char1 < 0x60)) { // Follow Safari's lead and replace the PAC with a space char0 = 0x20; // we only want one space so make the second character null // which will get become '' in getCharFromCode char1 = null; } // Look for special character sets if ((char0 === 0x11 || char0 === 0x19) && (char1 >= 0x30 && char1 <= 0x3F)) { // Put in eigth note and space char0 = 0x266A; char1 = ''; } // ignore unsupported control codes if ((char0 & 0xf0) === 0x10) { return; } // character handling is dependent on the current mode this[this.mode_](packet.pts, char0, char1); break; } }; }; Cea608Stream.prototype = new Stream(); // Trigger a cue point that captures the current state of the // display buffer Cea608Stream.prototype.flushDisplayed = function(pts) { var content = this.displayed_ // remove spaces from the start and end of the string .map(function(row) { return row.trim(); }) // remove empty rows .filter(function(row) { return row.length; }) // combine all text rows to display in one cue .join('\n'); if (content.length) { this.trigger('data', { startPts: this.startPts_, endPts: pts, text: content }); } }; // Mode Implementations Cea608Stream.prototype.popOn = function(pts, char0, char1) { var baseRow = this.nonDisplayed_[BOTTOM_ROW]; // buffer characters baseRow += getCharFromCode(char0); baseRow += getCharFromCode(char1); this.nonDisplayed_[BOTTOM_ROW] = baseRow; }; Cea608Stream.prototype.rollUp = function(pts, char0, char1) { var baseRow = this.displayed_[BOTTOM_ROW]; if (baseRow === '') { // we're starting to buffer new display input, so flush out the // current display this.flushDisplayed(pts); this.startPts_ = pts; } baseRow += getCharFromCode(char0); baseRow += getCharFromCode(char1); this.displayed_[BOTTOM_ROW] = baseRow; }; Cea608Stream.prototype.shiftRowsUp_ = function() { var i; // clear out inactive rows for (i = 0; i < this.topRow_; i++) { this.displayed_[i] = ''; } // shift displayed rows up for (i = this.topRow_; i < BOTTOM_ROW; i++) { this.displayed_[i] = this.displayed_[i + 1]; } // clear out the bottom row this.displayed_[BOTTOM_ROW] = ''; }; // exports module.exports = { CaptionStream: CaptionStream, Cea608Stream: Cea608Stream, }; },{"../utils/stream":20}],10:[function(require,module,exports){ module.exports = require('./m2ts'); },{"./m2ts":11}],11:[function(require,module,exports){ /** * mux.js * * Copyright (c) 2015 Brightcove * All rights reserved. * * A stream-based mp2t to mp4 converter. This utility can be used to * deliver mp4s to a SourceBuffer on platforms that support native * Media Source Extensions. */ 'use strict'; var Stream = require('../utils/stream.js'), CaptionStream = require('./caption-stream'), StreamTypes = require('./stream-types'); var Stream = require('../utils/stream.js'); var m2tsStreamTypes = require('./stream-types.js'); // object types var TransportPacketStream, TransportParseStream, ElementaryStream, AacStream, H264Stream, NalByteStream; // constants var MP2T_PACKET_LENGTH = 188, // bytes SYNC_BYTE = 0x47, /** * Splits an incoming stream of binary data into MPEG-2 Transport * Stream packets. */ TransportPacketStream = function() { var buffer = new Uint8Array(MP2T_PACKET_LENGTH), bytesInBuffer = 0; TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream. this.push = function(bytes) { var i = 0, startIndex = 0, endIndex = MP2T_PACKET_LENGTH, everything; // If there are bytes remaining from the last segment, prepend them to the // bytes that were pushed in if (bytesInBuffer) { everything = new Uint8Array(bytes.byteLength + bytesInBuffer); everything.set(buffer.subarray(0, bytesInBuffer)); everything.set(bytes, bytesInBuffer); bytesInBuffer = 0; } else { everything = bytes; } // While we have enough data for a packet while (endIndex < everything.byteLength) { // Look for a pair of start and end sync bytes in the data.. if (everything[startIndex] === SYNC_BYTE && everything[endIndex] === SYNC_BYTE) { // We found a packet so emit it and jump one whole packet forward in // the stream this.trigger('data', everything.subarray(startIndex, endIndex)); startIndex += MP2T_PACKET_LENGTH; endIndex += MP2T_PACKET_LENGTH; continue; } // If we get here, we have somehow become de-synchronized and we need to step // forward one byte at a time until we find a pair of sync bytes that denote // a packet startIndex++; endIndex++; } // If there was some data left over at the end of the segment that couldn't // possibly be a whole packet, keep it because it might be the start of a packet // that continues in the next segment if (startIndex < everything.byteLength) { buffer.set(everything.subarray(startIndex), 0); bytesInBuffer = everything.byteLength - startIndex; } }; this.flush = function () { // If the buffer contains a whole packet when we are being flushed, emit it // and empty the buffer. Otherwise hold onto the data because it may be // important for decoding the next segment if (bytesInBuffer === MP2T_PACKET_LENGTH && buffer[0] === SYNC_BYTE) { this.trigger('data', buffer); bytesInBuffer = 0; } this.trigger('done'); }; }; TransportPacketStream.prototype = new Stream(); /** * Accepts an MP2T TransportPacketStream and emits data events with parsed * forms of the individual transport stream packets. */ TransportParseStream = function() { var parsePsi, parsePat, parsePmt, parsePes, self; TransportParseStream.prototype.init.call(this); self = this; this.packetsWaitingForPmt = []; this.programMapTable = undefined; parsePsi = function(payload, psi) { var offset = 0; // PSI packets may be split into multiple sections and those // sections may be split into multiple packets. If a PSI // section starts in this packet, the payload_unit_start_indicator // will be true and the first byte of the payload will indicate // the offset from the current position to the start of the // section. if (psi.payloadUnitStartIndicator) { offset += payload[offset] + 1; } if (psi.type === 'pat') { parsePat(payload.subarray(offset), psi); } else { parsePmt(payload.subarray(offset), psi); } }; parsePat = function(payload, pat) { pat.section_number = payload[7]; pat.last_section_number = payload[8]; // skip the PSI header and parse the first PMT entry self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11]; pat.pmtPid = self.pmtPid; }; /** * Parse out the relevant fields of a Program Map Table (PMT). * @param payload {Uint8Array} the PMT-specific portion of an MP2T * packet. The first byte in this array should be the table_id * field. * @param pmt {object} the object that should be decorated with * fields parsed from the PMT. */ parsePmt = function(payload, pmt) { var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually // take effect. We don't believe this should ever be the case // for HLS but we'll ignore "forward" PMT declarations if we see // them. Future PMT declarations have the current_next_indicator // set to zero. if (!(payload[5] & 0x01)) { return; } // overwrite any existing program map table self.programMapTable = {}; // the mapping table ends at the end of the current section sectionLength = (payload[1] & 0x0f) << 8 | payload[2]; tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how // long the program info descriptors are programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table offset = 12 + programInfoLength; while (offset < tableEnd) { // add an entry that maps the elementary_pid to the stream_type self.programMapTable[(payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]] = payload[offset]; // move to the next table entry // skip past the elementary stream descriptors, if present offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5; } // record the map on the packet as well pmt.programMapTable = self.programMapTable; // if there are any packets waiting for a PMT to be found, process them now while (self.packetsWaitingForPmt.length) { self.processPes_.apply(self, self.packetsWaitingForPmt.shift()); } }; /** * Deliver a new MP2T packet to the stream. */ this.push = function(packet) { var result = {}, offset = 4; result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1] result.pid = packet[1] & 0x1f; result.pid <<= 8; result.pid |= packet[2]; // if an adaption field is present, its length is specified by the // fifth byte of the TS packet header. The adaptation field is // used to add stuffing to PES packets that don't fill a complete // TS packet, and to specify some forms of timing and control data // that we do not currently use. if (((packet[3] & 0x30) >>> 4) > 0x01) { offset += packet[offset] + 1; } // parse the rest of the packet based on the type if (result.pid === 0) { result.type = 'pat'; parsePsi(packet.subarray(offset), result); this.trigger('data', result); } else if (result.pid === this.pmtPid) { result.type = 'pmt'; parsePsi(packet.subarray(offset), result); this.trigger('data', result); } else if (this.programMapTable === undefined) { // When we have not seen a PMT yet, defer further processing of // PES packets until one has been parsed this.packetsWaitingForPmt.push([packet, offset, result]); } else { this.processPes_(packet, offset, result); } }; this.processPes_ = function (packet, offset, result) { result.streamType = this.programMapTable[result.pid]; result.type = 'pes'; result.data = packet.subarray(offset); this.trigger('data', result); }; }; TransportParseStream.prototype = new Stream(); TransportParseStream.STREAM_TYPES = { h264: 0x1b, adts: 0x0f }; /** * Reconsistutes program elementary stream (PES) packets from parsed * transport stream packets. That is, if you pipe an * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output * events will be events which capture the bytes for individual PES * packets plus relevant metadata that has been extracted from the * container. */ ElementaryStream = function() { var // PES packet fragments video = { data: [], size: 0 }, audio = { data: [], size: 0 }, timedMetadata = { data: [], size: 0 }, parsePes = function(payload, pes) { var ptsDtsFlags; // find out if this packets starts a new keyframe pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value // and a DTS value. Determine what combination of values is // available to work with. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript // performs all bitwise operations on 32-bit integers but javascript // supports a much greater range (52-bits) of integer using standard // mathematical operations. // We construct a 31-bit value using bitwise operators over the 31 // most significant bits and then multiply by 4 (equal to a left-shift // of 2) before we add the final 2 least significant bits of the // timestamp (equal to an OR.) if (ptsDtsFlags & 0xC0) { // the PTS and DTS are not written out directly. For information // on how they are encoded, see // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3; pes.pts *= 4; // Left shift by 2 pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs pes.dts = pes.pts; if (ptsDtsFlags & 0x40) { pes.dts = (payload[14] & 0x0E ) << 27 | (payload[15] & 0xFF ) << 20 | (payload[16] & 0xFE ) << 12 | (payload[17] & 0xFF ) << 5 | (payload[18] & 0xFE ) >>> 3; pes.dts *= 4; // Left shift by 2 pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs } } // the data section starts immediately after the PES header. // pes_header_data_length specifies the number of header bytes // that follow the last byte of the field. pes.data = payload.subarray(9 + payload[8]); }, flushStream = function(stream, type) { var packetData = new Uint8Array(stream.size), event = { type: type }, i = 0, fragment; // do nothing if there is no buffered data if (!stream.data.length) { return; } event.trackId = stream.data[0].pid; // reassemble the packet while (stream.data.length) { fragment = stream.data.shift(); packetData.set(fragment.data, i); i += fragment.data.byteLength; } // parse assembled packet's PES header parsePes(packetData, event); stream.size = 0; self.trigger('data', event); }, self; ElementaryStream.prototype.init.call(this); self = this; this.push = function(data) { ({ pat: function() { // we have to wait for the PMT to arrive as well before we // have any meaningful metadata }, pes: function() { var stream, streamType; switch (data.streamType) { case StreamTypes.H264_STREAM_TYPE: case m2tsStreamTypes.H264_STREAM_TYPE: stream = video; streamType = 'video'; break; case StreamTypes.ADTS_STREAM_TYPE: stream = audio; streamType = 'audio'; break; case StreamTypes.METADATA_STREAM_TYPE: stream = timedMetadata; streamType = 'timed-metadata'; break; default: // ignore unknown stream types return; } // if a new packet is starting, we can flush the completed // packet if (data.payloadUnitStartIndicator) { flushStream(stream, streamType); } // buffer this fragment until we are sure we've received the // complete payload stream.data.push(data); stream.size += data.data.byteLength; }, pmt: function() { var event = { type: 'metadata', tracks: [] }, programMapTable = data.programMapTable, k, track; // translate streams to tracks for (k in programMapTable) { if (programMapTable.hasOwnProperty(k)) { track = { timelineStartInfo: { baseMediaDecodeTime: 0 } }; track.id = +k; if (programMapTable[k] === m2tsStreamTypes.H264_STREAM_TYPE) { track.codec = 'avc'; track.type = 'video'; } else if (programMapTable[k] === m2tsStreamTypes.ADTS_STREAM_TYPE) { track.codec = 'adts'; track.type = 'audio'; } event.tracks.push(track); } } self.trigger('data', event); } })[data.type](); }; /** * Flush any remaining input. Video PES packets may be of variable * length. Normally, the start of a new video packet can trigger the * finalization of the previous packet. That is not possible if no * more video is forthcoming, however. In that case, some other * mechanism (like the end of the file) has to be employed. When it is * clear that no additional data is forthcoming, calling this method * will flush the buffered packets. */ this.flush = function() { // !!THIS ORDER IS IMPORTANT!! // video first then audio flushStream(video, 'video'); flushStream(audio, 'audio'); flushStream(timedMetadata, 'timed-metadata'); this.trigger('done'); }; }; ElementaryStream.prototype = new Stream(); var m2ts = { PAT_PID: 0x0000, MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH, TransportPacketStream: TransportPacketStream, TransportParseStream: TransportParseStream, ElementaryStream: ElementaryStream, CaptionStream: CaptionStream.CaptionStream, Cea608Stream: CaptionStream.Cea608Stream, MetadataStream: require('./metadata-stream'), }; for (var type in StreamTypes) { if (StreamTypes.hasOwnProperty(type)) { m2ts[type] = StreamTypes[type]; } } module.exports = m2ts; },{"../utils/stream.js":20,"./caption-stream":9,"./metadata-stream":12,"./stream-types":13,"./stream-types.js":13}],12:[function(require,module,exports){ /** * Accepts program elementary stream (PES) data events and parses out * ID3 metadata from them, if present. * @see http://id3.org/id3v2.3.0 */ 'use strict'; var Stream = require('../utils/stream'), StreamTypes = require('./stream-types'), // return a percent-encoded representation of the specified byte range // @see http://en.wikipedia.org/wiki/Percent-encoding percentEncode = function(bytes, start, end) { var i, result = ''; for (i = start; i < end; i++) { result += '%' + ('00' + bytes[i].toString(16)).slice(-2); } return result; }, // return the string representation of the specified byte range, // interpreted as UTf-8. parseUtf8 = function(bytes, start, end) { return decodeURIComponent(percentEncode(bytes, start, end)); }, // return the string representation of the specified byte range, // interpreted as ISO-8859-1. parseIso88591 = function(bytes, start, end) { return unescape(percentEncode(bytes, start, end)); // jshint ignore:line }, parseSyncSafeInteger = function (data) { return (data[0] << 21) | (data[1] << 14) | (data[2] << 7) | (data[3]); }, tagParsers = { 'TXXX': function(tag) { var i; if (tag.data[0] !== 3) { // ignore frames with unrecognized character encodings return; } for (i = 1; i < tag.data.length; i++) { if (tag.data[i] === 0) { // parse the text fields tag.description = parseUtf8(tag.data, 1, i); // do not include the null terminator in the tag value tag.value = parseUtf8(tag.data, i + 1, tag.data.length - 1); break; } } tag.data = tag.value; }, 'WXXX': function(tag) { var i; if (tag.data[0] !== 3) { // ignore frames with unrecognized character encodings return; } for (i = 1; i < tag.data.length; i++) { if (tag.data[i] === 0) { // parse the description and URL fields tag.description = parseUtf8(tag.data, 1, i); tag.url = parseUtf8(tag.data, i + 1, tag.data.length); break; } } }, 'PRIV': function(tag) { var i; for (i = 0; i < tag.data.length; i++) { if (tag.data[i] === 0) { // parse the description and URL fields tag.owner = parseIso88591(tag.data, 0, i); break; } } tag.privateData = tag.data.subarray(i + 1); tag.data = tag.privateData; } }, MetadataStream; MetadataStream = function(options) { var settings = { debug: !!(options && options.debug), // the bytes of the program-level descriptor field in MP2T // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and // program element descriptors" descriptor: options && options.descriptor }, // the total size in bytes of the ID3 tag being parsed tagSize = 0, // tag data that is not complete enough to be parsed buffer = [], // the total number of bytes currently in the buffer bufferSize = 0, i; MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track this.dispatchType = StreamTypes.METADATA_STREAM_TYPE.toString(16); if (settings.descriptor) { for (i = 0; i < settings.descriptor.length; i++) { this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2); } } this.push = function(chunk) { var tag, frameStart, frameSize, frame, i, frameHeader; if (chunk.type !== 'timed-metadata') { return; } // if data_alignment_indicator is set in the PES header, // we must have the start of a new ID3 tag. Assume anything // remaining in the buffer was malformed and throw it out if (chunk.dataAlignmentIndicator) { bufferSize = 0; buffer.length = 0; } // ignore events that don't look like ID3 data if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== 'I'.charCodeAt(0) || chunk.data[1] !== 'D'.charCodeAt(0) || chunk.data[2] !== '3'.charCodeAt(0))) { if (settings.debug) { console.log('Skipping unrecognized metadata packet'); } return; } // add this chunk to the data we've collected so far buffer.push(chunk); bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header if (buffer.length === 1) { // the frame size is transmitted as a 28-bit integer in the // last four bytes of the ID3 header. // The most significant bit of each byte is dropped and the // results concatenated to recover the actual value. tagSize = parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more // convenient for our comparisons to include it tagSize += 10; } // if the entire frame has not arrived, wait for more data if (bufferSize < tagSize) { return; } // collect the entire frame so it can be parsed tag = { data: new Uint8Array(tagSize), frames: [], pts: buffer[0].pts, dts: buffer[0].dts }; for (i = 0; i < tagSize;) { tag.data.set(buffer[0].data.subarray(0, tagSize - i), i); i += buffer[0].data.byteLength; bufferSize -= buffer[0].data.byteLength; buffer.shift(); } // find the start of the first frame and the end of the tag frameStart = 10; if (tag.data[5] & 0x40) { // advance the frame start past the extended header frameStart += 4; // header size field frameStart += parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end tagSize -= parseSyncSafeInteger(tag.data.subarray(16, 20)); } // parse one or more ID3 frames // http://id3.org/id3v2.3.0#ID3v2_frame_overview do { // determine the number of bytes in this frame frameSize = parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8)); if (frameSize < 1) { return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.'); } frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]); frame = { id: frameHeader, data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10) }; frame.key = frame.id; if (tagParsers[frame.id]) { tagParsers[frame.id](frame); if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') { var d = frame.data, size = ((d[3] & 0x01) << 30) | (d[4] << 22) | (d[5] << 14) | (d[6] << 6) | (d[7] >>> 2); size *= 4; size += d[7] & 0x03; frame.timeStamp = size; this.trigger('timestamp', frame); } } tag.frames.push(frame); frameStart += 10; // advance past the frame header frameStart += frameSize; // advance past the frame body } while (frameStart < tagSize); this.trigger('data', tag); }; }; MetadataStream.prototype = new Stream(); module.exports = MetadataStream; },{"../utils/stream":20,"./stream-types":13}],13:[function(require,module,exports){ 'use strict'; module.exports = { H264_STREAM_TYPE: 0x1B, ADTS_STREAM_TYPE: 0x0F, METADATA_STREAM_TYPE: 0x15 }; },{}],14:[function(require,module,exports){ module.exports = { generator: require('./mp4-generator'), Transmuxer: require('./transmuxer').Transmuxer, AudioSegmentStream: require('./transmuxer').AudioSegmentStream, VideoSegmentStream: require('./transmuxer').VideoSegmentStream, tools: require('../tools/mp4-inspector'), }; },{"../tools/mp4-inspector":18,"./mp4-generator":15,"./transmuxer":16}],15:[function(require,module,exports){ /** * mux.js * * Copyright (c) 2015 Brightcove * All rights reserved. * * Functions that generate fragmented MP4s suitable for use with Media * Source Extensions. */ 'use strict'; var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, styp, traf, trex, trun, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR, AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS; // pre-calculate constants (function() { var i; types = { avc1: [], // codingname avcC: [], btrt: [], dinf: [], dref: [], esds: [], ftyp: [], hdlr: [], mdat: [], mdhd: [], mdia: [], mfhd: [], minf: [], moof: [], moov: [], mp4a: [], // codingname mvex: [], mvhd: [], sdtp: [], smhd: [], stbl: [], stco: [], stsc: [], stsd: [], stsz: [], stts: [], styp: [], tfdt: [], tfhd: [], traf: [], trak: [], trun: [], trex: [], tkhd: [], vmhd: [] }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we // don't throw an error if (typeof Uint8Array === 'undefined') { return; } for (i in types) { if (types.hasOwnProperty(i)) { types[i] = [ i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3) ]; } } MAJOR_BRAND = new Uint8Array([ 'i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0) ]); AVC1_BRAND = new Uint8Array([ 'a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0) ]); MINOR_VERSION = new Uint8Array([0, 0, 0, 1]); VIDEO_HDLR = new Uint8Array([ 0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // pre_defined 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide' 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler' ]); AUDIO_HDLR = new Uint8Array([ 0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // pre_defined 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun' 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler' ]); HDLR_TYPES = { "video":VIDEO_HDLR, "audio": AUDIO_HDLR }; DREF = new Uint8Array([ 0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x01, // entry_count 0x00, 0x00, 0x00, 0x0c, // entry_size 0x75, 0x72, 0x6c, 0x20, // 'url' type 0x00, // version 0 0x00, 0x00, 0x01 // entry_flags ]); SMHD = new Uint8Array([ 0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, // balance, 0 means centered 0x00, 0x00 // reserved ]); STCO = new Uint8Array([ 0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00 // entry_count ]); STSC = STCO; STSZ = new Uint8Array([ 0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // sample_size 0x00, 0x00, 0x00, 0x00, // sample_count ]); STTS = STCO; VMHD = new Uint8Array([ 0x00, // version 0x00, 0x00, 0x01, // flags 0x00, 0x00, // graphicsmode 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor ]); })(); box = function(type) { var payload = [], size = 0, i, result, view; for (i = 1; i < arguments.length; i++) { payload.push(arguments[i]); } i = payload.length; // calculate the total size we need to allocate while (i--) { size += payload[i].byteLength; } result = new Uint8Array(size + 8); view = new DataView(result.buffer, result.byteOffset, result.byteLength); view.setUint32(0, result.byteLength); result.set(type, 4); // copy the payload into the result for (i = 0, size = 8; i < payload.length; i++) { result.set(payload[i], size); size += payload[i].byteLength; } return result; }; dinf = function() { return box(types.dinf, box(types.dref, DREF)); }; esds = function(track) { return box(types.esds, new Uint8Array([ 0x00, // version 0x00, 0x00, 0x00, // flags // ES_Descriptor 0x03, // tag, ES_DescrTag 0x19, // length 0x00, 0x00, // ES_ID 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority // DecoderConfigDescriptor 0x04, // tag, DecoderConfigDescrTag 0x11, // length 0x40, // object type 0x15, // streamType 0x00, 0x06, 0x00, // bufferSizeDB 0x00, 0x00, 0xda, 0xc0, // maxBitrate 0x00, 0x00, 0xda, 0xc0, // avgBitrate // DecoderSpecificInfo 0x05, // tag, DecoderSpecificInfoTag 0x02, // length // ISO/IEC 14496-3, AudioSpecificConfig // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35 (track.audioobjecttype << 3) | (track.samplingfrequencyindex >>> 1), (track.samplingfrequencyindex << 7) | (track.channelcount << 3), 0x06, 0x01, 0x02 // GASpecificConfig ])); }; ftyp = function() { return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND); }; hdlr = function(type) { return box(types.hdlr, HDLR_TYPES[type]); }; mdat = function(data) { return box(types.mdat, data); }; mdhd = function(track) { var result = new Uint8Array([ 0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x02, // creation_time 0x00, 0x00, 0x00, 0x03, // modification_time 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second (track.duration >>> 24) & 0xFF, (track.duration >>> 16) & 0xFF, (track.duration >>> 8) & 0xFF, track.duration & 0xFF, // duration 0x55, 0xc4, // 'und' language (undetermined) 0x00, 0x00 ]); // Use the sample rate from the track metadata, when it is // defined. The sample rate can be parsed out of an ADTS header, for // instance. if (track.samplerate) { result[12] = (track.samplerate >>> 24) & 0xFF; result[13] = (track.samplerate >>> 16) & 0xFF; result[14] = (track.samplerate >>> 8) & 0xFF; result[15] = (track.samplerate) & 0xFF; } return box(types.mdhd, result); }; mdia = function(track) { return box(types.mdia, mdhd(track), hdlr(track.type), minf(track)); }; mfhd = function(sequenceNumber) { return box(types.mfhd, new Uint8Array([ 0x00, 0x00, 0x00, 0x00, // flags (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF, // sequence_number ])); }; minf = function(track) { return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track)); }; moof = function(sequenceNumber, tracks) { var trackFragments = [], i = tracks.length; // build traf boxes for each track fragment while (i--) { trackFragments[i] = traf(tracks[i]); } return box.apply(null, [ types.moof, mfhd(sequenceNumber) ].concat(trackFragments)); }; /** * Returns a movie box. * @param tracks {array} the tracks associated with this movie * @see ISO/IEC 14496-12:2012(E), section 8.2.1 */ moov = function(tracks) { var i = tracks.length, boxes = []; while (i--) { boxes[i] = trak(tracks[i]); } return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks))); }; mvex = function(tracks) { var i = tracks.length, boxes = []; while (i--) { boxes[i] = trex(tracks[i]); } return box.apply(null, [types.mvex].concat(boxes)); }; mvhd = function(duration) { var bytes = new Uint8Array([ 0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x01, // creation_time 0x00, 0x00, 0x00, 0x02, // modification_time 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration 0x00, 0x01, 0x00, 0x00, // 1.0 rate 0x01, 0x00, // 1.0 volume 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined 0xff, 0xff, 0xff, 0xff // next_track_ID ]); return box(types.mvhd, bytes); }; sdtp = function(track) { var samples = track.samples || [], bytes = new Uint8Array(4 + samples.length), flags, i; // leave the full box header (4 bytes) all zero // write the sample table for (i = 0; i < samples.length; i++) { flags = samples[i].flags; bytes[i + 4] = (flags.dependsOn << 4) | (flags.isDependedOn << 2) | (flags.hasRedundancy); } return box(types.sdtp, bytes); }; stbl = function(track) { return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO)); }; (function() { var videoSample, audioSample; stsd = function(track) { return box(types.stsd, new Uint8Array([ 0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x01 ]), track.type === 'video' ? videoSample(track) : audioSample(track)); }; videoSample = function(track) { var sps = track.sps || [], pps = track.pps || [], sequenceParameterSets = [], pictureParameterSets = [], i; // assemble the SPSs for (i = 0; i < sps.length; i++) { sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8); sequenceParameterSets.push((sps[i].byteLength & 0xFF)); // sequenceParameterSetLength sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS } // assemble the PPSs for (i = 0; i < pps.length; i++) { pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8); pictureParameterSets.push((pps[i].byteLength & 0xFF)); pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i])); } return box(types.avc1, new Uint8Array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // data_reference_index 0x00, 0x00, // pre_defined 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined (track.width & 0xff00) >> 8, track.width & 0xff, // width (track.height & 0xff00) >> 8, track.height & 0xff, // height 0x00, 0x48, 0x00, 0x00, // horizresolution 0x00, 0x48, 0x00, 0x00, // vertresolution 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // frame_count 0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname 0x00, 0x18, // depth = 24 0x11, 0x11 // pre_defined = -1 ]), box(types.avcC, new Uint8Array([ 0x01, // configurationVersion track.profileIdc, // AVCProfileIndication track.profileCompatibility, // profile_compatibility track.levelIdc, // AVCLevelIndication 0xff // lengthSizeMinusOne, hard-coded to 4 bytes ].concat([ sps.length // numOfSequenceParameterSets ]).concat(sequenceParameterSets).concat([ pps.length // numOfPictureParameterSets ]).concat(pictureParameterSets))), // "PPS" box(types.btrt, new Uint8Array([ 0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate 0x00, 0x2d, 0xc6, 0xc0 ])) // avgBitrate ); }; audioSample = function(track) { return box(types.mp4a, new Uint8Array([ // SampleEntry, ISO/IEC 14496-12 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // data_reference_index // AudioSampleEntry, ISO/IEC 14496-12 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved (track.channelcount & 0xff00) >> 8, (track.channelcount & 0xff), // channelcount (track.samplesize & 0xff00) >> 8, (track.samplesize & 0xff), // samplesize 0x00, 0x00, // pre_defined 0x00, 0x00, // reserved (track.samplerate & 0xff00) >> 8, (track.samplerate & 0xff), 0x00, 0x00 // samplerate, 16.16 // MP4AudioSampleEntry, ISO/IEC 14496-14 ]), esds(track)); }; })(); styp = function() { return box(types.styp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND); }; tkhd = function(track) { var result = new Uint8Array([ 0x00, // version 0 0x00, 0x00, 0x07, // flags 0x00, 0x00, 0x00, 0x00, // creation_time 0x00, 0x00, 0x00, 0x00, // modification_time (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID 0x00, 0x00, 0x00, 0x00, // reserved (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, // layer 0x00, 0x00, // alternate_group 0x01, 0x00, // non-audio track volume 0x00, 0x00, // reserved 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height ]); return box(types.tkhd, result); }; /** * Generate a track fragment (traf) box. A traf box collects metadata * about tracks in a movie fragment (moof) box. */ traf = function(track) { var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset; trackFragmentHeader = box(types.tfhd, new Uint8Array([ 0x00, // version 0 0x00, 0x00, 0x3a, // flags (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, (track.id & 0xFF), // track_ID 0x00, 0x00, 0x00, 0x01, // sample_description_index 0x00, 0x00, 0x00, 0x00, // default_sample_duration 0x00, 0x00, 0x00, 0x00, // default_sample_size 0x00, 0x00, 0x00, 0x00 // default_sample_flags ])); trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([ 0x00, // version 0 0x00, 0x00, 0x00, // flags // baseMediaDecodeTime (track.baseMediaDecodeTime >>> 24) & 0xFF, (track.baseMediaDecodeTime >>> 16) & 0xFF, (track.baseMediaDecodeTime >>> 8) & 0xFF, track.baseMediaDecodeTime & 0xFF ])); // the data offset specifies the number of bytes from the start of // the containing moof to the first payload byte of the associated // mdat dataOffset = (32 + // tfhd 16 + // tfdt 8 + // traf header 16 + // mfhd 8 + // moof header 8); // mdat header // audio tracks require less metadata if (track.type === 'audio') { trackFragmentRun = trun(track, dataOffset); return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun); } // video tracks should contain an independent and disposable samples // box (sdtp) // generate one and adjust offsets to match sampleDependencyTable = sdtp(track); trackFragmentRun = trun(track, sampleDependencyTable.length + dataOffset); return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable); }; /** * Generate a track box. * @param track {object} a track definition * @return {Uint8Array} the track box */ trak = function(track) { track.duration = track.duration || 0xffffffff; return box(types.trak, tkhd(track), mdia(track)); }; trex = function(track) { var result = new Uint8Array([ 0x00, // version 0 0x00, 0x00, 0x00, // flags (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, (track.id & 0xFF), // track_ID 0x00, 0x00, 0x00, 0x01, // default_sample_description_index 0x00, 0x00, 0x00, 0x00, // default_sample_duration 0x00, 0x00, 0x00, 0x00, // default_sample_size 0x00, 0x01, 0x00, 0x01 // default_sample_flags ]); // the last two bytes of default_sample_flags is the sample // degradation priority, a hint about the importance of this sample // relative to others. Lower the degradation priority for all sample // types other than video. if (track.type !== 'video') { result[result.length - 1] = 0x00; } return box(types.trex, result); }; (function() { var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a // duration is present for the first sample, it will be present for // all subsequent samples. // see ISO/IEC 14496-12:2012, Section 8.8.8.1 trunHeader = function(samples, offset) { var durationPresent = 0, sizePresent = 0, flagsPresent = 0, compositionTimeOffset = 0; // trun flag constants if (samples.length) { if (samples[0].duration !== undefined) { durationPresent = 0x1; } if (samples[0].size !== undefined) { sizePresent = 0x2; } if (samples[0].flags !== undefined) { flagsPresent = 0x4; } if (samples[0].compositionTimeOffset !== undefined) { compositionTimeOffset = 0x8; } } return [ 0x00, // version 0 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset ]; }; videoTrun = function(track, offset) { var bytes, samples, sample, i; samples = track.samples || []; offset += 8 + 12 + (16 * samples.length); bytes = trunHeader(samples, offset); for (i = 0; i < samples.length; i++) { sample = samples[i]; bytes = bytes.concat([ (sample.duration & 0xFF000000) >>> 24, (sample.duration & 0xFF0000) >>> 16, (sample.duration & 0xFF00) >>> 8, sample.duration & 0xFF, // sample_duration (sample.size & 0xFF000000) >>> 24, (sample.size & 0xFF0000) >>> 16, (sample.size & 0xFF00) >>> 8, sample.size & 0xFF, // sample_size (sample.flags.isLeading << 2) | sample.flags.dependsOn, (sample.flags.isDependedOn << 6) | (sample.flags.hasRedundancy << 4) | (sample.flags.paddingValue << 1) | sample.flags.isNonSyncSample, sample.flags.degradationPriority & 0xF0 << 8, sample.flags.degradationPriority & 0x0F, // sample_flags (sample.compositionTimeOffset & 0xFF000000) >>> 24, (sample.compositionTimeOffset & 0xFF0000) >>> 16, (sample.compositionTimeOffset & 0xFF00) >>> 8, sample.compositionTimeOffset & 0xFF // sample_composition_time_offset ]); } return box(types.trun, new Uint8Array(bytes)); }; audioTrun = function(track, offset) { var bytes, samples, sample, i; samples = track.samples || []; offset += 8 + 12 + (8 * samples.length); bytes = trunHeader(samples, offset); for (i = 0; i < samples.length; i++) { sample = samples[i]; bytes = bytes.concat([ (sample.duration & 0xFF000000) >>> 24, (sample.duration & 0xFF0000) >>> 16, (sample.duration & 0xFF00) >>> 8, sample.duration & 0xFF, // sample_duration (sample.size & 0xFF000000) >>> 24, (sample.size & 0xFF0000) >>> 16, (sample.size & 0xFF00) >>> 8, sample.size & 0xFF]); // sample_size } return box(types.trun, new Uint8Array(bytes)); }; trun = function(track, offset) { if (track.type === 'audio') { return audioTrun(track, offset); } else { return videoTrun(track, offset); } }; })(); module.exports = { ftyp: ftyp, mdat: mdat, moof: moof, moov: moov, initSegment: function(tracks) { var fileType = ftyp(), movie = moov(tracks), result; result = new Uint8Array(fileType.byteLength + movie.byteLength); result.set(fileType); result.set(movie, fileType.byteLength); return result; } }; },{}],16:[function(require,module,exports){ /** * mux.js * * Copyright (c) 2015 Brightcove * All rights reserved. * * A stream-based mp2t to mp4 converter. This utility can be used to * deliver mp4s to a SourceBuffer on platforms that support native * Media Source Extensions. */ 'use strict'; var Stream = require('../utils/stream.js'); var mp4 = require('./mp4-generator.js'); var m2ts = require('../m2ts/m2ts.js'); var AdtsStream = require('../codecs/adts.js'); var H264Stream = require('../codecs/h264').H264Stream; var AacStream = require('../aac'); // constants var AUDIO_PROPERTIES = [ 'audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize' ]; var VIDEO_PROPERTIES = [ 'width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', ]; // object types var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream; // Helper functions var createDefaultSample, isLikelyAacData, collectDtsInfo, clearDtsInfo, calculateTrackBaseMediaDecodeTime, arrayEquals, sumFrameByteLengths; /** * Default sample object * see ISO/IEC 14496-12:2012, section 8.6.4.3 */ createDefaultSample = function () { return { size: 0, flags: { isLeading: 0, dependsOn: 1, isDependedOn: 0, hasRedundancy: 0, degradationPriority: 0 } }; }; isLikelyAacData = function (data) { if ((data[0] === 'I'.charCodeAt(0)) && (data[1] === 'D'.charCodeAt(0)) && (data[2] === '3'.charCodeAt(0))) { return true; } return false; }; /** * Compare two arrays (even typed) for same-ness */ arrayEquals = function(a, b) { var i; if (a.length !== b.length) { return false; } // compare the value of each element in the array for (i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; }; /** * Sum the `byteLength` properties of the data in each AAC frame */ sumFrameByteLengths = function(array) { var i, currentObj, sum = 0; // sum the byteLength's all each nal unit in the frame for (i = 0; i < array.length; i++) { currentObj = array[i]; sum += currentObj.data.byteLength; } return sum; }; /** * Constructs a single-track, ISO BMFF media segment from AAC data * events. The output of this stream can be fed to a SourceBuffer * configured with a suitable initialization segment. */ AudioSegmentStream = function(track) { var adtsFrames = [], sequenceNumber = 0, earliestAllowedDts = 0; AudioSegmentStream.prototype.init.call(this); this.push = function(data) { collectDtsInfo(track, data); if (track) { AUDIO_PROPERTIES.forEach(function(prop) { track[prop] = data[prop]; }); } // buffer audio data until end() is called adtsFrames.push(data); }; this.setEarliestDts = function(earliestDts) { earliestAllowedDts = earliestDts - track.timelineStartInfo.baseMediaDecodeTime; }; this.flush = function() { var frames, moof, mdat, boxes; // return early if no audio data has been observed if (adtsFrames.length === 0) { this.trigger('done', 'AudioSegmentStream'); return; } frames = this.trimAdtsFramesByEarliestDts_(adtsFrames); // we have to build the index from byte locations to // samples (that is, adts frames) in the audio data track.samples = this.generateSampleTable_(frames); // concatenate the audio data to constuct the mdat mdat = mp4.mdat(this.concatenateFrameData_(frames)); adtsFrames = []; calculateTrackBaseMediaDecodeTime(track); moof = mp4.moof(sequenceNumber, [track]); boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time sequenceNumber++; boxes.set(moof); boxes.set(mdat, moof.byteLength); clearDtsInfo(track); this.trigger('data', {track: track, boxes: boxes}); this.trigger('done', 'AudioSegmentStream'); }; // If the audio segment extends before the earliest allowed dts // value, remove AAC frames until starts at or after the earliest // allowed DTS so that we don't end up with a negative baseMedia- // DecodeTime for the audio track this.trimAdtsFramesByEarliestDts_ = function(adtsFrames) { if (track.minSegmentDts >= earliestAllowedDts) { return adtsFrames; } // We will need to recalculate the earliest segment Dts track.minSegmentDts = Infinity; return adtsFrames.filter(function(currentFrame) { // If this is an allowed frame, keep it and record it's Dts if (currentFrame.dts >= earliestAllowedDts) { track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts); track.minSegmentPts = track.minSegmentDts; return true; } // Otherwise, discard it return false; }); }; // generate the track's raw mdat data from an array of frames this.generateSampleTable_ = function(frames) { var i, currentFrame, samples = []; for (i = 0; i < frames.length; i++) { currentFrame = frames[i]; samples.push({ size: currentFrame.data.byteLength, duration: 1024 // For AAC audio, all samples contain 1024 samples }); } return samples; }; // generate the track's sample table from an array of frames this.concatenateFrameData_ = function(frames) { var i, currentFrame, dataOffset = 0, data = new Uint8Array(sumFrameByteLengths(frames)); for (i = 0; i < frames.length; i++) { currentFrame = frames[i]; data.set(currentFrame.data, dataOffset); dataOffset += currentFrame.data.byteLength; } return data; }; }; AudioSegmentStream.prototype = new Stream(); /** * Constructs a single-track, ISO BMFF media segment from H264 data * events. The output of this stream can be fed to a SourceBuffer * configured with a suitable initialization segment. * @param track {object} track metadata configuration */ VideoSegmentStream = function(track) { var sequenceNumber = 0, nalUnits = [], config, pps; VideoSegmentStream.prototype.init.call(this); delete track.minPTS; this.gopCache_ = []; this.push = function(nalUnit) { collectDtsInfo(track, nalUnit); // record the track config if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) { config = nalUnit.config; track.sps = [nalUnit.data]; VIDEO_PROPERTIES.forEach(function(prop) { track[prop] = config[prop]; }, this); } if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) { pps = nalUnit.data; track.pps = [nalUnit.data]; } // buffer video until flush() is called nalUnits.push(nalUnit); }; this.flush = function() { var frames, gopForFusion, gops, moof, mdat, boxes; // Throw away nalUnits at the start of the byte stream until // we find the first AUD while (nalUnits.length) { if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') { break; } nalUnits.shift(); } // Return early if no video data has been observed if (nalUnits.length === 0) { this.resetStream_(); this.trigger('done', 'VideoSegmentStream'); return; } // Organize the raw nal-units into arrays that represent // higher-level constructs such as frames and gops // (group-of-pictures) frames = this.groupNalsIntoFrames_(nalUnits); gops = this.groupFramesIntoGops_(frames); // If the first frame of this fragment is not a keyframe we have // a problem since MSE (on Chrome) requires a leading keyframe. // // We have two approaches to repairing this situation: // 1) GOP-FUSION: // This is where we keep track of the GOPS (group-of-pictures) // from previous fragments and attempt to find one that we can // prepend to the current fragment in order to create a valid // fragment. // 2) KEYFRAME-PULLING: // Here we search for the first keyframe in the fragment and // throw away all the frames between the start of the fragment // and that keyframe. We then extend the duration and pull the // PTS of the keyframe forward so that it covers the time range // of the frames that were disposed of. // // #1 is far prefereable over #2 which can cause "stuttering" but // requires more things to be just right. if (!gops[0][0].keyFrame) { // Search for a gop for fusion from our gopCache gopForFusion = this.getGopForFusion_(nalUnits[0], track); if (gopForFusion) { gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the // new gop at the beginning gops.byteLength += gopForFusion.byteLength; gops.nalCount += gopForFusion.nalCount; gops.pts = gopForFusion.pts; gops.dts = gopForFusion.dts; gops.duration += gopForFusion.duration; } else { // If we didn't find a candidate gop fall back to keyrame-pulling gops = this.extendFirstKeyFrame_(gops); } } collectDtsInfo(track, gops); // First, we have to build the index from byte locations to // samples (that is, frames) in the video data track.samples = this.generateSampleTable_(gops); // Concatenate the video data and construct the mdat mdat = mp4.mdat(this.concatenateNalData_(gops)); // save all the nals in the last GOP into the gop cache this.gopCache_.unshift({ gop: gops.pop(), pps: track.pps, sps: track.sps }); // Keep a maximum of 6 GOPs in the cache this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits nalUnits = []; calculateTrackBaseMediaDecodeTime(track); this.trigger('timelineStartInfo', track.timelineStartInfo); moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of // throwing away hundreds of media segment fragments boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time sequenceNumber++; boxes.set(moof); boxes.set(mdat, moof.byteLength); this.trigger('data', {track: track, boxes: boxes}); this.resetStream_(); // Continue with the flush process now this.trigger('done', 'VideoSegmentStream'); }; this.resetStream_ = function() { clearDtsInfo(track); // reset config and pps because they may differ across segments // for instance, when we are rendition switching config = undefined; pps = undefined; }; // Search for a candidate Gop for gop-fusion from the gop cache and // return it or return null if no good candidate was found this.getGopForFusion_ = function (nalUnit) { var halfSecond = 45000, // Half-a-second in a 90khz clock allowableOverlap = 10000, // About 3 frames @ 30fps nearestDistance = Infinity, dtsDistance, nearestGopObj, currentGop, currentGopObj, i; // Search for the GOP nearest to the beginning of this nal unit for (i = 0; i < this.gopCache_.length; i++) { currentGopObj = this.gopCache_[i]; currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) { continue; } // Reject Gops that would require a negative baseMediaDecodeTime if (currentGop.dts < track.timelineStartInfo.dts) { continue; } // The distance between the end of the gop and the start of the nalUnit dtsDistance = (nalUnit.dts - currentGop.dts) - currentGop.duration; // Only consider GOPS that start before the nal unit and end within // a half-second of the nal unit if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) { // Always use the closest GOP we found if there is more than // one candidate if (!nearestGopObj || nearestDistance > dtsDistance) { nearestGopObj = currentGopObj; nearestDistance = dtsDistance; } } } if (nearestGopObj) { return nearestGopObj.gop; } return null; }; this.extendFirstKeyFrame_ = function(gops) { var h, i, currentGop, newGops; if (!gops[0][0].keyFrame) { // Remove the first GOP currentGop = gops.shift(); gops.byteLength -= currentGop.byteLength; gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the // first gop to cover the time period of the // frames we just removed gops[0][0].dts = currentGop.dts; gops[0][0].pts = currentGop.pts; gops[0][0].duration += currentGop.duration; } return gops; }; // Convert an array of nal units into an array of frames with each frame being // composed of the nal units that make up that frame // Also keep track of cummulative data about the frame from the nal units such // as the frame duration, starting pts, etc. this.groupNalsIntoFrames_ = function(nalUnits) { var i, currentNal, startPts, startDts, currentFrame = [], frames = []; currentFrame.byteLength = 0; for (i = 0; i < nalUnits.length; i++) { currentNal = nalUnits[i]; // Split on 'aud'-type nal units if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') { // Since the very first nal unit is expected to be an AUD // only push to the frames array when currentFrame is not empty if (currentFrame.length) { currentFrame.duration = currentNal.dts - currentFrame.dts; frames.push(currentFrame); } currentFrame = [currentNal]; currentFrame.byteLength = currentNal.data.byteLength; currentFrame.pts = currentNal.pts; currentFrame.dts = currentNal.dts; } else { // Specifically flag key frames for ease of use later if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') { currentFrame.keyFrame = true; } currentFrame.duration = currentNal.dts - currentFrame.dts; currentFrame.byteLength += currentNal.data.byteLength; currentFrame.push(currentNal); } } // For the last frame, use the duration of the previous frame if we // have nothing better to go on if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) { currentFrame.duration = frames[frames.length - 1].duration; } // Push the final frame frames.push(currentFrame); return frames; }; // Convert an array of frames into an array of Gop with each Gop being composed // of the frames that make up that Gop // Also keep track of cummulative data about the Gop from the frames such as the // Gop duration, starting pts, etc. this.groupFramesIntoGops_ = function(frames) { var i, currentFrame, currentGop = [], gops = []; // We must pre-set some of the values on the Gop since we // keep running totals of these values currentGop.byteLength = 0; currentGop.nalCount = 0; currentGop.duration = 0; currentGop.pts = frames[0].pts; currentGop.dts = frames[0].dts; // store some metadata about all the Gops gops.byteLength = 0; gops.nalCount = 0; gops.duration = 0; gops.pts = frames[0].pts; gops.dts = frames[0].dts; for (i = 0; i < frames.length; i++) { currentFrame = frames[i]; if (currentFrame.keyFrame) { // Since the very first frame is expected to be an keyframe // only push to the gops array when currentGop is not empty if (currentGop.length) { gops.push(currentGop); gops.byteLength += currentGop.byteLength; gops.nalCount += currentGop.nalCount; gops.duration += currentGop.duration; } currentGop = [currentFrame]; currentGop.nalCount = currentFrame.length; currentGop.byteLength = currentFrame.byteLength; currentGop.pts = currentFrame.pts; currentGop.dts = currentFrame.dts; currentGop.duration = currentFrame.duration; } else { currentGop.duration += currentFrame.duration; currentGop.nalCount += currentFrame.length; currentGop.byteLength += currentFrame.byteLength; currentGop.push(currentFrame); } } if (gops.length && currentGop.duration <= 0) { currentGop.duration = gops[gops.length - 1].duration; } gops.byteLength += currentGop.byteLength; gops.nalCount += currentGop.nalCount; gops.duration += currentGop.duration; // push the final Gop gops.push(currentGop); return gops; }; // generate the track's sample table from an array of gops this.generateSampleTable_ = function(gops, baseDataOffset) { var h, i, sample, currentGop, currentFrame, currentSample, dataOffset = baseDataOffset || 0, samples = []; for (h = 0; h < gops.length; h++) { currentGop = gops[h]; for (i = 0; i < currentGop.length; i++) { currentFrame = currentGop[i]; sample = createDefaultSample(); sample.dataOffset = dataOffset; sample.compositionTimeOffset = currentFrame.pts - currentFrame.dts; sample.duration = currentFrame.duration; sample.size = 4 * currentFrame.length; // Space for nal unit size sample.size += currentFrame.byteLength; if (currentFrame.keyFrame) { sample.flags.dependsOn = 2; } dataOffset += sample.size; samples.push(sample); } } return samples; }; // generate the track's raw mdat data from an array of gops this.concatenateNalData_ = function (gops) { var h, i, j, currentGop, currentFrame, currentNal, dataOffset = 0, nalsByteLength = gops.byteLength, numberOfNals = gops.nalCount, totalByteLength = nalsByteLength + 4 * numberOfNals, data = new Uint8Array(totalByteLength), view = new DataView(data.buffer); // For each Gop.. for (h = 0; h < gops.length; h++) { currentGop = gops[h]; // For each Frame.. for (i = 0; i < currentGop.length; i++) { currentFrame = currentGop[i]; // For each NAL.. for (j = 0; j < currentFrame.length; j++) { currentNal = currentFrame[j]; view.setUint32(dataOffset, currentNal.data.byteLength); dataOffset += 4; data.set(currentNal.data, dataOffset); dataOffset += currentNal.data.byteLength; } } } return data; }; }; VideoSegmentStream.prototype = new Stream(); /** * Store information about the start and end of the track and the * duration for each frame/sample we process in order to calculate * the baseMediaDecodeTime */ collectDtsInfo = function (track, data) { if (typeof data.pts === 'number') { if (track.timelineStartInfo.pts === undefined) { track.timelineStartInfo.pts = data.pts; } if (track.minSegmentPts === undefined) { track.minSegmentPts = data.pts; } else { track.minSegmentPts = Math.min(track.minSegmentPts, data.pts); } if (track.maxSegmentPts === undefined) { track.maxSegmentPts = data.pts; } else { track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts); } } if (typeof data.dts === 'number') { if (track.timelineStartInfo.dts === undefined) { track.timelineStartInfo.dts = data.dts; } if (track.minSegmentDts === undefined) { track.minSegmentDts = data.dts; } else { track.minSegmentDts = Math.min(track.minSegmentDts, data.dts); } if (track.maxSegmentDts === undefined) { track.maxSegmentDts = data.dts; } else { track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts); } } }; /** * Clear values used to calculate the baseMediaDecodeTime between * tracks */ clearDtsInfo = function (track) { delete track.minSegmentDts; delete track.maxSegmentDts; delete track.minSegmentPts; delete track.maxSegmentPts; }; /** * Calculate the track's baseMediaDecodeTime based on the earliest * DTS the transmuxer has ever seen and the minimum DTS for the * current track */ calculateTrackBaseMediaDecodeTime = function (track) { var oneSecondInPTS = 90000, // 90kHz clock scale, // Calculate the distance, in time, that this segment starts from the start // of the timeline (earliest time seen since the transmuxer initialized) timeSinceStartOfTimeline = track.minSegmentDts - track.timelineStartInfo.dts, // Calculate the first sample's effective compositionTimeOffset firstSampleCompositionOffset = track.minSegmentPts - track.minSegmentDts; // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where // we want the start of the first segment to be placed track.baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first track.baseMediaDecodeTime += timeSinceStartOfTimeline; // Subtract this segment's "compositionTimeOffset" so that the first frame of // this segment is displayed exactly at the `baseMediaDecodeTime` or at the // end of the previous segment track.baseMediaDecodeTime -= firstSampleCompositionOffset; // baseMediaDecodeTime must not become negative track.baseMediaDecodeTime = Math.max(0, track.baseMediaDecodeTime); if (track.type === 'audio') { // Audio has a different clock equal to the sampling_rate so we need to // scale the PTS values into the clock rate of the track scale = track.samplerate / oneSecondInPTS; track.baseMediaDecodeTime *= scale; track.baseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime); } }; /** * A Stream that can combine multiple streams (ie. audio & video) * into a single output segment for MSE. Also supports audio-only * and video-only streams. */ CoalesceStream = function(options, metadataStream) { // Number of Tracks per output segment // If greater than 1, we combine multiple // tracks into a single segment this.numberOfTracks = 0; this.metadataStream = metadataStream; if (typeof options.remux !== 'undefined') { this.remuxTracks = !!options.remux; } else { this.remuxTracks = true; } this.pendingTracks = []; this.videoTrack = null; this.pendingBoxes = []; this.pendingCaptions = []; this.pendingMetadata = []; this.pendingBytes = 0; this.emittedTracks = 0; CoalesceStream.prototype.init.call(this); // Take output from multiple this.push = function(output) { // buffer incoming captions until the associated video segment // finishes if (output.text) { return this.pendingCaptions.push(output); } // buffer incoming id3 tags until the final flush if (output.frames) { return this.pendingMetadata.push(output); } // Add this track to the list of pending tracks and store // important information required for the construction of // the final segment this.pendingTracks.push(output.track); this.pendingBoxes.push(output.boxes); this.pendingBytes += output.boxes.byteLength; if (output.track.type === 'video') { this.videoTrack = output.track; } if (output.track.type === 'audio') { this.audioTrack = output.track; } }; }; CoalesceStream.prototype = new Stream(); CoalesceStream.prototype.flush = function(flushSource) { var offset = 0, event = { captions: [], metadata: [], info: {} }, caption, id3, initSegment, timelineStartPts = 0, i; if (this.pendingTracks.length < this.numberOfTracks) { if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') { // Return because we haven't received a flush from a data-generating // portion of the segment (meaning that we have only recieved meta-data // or captions.) return; } else if (this.remuxTracks) { // Return until we have enough tracks from the pipeline to remux (if we // are remuxing audio and video into a single MP4) return; } else if (this.pendingTracks.length === 0) { // In the case where we receive a flush without any data having been // received we consider it an emitted track for the purposes of coalescing // `done` events. // We do this for the case where there is an audio and video track in the // segment but no audio data. (seen in several playlists with alternate // audio tracks and no audio present in the main TS segments.) this.emittedTracks++; if (this.emittedTracks >= this.numberOfTracks) { this.trigger('done'); this.emittedTracks = 0; } return; } } if (this.videoTrack) { timelineStartPts = this.videoTrack.timelineStartInfo.pts; VIDEO_PROPERTIES.forEach(function(prop) { event.info[prop] = this.videoTrack[prop]; }, this); } else if (this.audioTrack) { timelineStartPts = this.audioTrack.timelineStartInfo.pts; AUDIO_PROPERTIES.forEach(function(prop) { event.info[prop] = this.audioTrack[prop]; }, this); } if (this.pendingTracks.length === 1) { event.type = this.pendingTracks[0].type; } else { event.type = 'combined'; } this.emittedTracks += this.pendingTracks.length; initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array large enough to hold the init // segment and all tracks event.data = new Uint8Array(initSegment.byteLength + this.pendingBytes); // Create an init segment containing a moov // and track definitions event.data.set(initSegment); offset += initSegment.byteLength; // Append each moof+mdat (one per track) after the init segment for (i = 0; i < this.pendingBoxes.length; i++) { event.data.set(this.pendingBoxes[i], offset); offset += this.pendingBoxes[i].byteLength; } // Translate caption PTS times into second offsets into the // video timeline for the segment for (i = 0; i < this.pendingCaptions.length; i++) { caption = this.pendingCaptions[i]; caption.startTime = (caption.startPts - timelineStartPts); caption.startTime /= 90e3; caption.endTime = (caption.endPts - timelineStartPts); caption.endTime /= 90e3; event.captions.push(caption); } // Translate ID3 frame PTS times into second offsets into the // video timeline for the segment for (i = 0; i < this.pendingMetadata.length; i++) { id3 = this.pendingMetadata[i]; id3.cueTime = (id3.pts - timelineStartPts); id3.cueTime /= 90e3; event.metadata.push(id3); } // We add this to every single emitted segment even though we only need // it for the first event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state this.pendingTracks.length = 0; this.videoTrack = null; this.pendingBoxes.length = 0; this.pendingCaptions.length = 0; this.pendingBytes = 0; this.pendingMetadata.length = 0; // Emit the built segment this.trigger('data', event); // Only emit `done` if all tracks have been flushed and emitted if (this.emittedTracks >= this.numberOfTracks) { this.trigger('done'); this.emittedTracks = 0; } }; /** * A Stream that expects MP2T binary data as input and produces * corresponding media segments, suitable for use with Media Source * Extension (MSE) implementations that support the ISO BMFF byte * stream format, like Chrome. */ Transmuxer = function(options) { var self = this, hasFlushed = true, videoTrack, audioTrack; Transmuxer.prototype.init.call(this); options = options || {}; this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0; this.transmuxPipeline_ = {}; this.setupAacPipeline = function() { var pipeline = {}; this.transmuxPipeline_ = pipeline; pipeline.type = 'aac'; pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline pipeline.aacStream = new AacStream(); pipeline.adtsStream = new AdtsStream(); pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream); pipeline.headOfPipeline = pipeline.aacStream; pipeline.aacStream.pipe(pipeline.adtsStream); pipeline.aacStream.pipe(pipeline.metadataStream); pipeline.metadataStream.pipe(pipeline.coalesceStream); pipeline.metadataStream.on('timestamp', function(frame) { pipeline.aacStream.setTimestamp(frame.timeStamp); }); pipeline.aacStream.on('data', function(data) { var i; if (data.type === 'timed-metadata' && !pipeline.audioSegmentStream) { audioTrack = audioTrack || { timelineStartInfo: { baseMediaDecodeTime: self.baseMediaDecodeTime }, codec: 'adts', type: 'audio' }; // hook up the audio segment stream to the first track with aac data pipeline.coalesceStream.numberOfTracks++; pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack); // Set up the final part of the audio pipeline pipeline.adtsStream .pipe(pipeline.audioSegmentStream) .pipe(pipeline.coalesceStream); } }); // Re-emit any data coming from the coalesce stream to the outside world pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done')); }; this.setupTsPipeline = function() { var pipeline = {}; this.transmuxPipeline_ = pipeline; pipeline.type = 'ts'; pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline pipeline.packetStream = new m2ts.TransportPacketStream(); pipeline.parseStream = new m2ts.TransportParseStream(); pipeline.elementaryStream = new m2ts.ElementaryStream(); pipeline.adtsStream = new AdtsStream(); pipeline.h264Stream = new H264Stream(); pipeline.captionStream = new m2ts.CaptionStream(); pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream); pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams pipeline.packetStream .pipe(pipeline.parseStream) .pipe(pipeline.elementaryStream); // !!THIS ORDER IS IMPORTANT!! // demux the streams pipeline.elementaryStream .pipe(pipeline.h264Stream); pipeline.elementaryStream .pipe(pipeline.adtsStream); pipeline.elementaryStream .pipe(pipeline.metadataStream) .pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream pipeline.h264Stream.pipe(pipeline.captionStream) .pipe(pipeline.coalesceStream); pipeline.elementaryStream.on('data', function(data) { var i; if (data.type === 'metadata') { i = data.tracks.length; // scan the tracks listed in the metadata while (i--) { if (!videoTrack && data.tracks[i].type === 'video') { videoTrack = data.tracks[i]; videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime; } else if (!audioTrack && data.tracks[i].type === 'audio') { audioTrack = data.tracks[i]; audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime; } } // hook up the video segment stream to the first track with h264 data if (videoTrack && !pipeline.videoSegmentStream) { pipeline.coalesceStream.numberOfTracks++; pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack); pipeline.videoSegmentStream.on('timelineStartInfo', function(timelineStartInfo){ // When video emits timelineStartInfo data after a flush, we forward that // info to the AudioSegmentStream, if it exists, because video timeline // data takes precedence. if (audioTrack) { audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the // very earliest DTS we have seen in video because Chrome will // interpret any video track with a baseMediaDecodeTime that is // non-zero as a gap. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts); } }); // Set up the final part of the video pipeline pipeline.h264Stream .pipe(pipeline.videoSegmentStream) .pipe(pipeline.coalesceStream); } if (audioTrack && !pipeline.audioSegmentStream) { // hook up the audio segment stream to the first track with aac data pipeline.coalesceStream.numberOfTracks++; pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack); // Set up the final part of the audio pipeline pipeline.adtsStream .pipe(pipeline.audioSegmentStream) .pipe(pipeline.coalesceStream); } } }); // Re-emit any data coming from the coalesce stream to the outside world pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done')); }; // hook up the segment streams once track metadata is delivered this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) { var pipeline = this.transmuxPipeline_; this.baseMediaDecodeTime = baseMediaDecodeTime; if (audioTrack) { audioTrack.timelineStartInfo.dts = undefined; audioTrack.timelineStartInfo.pts = undefined; clearDtsInfo(audioTrack); audioTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime; } if (videoTrack) { if (pipeline.videoSegmentStream) { pipeline.videoSegmentStream.gopCache_ = []; } videoTrack.timelineStartInfo.dts = undefined; videoTrack.timelineStartInfo.pts = undefined; clearDtsInfo(videoTrack); videoTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime; } }; // feed incoming data to the front of the parsing pipeline this.push = function(data) { if (hasFlushed) { var isAac = isLikelyAacData(data); if (isAac && this.transmuxPipeline_.type !== 'aac') { this.setupAacPipeline(); } else if (!isAac && this.transmuxPipeline_.type !== 'ts') { this.setupTsPipeline(); } hasFlushed = false; } this.transmuxPipeline_.headOfPipeline.push(data); }; // flush any buffered data this.flush = function() { hasFlushed = true; // Start at the top of the pipeline and flush all pending work this.transmuxPipeline_.headOfPipeline.flush(); }; }; Transmuxer.prototype = new Stream(); module.exports = { Transmuxer: Transmuxer, VideoSegmentStream: VideoSegmentStream, AudioSegmentStream: AudioSegmentStream, AUDIO_PROPERTIES: AUDIO_PROPERTIES, VIDEO_PROPERTIES: VIDEO_PROPERTIES }; },{"../aac":1,"../codecs/adts.js":2,"../codecs/h264":3,"../m2ts/m2ts.js":11,"../utils/stream.js":20,"./mp4-generator.js":15}],17:[function(require,module,exports){ 'use strict'; var tagTypes = { 0x08: 'audio', 0x09: 'video', 0x12: 'metadata' }, hex = function (val) { return '0x' + ('00' + val.toString(16)).slice(-2).toUpperCase(); }, hexStringList = function (data) { var arr = [], i; /* jshint -W086 */ while(data.byteLength > 0) { i = 0; switch(data.byteLength) { default: arr.push(hex(data[i++])); case 7: arr.push(hex(data[i++])); case 6: arr.push(hex(data[i++])); case 5: arr.push(hex(data[i++])); case 4: arr.push(hex(data[i++])); case 3: arr.push(hex(data[i++])); case 2: arr.push(hex(data[i++])); case 1: arr.push(hex(data[i++])); } data = data.subarray(i); } /* jshint +W086 */ return arr.join(' '); }, parseAVCTag = function (tag, obj) { var avcPacketTypes = [ 'AVC Sequence Header', 'AVC NALU', 'AVC End-of-Sequence' ], nalUnitTypes = [ 'unspecified', 'slice_layer_without_partitioning', 'slice_data_partition_a_layer', 'slice_data_partition_b_layer', 'slice_data_partition_c_layer', 'slice_layer_without_partitioning_idr', 'sei', 'seq_parameter_set', 'pic_parameter_set', 'access_unit_delimiter', 'end_of_seq', 'end_of_stream', 'filler', 'seq_parameter_set_ext', 'prefix_nal_unit', 'subset_seq_parameter_set', 'reserved', 'reserved', 'reserved' ], compositionTime = (tag[1] & parseInt('01111111', 2) << 16) | (tag[2] << 8) | tag[3]; obj = obj || {}; obj.avcPacketType = avcPacketTypes[tag[0]]; obj.CompositionTime = (tag[1] & parseInt('10000000', 2)) ? -compositionTime : compositionTime; if (tag[0] === 1) { obj.nalUnitTypeRaw = hexStringList(tag.subarray(4, 100)); } else { obj.data = hexStringList(tag.subarray(4)); } return obj; }, parseVideoTag = function (tag, obj) { var frameTypes = [ 'Unknown', 'Keyframe (for AVC, a seekable frame)', 'Inter frame (for AVC, a nonseekable frame)', 'Disposable inter frame (H.263 only)', 'Generated keyframe (reserved for server use only)', 'Video info/command frame' ], codecIDs = [ 'JPEG (currently unused)', 'Sorenson H.263', 'Screen video', 'On2 VP6', 'On2 VP6 with alpha channel', 'Screen video version 2', 'AVC' ], codecID = tag[0] & parseInt('00001111', 2); obj = obj || {}; obj.frameType = frameTypes[(tag[0] & parseInt('11110000', 2)) >>> 4]; obj.codecID = codecID; if (codecID === 7) { return parseAVCTag(tag.subarray(1), obj); } return obj; }, parseAACTag = function (tag, obj) { var packetTypes = [ 'AAC Sequence Header', 'AAC Raw' ]; obj = obj || {}; obj.aacPacketType = packetTypes[tag[0]]; obj.data = hexStringList(tag.subarray(1)); return obj; }, parseAudioTag = function (tag, obj) { var formatTable = [ 'Linear PCM, platform endian', 'ADPCM', 'MP3', 'Linear PCM, little endian', 'Nellymoser 16-kHz mono', 'Nellymoser 8-kHz mono', 'Nellymoser', 'G.711 A-law logarithmic PCM', 'G.711 mu-law logarithmic PCM', 'reserved', 'AAC', 'Speex', 'MP3 8-Khz', 'Device-specific sound' ], samplingRateTable = [ '5.5-kHz', '11-kHz', '22-kHz', '44-kHz' ], soundFormat = (tag[0] & parseInt('11110000', 2)) >>> 4; obj = obj || {}; obj.soundFormat = formatTable[soundFormat]; obj.soundRate = samplingRateTable[(tag[0] & parseInt('00001100', 2)) >>> 2]; obj.soundSize = ((tag[0] & parseInt('00000010', 2)) >>> 1) ? '16-bit' : '8-bit'; obj.soundType = (tag[0] & parseInt('00000001', 2)) ? 'Stereo' : 'Mono'; if (soundFormat === 10) { return parseAACTag(tag.subarray(1), obj); } return obj; }, parseGenericTag = function (tag) { return { tagType: tagTypes[tag[0]], dataSize: (tag[1] << 16) | (tag[2] << 8) | tag[3], timestamp: (tag[7] << 24) | (tag[4] << 16) | (tag[5] << 8) | tag[6], streamID: (tag[8] << 16) | (tag[9] << 8) | tag[10] }; }, inspectFlvTag = function (tag) { var header = parseGenericTag(tag); switch (tag[0]) { case 0x08: parseAudioTag(tag.subarray(11), header); break; case 0x09: parseVideoTag(tag.subarray(11), header); break; case 0x12: } return header; }, inspectFlv = function (bytes) { var i = 9, // header dataSize, parsedResults = [], tag; // traverse the tags i += 4; // skip previous tag size while (i < bytes.byteLength) { dataSize = bytes[i + 1] << 16; dataSize |= bytes[i + 2] << 8; dataSize |= bytes[i + 3]; dataSize += 11; tag = bytes.subarray(i, i + dataSize); parsedResults.push(inspectFlvTag(tag)); i += dataSize + 4; } return parsedResults; }, textifyFlv = function (flvTagArray) { return JSON.stringify(flvTagArray, null, 2); }; module.exports = { inspectTag: inspectFlvTag, inspect: inspectFlv, textify: textifyFlv }; },{}],18:[function(require,module,exports){ (function (global){ 'use strict'; var inspectMp4, textifyMp4, /** * Returns the string representation of an ASCII encoded four byte buffer. * @param buffer {Uint8Array} a four-byte buffer to translate * @return {string} the corresponding string */ parseType = function(buffer) { var result = ''; result += String.fromCharCode(buffer[0]); result += String.fromCharCode(buffer[1]); result += String.fromCharCode(buffer[2]); result += String.fromCharCode(buffer[3]); return result; }, parseMp4Date = function(seconds) { return new Date(seconds * 1000 - 2082844800000); }, parseSampleFlags = function(flags) { return { isLeading: (flags[0] & 0x0c) >>> 2, dependsOn: flags[0] & 0x03, isDependedOn: (flags[1] & 0xc0) >>> 6, hasRedundancy: (flags[1] & 0x30) >>> 4, paddingValue: (flags[1] & 0x0e) >>> 1, isNonSyncSample: flags[1] & 0x01, degradationPriority: (flags[2] << 8) | flags[3] }; }, nalParse = function(avcStream) { var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength), result = [], i, length; for (i = 0; i + 4 < avcStream.length; i += length) { length = avcView.getUint32(i); i += 4; // bail if this doesn't appear to be an H264 stream if (length <= 0) { result.push('<span style=\'color:red;\'>MALFORMED DATA</span>'); continue; } switch(avcStream[i] & 0x1F) { case 0x01: result.push('slice_layer_without_partitioning_rbsp'); break; case 0x05: result.push('slice_layer_without_partitioning_rbsp_idr'); break; case 0x06: result.push('sei_rbsp'); break; case 0x07: result.push('seq_parameter_set_rbsp'); break; case 0x08: result.push('pic_parameter_set_rbsp'); break; case 0x09: result.push('access_unit_delimiter_rbsp'); break; default: result.push('UNKNOWN NAL - ' + avcStream[i] & 0x1F); break; } } return result; }, // registry of handlers for individual mp4 box types parse = { // codingname, not a first-class box type. stsd entries share the // same format as real boxes so the parsing infrastructure can be // shared avc1: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength); return { dataReferenceIndex: view.getUint16(6), width: view.getUint16(24), height: view.getUint16(26), horizresolution: view.getUint16(28) + (view.getUint16(30) / 16), vertresolution: view.getUint16(32) + (view.getUint16(34) / 16), frameCount: view.getUint16(40), depth: view.getUint16(74), config: inspectMp4(data.subarray(78, data.byteLength)) }; }, avcC: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), result = { configurationVersion: data[0], avcProfileIndication: data[1], profileCompatibility: data[2], avcLevelIndication: data[3], lengthSizeMinusOne: data[4] & 0x03, sps: [], pps: [] }, numOfSequenceParameterSets = data[5] & 0x1f, numOfPictureParameterSets, nalSize, offset, i; // iterate past any SPSs offset = 6; for (i = 0; i < numOfSequenceParameterSets; i++) { nalSize = view.getUint16(offset); offset += 2; result.sps.push(new Uint8Array(data.subarray(offset, offset + nalSize))); offset += nalSize; } // iterate past any PPSs numOfPictureParameterSets = data[offset]; offset++; for (i = 0; i < numOfPictureParameterSets; i++) { nalSize = view.getUint16(offset); offset += 2; result.pps.push(new Uint8Array(data.subarray(offset, offset + nalSize))); offset += nalSize; } return result; }, btrt: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength); return { bufferSizeDB: view.getUint32(0), maxBitrate: view.getUint32(4), avgBitrate: view.getUint32(8) }; }, esds: function(data) { return { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), esId: (data[6] << 8) | data[7], streamPriority: data[8] & 0x1f, decoderConfig: { objectProfileIndication: data[11], streamType: (data[12] >>> 2) & 0x3f, bufferSize: (data[13] << 16) | (data[14] << 8) | data[15], maxBitrate: (data[16] << 24) | (data[17] << 16) | (data[18] << 8) | data[19], avgBitrate: (data[20] << 24) | (data[21] << 16) | (data[22] << 8) | data[23], decoderConfigDescriptor: { tag: data[24], length: data[25], audioObjectType: (data[26] >>> 3) & 0x1f, samplingFrequencyIndex: ((data[26] & 0x07) << 1) | ((data[27] >>> 7) & 0x01), channelConfiguration: (data[27] >>> 3) & 0x0f } } }; }, ftyp: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), result = { majorBrand: parseType(data.subarray(0, 4)), minorVersion: view.getUint32(4), compatibleBrands: [] }, i = 8; while (i < data.byteLength) { result.compatibleBrands.push(parseType(data.subarray(i, i + 4))); i += 4; } return result; }, dinf: function(data) { return { boxes: inspectMp4(data) }; }, dref: function(data) { return { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), dataReferences: inspectMp4(data.subarray(8)) }; }, hdlr: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), language, result = { version: view.getUint8(0), flags: new Uint8Array(data.subarray(1, 4)), handlerType: parseType(data.subarray(8, 12)), name: '' }, i = 8; // parse out the name field for (i = 24; i < data.byteLength; i++) { if (data[i] === 0x00) { // the name field is null-terminated i++; break; } result.name += String.fromCharCode(data[i]); } // decode UTF-8 to javascript's internal representation // see http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html result.name = decodeURIComponent(global.escape(result.name)); return result; }, mdat: function(data) { return { byteLength: data.byteLength, nals: nalParse(data) }; }, mdhd: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), i = 4, language, result = { version: view.getUint8(0), flags: new Uint8Array(data.subarray(1, 4)), language: '' }; if (result.version === 1) { i += 4; result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes i += 8; result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes i += 4; result.timescale = view.getUint32(i); i += 8; result.duration = view.getUint32(i); // truncating top 4 bytes } else { result.creationTime = parseMp4Date(view.getUint32(i)); i += 4; result.modificationTime = parseMp4Date(view.getUint32(i)); i += 4; result.timescale = view.getUint32(i); i += 4; result.duration = view.getUint32(i); } i += 4; // language is stored as an ISO-639-2/T code in an array of three 5-bit fields // each field is the packed difference between its ASCII value and 0x60 language = view.getUint16(i); result.language += String.fromCharCode((language >> 10) + 0x60); result.language += String.fromCharCode(((language & 0x03c0) >> 5) + 0x60); result.language += String.fromCharCode((language & 0x1f) + 0x60); return result; }, mdia: function(data) { return { boxes: inspectMp4(data) }; }, mfhd: function(data) { return { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), sequenceNumber: (data[4] << 24) | (data[5] << 16) | (data[6] << 8) | (data[7]) }; }, minf: function(data) { return { boxes: inspectMp4(data) }; }, // codingname, not a first-class box type. stsd entries share the // same format as real boxes so the parsing infrastructure can be // shared mp4a: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), result = { // 6 bytes reserved dataReferenceIndex: view.getUint16(6), // 4 + 4 bytes reserved channelcount: view.getUint16(16), samplesize: view.getUint16(18), // 2 bytes pre_defined // 2 bytes reserved samplerate: view.getUint16(24) + (view.getUint16(26) / 65536) }; // if there are more bytes to process, assume this is an ISO/IEC // 14496-14 MP4AudioSampleEntry and parse the ESDBox if (data.byteLength > 28) { result.streamDescriptor = inspectMp4(data.subarray(28))[0]; } return result; }, moof: function(data) { return { boxes: inspectMp4(data) }; }, moov: function(data) { return { boxes: inspectMp4(data) }; }, mvex: function(data) { return { boxes: inspectMp4(data) }; }, mvhd: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), i = 4, result = { version: view.getUint8(0), flags: new Uint8Array(data.subarray(1, 4)) }; if (result.version === 1) { i += 4; result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes i += 8; result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes i += 4; result.timescale = view.getUint32(i); i += 8; result.duration = view.getUint32(i); // truncating top 4 bytes } else { result.creationTime = parseMp4Date(view.getUint32(i)); i += 4; result.modificationTime = parseMp4Date(view.getUint32(i)); i += 4; result.timescale = view.getUint32(i); i += 4; result.duration = view.getUint32(i); } i += 4; // convert fixed-point, base 16 back to a number result.rate = view.getUint16(i) + (view.getUint16(i + 2) / 16); i += 4; result.volume = view.getUint8(i) + (view.getUint8(i + 1) / 8); i += 2; i += 2; i += 2 * 4; result.matrix = new Uint32Array(data.subarray(i, i + (9 * 4))); i += 9 * 4; i += 6 * 4; result.nextTrackId = view.getUint32(i); return result; }, pdin: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength); return { version: view.getUint8(0), flags: new Uint8Array(data.subarray(1, 4)), rate: view.getUint32(4), initialDelay: view.getUint32(8) }; }, sdtp: function(data) { var result = { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), samples: [] }, i; for (i = 4; i < data.byteLength; i++) { result.samples.push({ dependsOn: (data[i] & 0x30) >> 4, isDependedOn: (data[i] & 0x0c) >> 2, hasRedundancy: data[i] & 0x03 }); } return result; }, sidx: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), result = { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), references: [], referenceId: view.getUint32(4), timescale: view.getUint32(8), earliestPresentationTime: view.getUint32(12), firstOffset: view.getUint32(16) }, referenceCount = view.getUint16(22), i; for (i = 24; referenceCount; i += 12, referenceCount-- ) { result.references.push({ referenceType: (data[i] & 0x80) >>> 7, referencedSize: view.getUint32(i) & 0x7FFFFFFF, subsegmentDuration: view.getUint32(i + 4), startsWithSap: !!(data[i + 8] & 0x80), sapType: (data[i + 8] & 0x70) >>> 4, sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF }); } return result; }, smhd: function(data) { return { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), balance: data[4] + (data[5] / 256) }; }, stbl: function(data) { return { boxes: inspectMp4(data) }; }, stco: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), result = { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), chunkOffsets: [] }, entryCount = view.getUint32(4), i; for (i = 8; entryCount; i += 4, entryCount--) { result.chunkOffsets.push(view.getUint32(i)); } return result; }, stsc: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), entryCount = view.getUint32(4), result = { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), sampleToChunks: [] }, i; for (i = 8; entryCount; i += 12, entryCount--) { result.sampleToChunks.push({ firstChunk: view.getUint32(i), samplesPerChunk: view.getUint32(i + 4), sampleDescriptionIndex: view.getUint32(i + 8) }); } return result; }, stsd: function(data) { return { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), sampleDescriptions: inspectMp4(data.subarray(8)) }; }, stsz: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), result = { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), sampleSize: view.getUint32(4), entries: [] }, i; for (i = 12; i < data.byteLength; i += 4) { result.entries.push(view.getUint32(i)); } return result; }, stts: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), result = { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), timeToSamples: [] }, entryCount = view.getUint32(4), i; for (i = 8; entryCount; i += 8, entryCount--) { result.timeToSamples.push({ sampleCount: view.getUint32(i), sampleDelta: view.getUint32(i + 4) }); } return result; }, styp: function(data) { return parse.ftyp(data); }, tfdt: function(data) { return { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), baseMediaDecodeTime: data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7] }; }, tfhd: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), result = { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), trackId: view.getUint32(4) }, baseDataOffsetPresent = result.flags[2] & 0x01, sampleDescriptionIndexPresent = result.flags[2] & 0x02, defaultSampleDurationPresent = result.flags[2] & 0x08, defaultSampleSizePresent = result.flags[2] & 0x10, defaultSampleFlagsPresent = result.flags[2] & 0x20, i; i = 8; if (baseDataOffsetPresent) { i += 4; // truncate top 4 bytes result.baseDataOffset = view.getUint32(12); i += 4; } if (sampleDescriptionIndexPresent) { result.sampleDescriptionIndex = view.getUint32(i); i += 4; } if (defaultSampleDurationPresent) { result.defaultSampleDuration = view.getUint32(i); i += 4; } if (defaultSampleSizePresent) { result.defaultSampleSize = view.getUint32(i); i += 4; } if (defaultSampleFlagsPresent) { result.defaultSampleFlags = view.getUint32(i); } return result; }, tkhd: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength), i = 4, result = { version: view.getUint8(0), flags: new Uint8Array(data.subarray(1, 4)), }; if (result.version === 1) { i += 4; result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes i += 8; result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes i += 4; result.trackId = view.getUint32(i); i += 4; i += 8; result.duration = view.getUint32(i); // truncating top 4 bytes } else { result.creationTime = parseMp4Date(view.getUint32(i)); i += 4; result.modificationTime = parseMp4Date(view.getUint32(i)); i += 4; result.trackId = view.getUint32(i); i += 4; i += 4; result.duration = view.getUint32(i); } i += 4; i += 2 * 4; result.layer = view.getUint16(i); i += 2; result.alternateGroup = view.getUint16(i); i += 2; // convert fixed-point, base 16 back to a number result.volume = view.getUint8(i) + (view.getUint8(i + 1) / 8); i += 2; i += 2; result.matrix = new Uint32Array(data.subarray(i, i + (9 * 4))); i += 9 * 4; result.width = view.getUint16(i) + (view.getUint16(i + 2) / 16); i += 4; result.height = view.getUint16(i) + (view.getUint16(i + 2) / 16); return result; }, traf: function(data) { return { boxes: inspectMp4(data) }; }, trak: function(data) { return { boxes: inspectMp4(data) }; }, trex: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength); return { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), trackId: view.getUint32(4), defaultSampleDescriptionIndex: view.getUint32(8), defaultSampleDuration: view.getUint32(12), defaultSampleSize: view.getUint32(16), sampleDependsOn: data[20] & 0x03, sampleIsDependedOn: (data[21] & 0xc0) >> 6, sampleHasRedundancy: (data[21] & 0x30) >> 4, samplePaddingValue: (data[21] & 0x0e) >> 1, sampleIsDifferenceSample: !!(data[21] & 0x01), sampleDegradationPriority: view.getUint16(22) }; }, trun: function(data) { var result = { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), samples: [] }, view = new DataView(data.buffer, data.byteOffset, data.byteLength), dataOffsetPresent = result.flags[2] & 0x01, firstSampleFlagsPresent = result.flags[2] & 0x04, sampleDurationPresent = result.flags[1] & 0x01, sampleSizePresent = result.flags[1] & 0x02, sampleFlagsPresent = result.flags[1] & 0x04, sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08, sampleCount = view.getUint32(4), offset = 8, sample; if (dataOffsetPresent) { result.dataOffset = view.getUint32(offset); offset += 4; } if (firstSampleFlagsPresent && sampleCount) { sample = { flags: parseSampleFlags(data.subarray(offset, offset + 4)) }; offset += 4; if (sampleDurationPresent) { sample.duration = view.getUint32(offset); offset += 4; } if (sampleSizePresent) { sample.size = view.getUint32(offset); offset += 4; } if (sampleCompositionTimeOffsetPresent) { sample.compositionTimeOffset = view.getUint32(offset); offset += 4; } result.samples.push(sample); sampleCount--; } while (sampleCount--) { sample = {}; if (sampleDurationPresent) { sample.duration = view.getUint32(offset); offset += 4; } if (sampleSizePresent) { sample.size = view.getUint32(offset); offset += 4; } if (sampleFlagsPresent) { sample.flags = parseSampleFlags(data.subarray(offset, offset + 4)); offset += 4; } if (sampleCompositionTimeOffsetPresent) { sample.compositionTimeOffset = view.getUint32(offset); offset += 4; } result.samples.push(sample); } return result; }, 'url ': function(data) { return { version: data[0], flags: new Uint8Array(data.subarray(1, 4)) }; }, vmhd: function(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength); return { version: data[0], flags: new Uint8Array(data.subarray(1, 4)), graphicsmode: view.getUint16(4), opcolor: new Uint16Array([view.getUint16(6), view.getUint16(8), view.getUint16(10)]) }; } }; /** * Return a javascript array of box objects parsed from an ISO base * media file. * @param data {Uint8Array} the binary data of the media to be inspected * @return {array} a javascript array of potentially nested box objects */ inspectMp4 = function(data) { var i = 0, result = [], view, size, type, end, box; // Convert data from Uint8Array to ArrayBuffer, to follow Dataview API var ab = new ArrayBuffer(data.length); var v = new Uint8Array(ab); for (var z = 0; z < data.length; ++z) { v[z] = data[z]; } view = new DataView(ab); while (i < data.byteLength) { // parse box data size = view.getUint32(i); type = parseType(data.subarray(i + 4, i + 8)); end = size > 1 ? i + size : data.byteLength; // parse type-specific data box = (parse[type] || function(data) { return { data: data }; })(data.subarray(i + 8, end)); box.size = size; box.type = type; // store this box and move to the next result.push(box); i = end; } return result; }; /** * Returns a textual representation of the javascript represtentation * of an MP4 file. You can use it as an alternative to * JSON.stringify() to compare inspected MP4s. * @param inspectedMp4 {array} the parsed array of boxes in an MP4 * file * @param depth {number} (optional) the number of ancestor boxes of * the elements of inspectedMp4. Assumed to be zero if unspecified. * @return {string} a text representation of the parsed MP4 */ textifyMp4 = function(inspectedMp4, depth) { var indent; depth = depth || 0; indent = new Array(depth * 2 + 1).join(' '); // iterate over all the boxes return inspectedMp4.map(function(box, index) { // list the box type first at the current indentation level return indent + box.type + '\n' + // the type is already included and handle child boxes separately Object.keys(box).filter(function(key) { return key !== 'type' && key !== 'boxes'; // output all the box properties }).map(function(key) { var prefix = indent + ' ' + key + ': ', value = box[key]; // print out raw bytes as hexademical if (value instanceof Uint8Array || value instanceof Uint32Array) { var bytes = Array.prototype.slice.call(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) .map(function(byte) { return ' ' + ('00' + byte.toString(16)).slice(-2); }).join('').match(/.{1,24}/g); if (!bytes) { return prefix + '<>'; } if (bytes.length === 1) { return prefix + '<' + bytes.join('').slice(1) + '>'; } return prefix + '<\n' + bytes.map(function(line) { return indent + ' ' + line; }).join('\n') + '\n' + indent + ' >'; } // stringify generic objects return prefix + JSON.stringify(value, null, 2) .split('\n').map(function(line, index) { if (index === 0) { return line; } return indent + ' ' + line; }).join('\n'); }).join('\n') + // recursively textify the child boxes (box.boxes ? '\n' + textifyMp4(box.boxes, depth + 1) : ''); }).join('\n'); }; module.exports = { inspect: inspectMp4, textify: textifyMp4 }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],19:[function(require,module,exports){ 'use strict'; var ExpGolomb; /** * Parser for exponential Golomb codes, a variable-bitwidth number encoding * scheme used by h264. */ ExpGolomb = function(workingData) { var // the number of bytes left to examine in workingData workingBytesAvailable = workingData.byteLength, // the current word being examined workingWord = 0, // :uint // the number of bits left to examine in the current word workingBitsAvailable = 0; // :uint; // ():uint this.length = function() { return (8 * workingBytesAvailable); }; // ():uint this.bitsAvailable = function() { return (8 * workingBytesAvailable) + workingBitsAvailable; }; // ():void this.loadWord = function() { var position = workingData.byteLength - workingBytesAvailable, workingBytes = new Uint8Array(4), availableBytes = Math.min(4, workingBytesAvailable); if (availableBytes === 0) { throw new Error('no bytes available'); } workingBytes.set(workingData.subarray(position, position + availableBytes)); workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed workingBitsAvailable = availableBytes * 8; workingBytesAvailable -= availableBytes; }; // (count:int):void this.skipBits = function(count) { var skipBytes; // :int if (workingBitsAvailable > count) { workingWord <<= count; workingBitsAvailable -= count; } else { count -= workingBitsAvailable; skipBytes = Math.floor(count / 8); count -= (skipBytes * 8); workingBytesAvailable -= skipBytes; this.loadWord(); workingWord <<= count; workingBitsAvailable -= count; } }; // (size:int):uint this.readBits = function(size) { var bits = Math.min(workingBitsAvailable, size), // :uint valu = workingWord >>> (32 - bits); // :uint // if size > 31, handle error workingBitsAvailable -= bits; if (workingBitsAvailable > 0) { workingWord <<= bits; } else if (workingBytesAvailable > 0) { this.loadWord(); } bits = size - bits; if (bits > 0) { return valu << bits | this.readBits(bits); } else { return valu; } }; // ():uint this.skipLeadingZeros = function() { var leadingZeroCount; // :uint for (leadingZeroCount = 0 ; leadingZeroCount < workingBitsAvailable ; ++leadingZeroCount) { if (0 !== (workingWord & (0x80000000 >>> leadingZeroCount))) { // the first bit of working word is 1 workingWord <<= leadingZeroCount; workingBitsAvailable -= leadingZeroCount; return leadingZeroCount; } } // we exhausted workingWord and still have not found a 1 this.loadWord(); return leadingZeroCount + this.skipLeadingZeros(); }; // ():void this.skipUnsignedExpGolomb = function() { this.skipBits(1 + this.skipLeadingZeros()); }; // ():void this.skipExpGolomb = function() { this.skipBits(1 + this.skipLeadingZeros()); }; // ():uint this.readUnsignedExpGolomb = function() { var clz = this.skipLeadingZeros(); // :uint return this.readBits(clz + 1) - 1; }; // ():int this.readExpGolomb = function() { var valu = this.readUnsignedExpGolomb(); // :int if (0x01 & valu) { // the number is odd if the low order bit is set return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2 } else { return -1 * (valu >>> 1); // divide by two then make it negative } }; // Some convenience functions // :Boolean this.readBoolean = function() { return 1 === this.readBits(1); }; // ():int this.readUnsignedByte = function() { return this.readBits(8); }; this.loadWord(); }; module.exports = ExpGolomb; },{}],20:[function(require,module,exports){ /** * mux.js * * Copyright (c) 2014 Brightcove * All rights reserved. * * A lightweight readable stream implemention that handles event dispatching. * Objects that inherit from streams should call init in their constructors. */ 'use strict'; var Stream = function() { this.init = function() { var listeners = {}; /** * Add a listener for a specified event type. * @param type {string} the event name * @param listener {function} the callback to be invoked when an event of * the specified type occurs */ this.on = function(type, listener) { if (!listeners[type]) { listeners[type] = []; } listeners[type].push(listener); }; /** * Remove a listener for a specified event type. * @param type {string} the event name * @param listener {function} a function previously registered for this * type of event through `on` */ this.off = function(type, listener) { var index; if (!listeners[type]) { return false; } index = listeners[type].indexOf(listener); listeners[type].splice(index, 1); return index > -1; }; /** * Trigger an event of the specified type on this stream. Any additional * arguments to this function are passed as parameters to event listeners. * @param type {string} the event name */ this.trigger = function(type) { var callbacks, i, length, args; callbacks = listeners[type]; if (!callbacks) { return; } // Slicing the arguments on every invocation of this method // can add a significant amount of overhead. Avoid the // intermediate object creation for the common case of a // single callback argument if (arguments.length === 2) { length = callbacks.length; for (i = 0; i < length; ++i) { callbacks[i].call(this, arguments[1]); } } else { args = []; i = arguments.length; for (i = 1; i < arguments.length; ++i) { args.push(arguments[i]); } length = callbacks.length; for (i = 0; i < length; ++i) { callbacks[i].apply(this, args); } } }; /** * Destroys the stream and cleans up. */ this.dispose = function() { listeners = {}; }; }; }; /** * Forwards all `data` events on this stream to the destination stream. The * destination stream should provide a method `push` to receive the data * events as they arrive. * @param destination {stream} the stream that will receive all `data` events * @param autoFlush {boolean} if false, we will not call `flush` on the destination * when the current stream emits a 'done' event * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options */ Stream.prototype.pipe = function(destination) { this.on('data', function(data) { destination.push(data); }); this.on('done', function(flushSource) { destination.flush(flushSource); }); return destination; }; // Default stream functions that are expected to be overridden to perform // actual work. These are provided by the prototype as a sort of no-op // implementation so that we don't have to check for their existence in the // `pipe` function above. Stream.prototype.push = function(data) { this.trigger('data', data); }; Stream.prototype.flush = function(flushSource) { this.trigger('done', flushSource); }; module.exports = Stream; },{}],21:[function(require,module,exports){ (function (global){ /** * @file add-text-track-data.js */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null); var _videoJs2 = _interopRequireDefault(_videoJs); /** * Define properties on a cue for backwards compatability, * but warn the user that the way that they are using it * is depricated and will be removed at a later date. * * @param {Cue} cue the cue to add the properties on * @private */ var deprecateOldCue = function deprecateOldCue(cue) { Object.defineProperties(cue.frame, { id: { get: function get() { _videoJs2['default'].log.warn('cue.frame.id is deprecated. Use cue.value.key instead.'); return cue.value.key; } }, value: { get: function get() { _videoJs2['default'].log.warn('cue.frame.value is deprecated. Use cue.value.data instead.'); return cue.value.data; } }, privateData: { get: function get() { _videoJs2['default'].log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.'); return cue.value.data; } } }); }; /** * Add text track data to a source handler given the captions and * metadata from the buffer. * * @param {Object} sourceHandler the flash or virtual source buffer * @param {Array} captionArray an array of caption data * @param {Array} cue an array of meta data * @private */ var addTextTrackData = function addTextTrackData(sourceHandler, captionArray, metadataArray) { var Cue = window.WebKitDataCue || window.VTTCue; if (captionArray) { captionArray.forEach(function (caption) { this.inbandTextTrack_.addCue(new Cue(caption.startTime + this.timestampOffset, caption.endTime + this.timestampOffset, caption.text)); }, sourceHandler); } if (metadataArray) { metadataArray.forEach(function (metadata) { var time = metadata.cueTime + this.timestampOffset; metadata.frames.forEach(function (frame) { var cue = new Cue(time, time, frame.value || frame.url || frame.data || ''); cue.frame = frame; cue.value = frame; deprecateOldCue(cue); this.metadataTrack_.addCue(cue); }, this); }, sourceHandler); } }; exports['default'] = addTextTrackData; module.exports = exports['default']; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],22:[function(require,module,exports){ /** * @file codec-utils.js */ /** * Check if a codec string refers to an audio codec. * * @param {String} codec codec string to check * @return {Boolean} if this is an audio codec * @private */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var isAudioCodec = function isAudioCodec(codec) { return (/mp4a\.\d+.\d+/i.test(codec) ); }; /** * Check if a codec string refers to a video codec. * * @param {String} codec codec string to check * @return {Boolean} if this is a video codec * @private */ var isVideoCodec = function isVideoCodec(codec) { return (/avc1\.[\da-f]+/i.test(codec) ); }; /** * Parse a content type header into a type and parameters * object * * @param {String} type the content type header * @return {Object} the parsed content-type * @private */ var parseContentType = function parseContentType(type) { var object = { type: '', parameters: {} }; var parameters = type.trim().split(';'); // first parameter should always be content-type object.type = parameters.shift().trim(); parameters.forEach(function (parameter) { var pair = parameter.trim().split('='); if (pair.length > 1) { var _name = pair[0].replace(/"/g, '').trim(); var value = pair[1].replace(/"/g, '').trim(); object.parameters[_name] = value; } }); return object; }; exports['default'] = { isAudioCodec: isAudioCodec, parseContentType: parseContentType, isVideoCodec: isVideoCodec }; module.exports = exports['default']; },{}],23:[function(require,module,exports){ /** * @file create-text-tracks-if-necessary.js */ /** * Create text tracks on video.js if they exist on a segment. * * @param {Object} sourceBuffer the VSB or FSB * @param {Object} mediaSource the HTML or Flash media source * @param {Object} segment the segment that may contain the text track * @private */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var createTextTracksIfNecessary = function createTextTracksIfNecessary(sourceBuffer, mediaSource, segment) { // create an in-band caption track if one is present in the segment if (segment.captions && segment.captions.length && !sourceBuffer.inbandTextTrack_) { sourceBuffer.inbandTextTrack_ = mediaSource.player_.addTextTrack('captions', 'cc1'); } if (segment.metadata && segment.metadata.length && !sourceBuffer.metadataTrack_) { sourceBuffer.metadataTrack_ = mediaSource.player_.addTextTrack('metadata', 'Timed Metadata'); sourceBuffer.metadataTrack_.inBandMetadataTrackDispatchType = segment.metadata.dispatchType; } }; exports['default'] = createTextTracksIfNecessary; module.exports = exports['default']; },{}],24:[function(require,module,exports){ /** * @file flash-constants.js */ /** * The maximum size in bytes for append operations to the video.js * SWF. Calling through to Flash blocks and can be expensive so * tuning this parameter may improve playback on slower * systems. There are two factors to consider: * - Each interaction with the SWF must be quick or you risk dropping * video frames. To maintain 60fps for the rest of the page, each append * must not take longer than 16ms. Given the likelihood that the page * will be executing more javascript than just playback, you probably * want to aim for less than 8ms. We aim for just 4ms. * - Bigger appends significantly increase throughput. The total number of * bytes over time delivered to the SWF must exceed the video bitrate or * playback will stall. * * We adaptively tune the size of appends to give the best throughput * possible given the performance of the system. To do that we try to append * as much as possible in TIME_PER_TICK and while tuning the size of appends * dynamically so that we only append about 4-times in that 4ms span. * * The reason we try to keep the number of appends around four is due to * externalities such as Flash load and garbage collection that are highly * variable and having 4 iterations allows us to exit the loop early if * an iteration takes longer than expected. * * @private */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var flashConstants = { TIME_BETWEEN_TICKS: Math.floor(1000 / 480), TIME_PER_TICK: Math.floor(1000 / 240), // 1kb BYTES_PER_CHUNK: 1 * 1024, MIN_CHUNK: 1024, MAX_CHUNK: 1024 * 1024 }; exports["default"] = flashConstants; module.exports = exports["default"]; },{}],25:[function(require,module,exports){ (function (global){ /** * @file flash-media-source.js */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null); var _videoJs2 = _interopRequireDefault(_videoJs); var _flashSourceBuffer = require('./flash-source-buffer'); var _flashSourceBuffer2 = _interopRequireDefault(_flashSourceBuffer); var _flashConstants = require('./flash-constants'); var _flashConstants2 = _interopRequireDefault(_flashConstants); var _codecUtils = require('./codec-utils'); /** * A flash implmentation of HTML MediaSources and a polyfill * for browsers that don't support native or HTML MediaSources.. * * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource * @class FlashMediaSource * @extends videojs.EventTarget */ var FlashMediaSource = (function (_videojs$EventTarget) { _inherits(FlashMediaSource, _videojs$EventTarget); function FlashMediaSource() { var _this = this; _classCallCheck(this, FlashMediaSource); _get(Object.getPrototypeOf(FlashMediaSource.prototype), 'constructor', this).call(this); this.sourceBuffers = []; this.readyState = 'closed'; this.on(['sourceopen', 'webkitsourceopen'], function (event) { // find the swf where we will push media data _this.swfObj = document.getElementById(event.swfId); _this.player_ = (0, _videoJs2['default'])(_this.swfObj.parentNode); _this.tech_ = _this.swfObj.tech; _this.readyState = 'open'; _this.tech_.on('seeking', function () { var i = _this.sourceBuffers.length; while (i--) { _this.sourceBuffers[i].abort(); } }); // trigger load events if (_this.swfObj) { _this.swfObj.vjs_load(); } }); } /** * Set or return the presentation duration. * * @param {Double} value the duration of the media in seconds * @param {Double} the current presentation duration * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration */ /** * We have this function so that the html and flash interfaces * are the same. * * @private */ _createClass(FlashMediaSource, [{ key: 'addSeekableRange_', value: function addSeekableRange_() {} // intentional no-op /** * Create a new flash source buffer and add it to our flash media source. * * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/addSourceBuffer * @param {String} type the content-type of the source * @return {Object} the flash source buffer */ }, { key: 'addSourceBuffer', value: function addSourceBuffer(type) { var parsedType = (0, _codecUtils.parseContentType)(type); var sourceBuffer = undefined; // if this is an FLV type, we'll push data to flash if (parsedType.type === 'video/mp2t') { // Flash source buffers sourceBuffer = new _flashSourceBuffer2['default'](this); } else { throw new Error('NotSupportedError (Video.js)'); } this.sourceBuffers.push(sourceBuffer); return sourceBuffer; } /** * Signals the end of the stream. * * @link https://w3c.github.io/media-source/#widl-MediaSource-endOfStream-void-EndOfStreamError-error * @param {String=} error Signals that a playback error * has occurred. If specified, it must be either "network" or * "decode". */ }, { key: 'endOfStream', value: function endOfStream(error) { if (error === 'network') { // MEDIA_ERR_NETWORK this.tech_.error(2); } else if (error === 'decode') { // MEDIA_ERR_DECODE this.tech_.error(3); } if (this.readyState !== 'ended') { this.readyState = 'ended'; this.swfObj.vjs_endOfStream(); } } }]); return FlashMediaSource; })(_videoJs2['default'].EventTarget); exports['default'] = FlashMediaSource; try { Object.defineProperty(FlashMediaSource.prototype, 'duration', { /** * Return the presentation duration. * * @return {Double} the duration of the media in seconds * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration */ get: function get() { if (!this.swfObj) { return NaN; } // get the current duration from the SWF return this.swfObj.vjs_getProperty('duration'); }, /** * Set the presentation duration. * * @param {Double} value the duration of the media in seconds * @return {Double} the duration of the media in seconds * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration */ set: function set(value) { var i = undefined; var oldDuration = this.swfObj.vjs_getProperty('duration'); this.swfObj.vjs_setProperty('duration', value); if (value < oldDuration) { // In MSE, this triggers the range removal algorithm which causes // an update to occur for (i = 0; i < this.sourceBuffers.length; i++) { this.sourceBuffers[i].remove(value, oldDuration); } } return value; } }); } catch (e) { // IE8 throws if defineProperty is called on a non-DOM node. We // don't support IE8 but we shouldn't throw an error if loaded // there. FlashMediaSource.prototype.duration = NaN; } for (var property in _flashConstants2['default']) { FlashMediaSource[property] = _flashConstants2['default'][property]; } module.exports = exports['default']; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./codec-utils":22,"./flash-constants":24,"./flash-source-buffer":26}],26:[function(require,module,exports){ (function (global){ /** * @file flash-source-buffer.js */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null); var _videoJs2 = _interopRequireDefault(_videoJs); var _muxJs = require('mux.js'); var _muxJs2 = _interopRequireDefault(_muxJs); var _removeCuesFromTrack = require('./remove-cues-from-track'); var _removeCuesFromTrack2 = _interopRequireDefault(_removeCuesFromTrack); var _createTextTracksIfNecessary = require('./create-text-tracks-if-necessary'); var _createTextTracksIfNecessary2 = _interopRequireDefault(_createTextTracksIfNecessary); var _addTextTrackData = require('./add-text-track-data'); var _addTextTrackData2 = _interopRequireDefault(_addTextTrackData); var _flashConstants = require('./flash-constants'); var _flashConstants2 = _interopRequireDefault(_flashConstants); /** * A wrapper around the setTimeout function that uses * the flash constant time between ticks value. * * @param {Function} func the function callback to run * @private */ var scheduleTick = function scheduleTick(func) { // Chrome doesn't invoke requestAnimationFrame callbacks // in background tabs, so use setTimeout. window.setTimeout(func, _flashConstants2['default'].TIME_BETWEEN_TICKS); }; /** * Round a number to a specified number of places much like * toFixed but return a number instead of a string representation. * * @param {Number} num A number * @param {Number} places The number of decimal places which to * round * @private */ var toDecimalPlaces = function toDecimalPlaces(num, places) { if (typeof places !== 'number' || places < 0) { places = 0; } var scale = Math.pow(10, places); return Math.round(num * scale) / scale; }; /** * A SourceBuffer implementation for Flash rather than HTML. * * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource * @param {Object} mediaSource the flash media source * @class FlashSourceBuffer * @extends videojs.EventTarget */ var FlashSourceBuffer = (function (_videojs$EventTarget) { _inherits(FlashSourceBuffer, _videojs$EventTarget); function FlashSourceBuffer(mediaSource) { var _this = this; _classCallCheck(this, FlashSourceBuffer); _get(Object.getPrototypeOf(FlashSourceBuffer.prototype), 'constructor', this).call(this); var encodedHeader = undefined; // Start off using the globally defined value but refine // as we append data into flash this.chunkSize_ = _flashConstants2['default'].BYTES_PER_CHUNK; // byte arrays queued to be appended this.buffer_ = []; // the total number of queued bytes this.bufferSize_ = 0; // to be able to determine the correct position to seek to, we // need to retain information about the mapping between the // media timeline and PTS values this.basePtsOffset_ = NaN; this.mediaSource = mediaSource; // indicates whether the asynchronous continuation of an operation // is still being processed // see https://w3c.github.io/media-source/#widl-SourceBuffer-updating this.updating = false; this.timestampOffset_ = 0; // TS to FLV transmuxer this.segmentParser_ = new _muxJs2['default'].flv.Transmuxer(); this.segmentParser_.on('data', this.receiveBuffer_.bind(this)); encodedHeader = window.btoa(String.fromCharCode.apply(null, Array.prototype.slice.call(this.segmentParser_.getFlvHeader()))); this.mediaSource.swfObj.vjs_appendBuffer(encodedHeader); Object.defineProperty(this, 'timestampOffset', { get: function get() { return this.timestampOffset_; }, set: function set(val) { if (typeof val === 'number' && val >= 0) { this.timestampOffset_ = val; this.segmentParser_ = new _muxJs2['default'].flv.Transmuxer(); this.segmentParser_.on('data', this.receiveBuffer_.bind(this)); // We have to tell flash to expect a discontinuity this.mediaSource.swfObj.vjs_discontinuity(); // the media <-> PTS mapping must be re-established after // the discontinuity this.basePtsOffset_ = NaN; } } }); Object.defineProperty(this, 'buffered', { get: function get() { if (!this.mediaSource || !this.mediaSource.swfObj || !('vjs_getProperty' in this.mediaSource.swfObj)) { return _videoJs2['default'].createTimeRange(); } var buffered = this.mediaSource.swfObj.vjs_getProperty('buffered'); if (buffered && buffered.length) { buffered[0][0] = toDecimalPlaces(buffered[0][0], 3); buffered[0][1] = toDecimalPlaces(buffered[0][1], 3); } return _videoJs2['default'].createTimeRanges(buffered); } }); // On a seek we remove all text track data since flash has no concept // of a buffered-range and everything else is reset on seek this.mediaSource.player_.on('seeked', function () { (0, _removeCuesFromTrack2['default'])(0, Infinity, _this.metadataTrack_); (0, _removeCuesFromTrack2['default'])(0, Infinity, _this.inbandTextTrack_); }); } /** * Append bytes to the sourcebuffers buffer, in this case we * have to append it to swf object. * * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/appendBuffer * @param {Array} bytes */ _createClass(FlashSourceBuffer, [{ key: 'appendBuffer', value: function appendBuffer(bytes) { var _this2 = this; var error = undefined; var chunk = 512 * 1024; var i = 0; if (this.updating) { error = new Error('SourceBuffer.append() cannot be called ' + 'while an update is in progress'); error.name = 'InvalidStateError'; error.code = 11; throw error; } this.updating = true; this.mediaSource.readyState = 'open'; this.trigger({ type: 'update' }); // this is here to use recursion var chunkInData = function chunkInData() { _this2.segmentParser_.push(bytes.subarray(i, i + chunk)); i += chunk; if (i < bytes.byteLength) { scheduleTick(chunkInData); } else { scheduleTick(_this2.segmentParser_.flush.bind(_this2.segmentParser_)); } }; chunkInData(); } /** * Reset the parser and remove any data queued to be sent to the SWF. * * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/abort */ }, { key: 'abort', value: function abort() { this.buffer_ = []; this.bufferSize_ = 0; this.mediaSource.swfObj.vjs_abort(); // report any outstanding updates have ended if (this.updating) { this.updating = false; this.trigger({ type: 'updateend' }); } } /** * Flash cannot remove ranges already buffered in the NetStream * but seeking clears the buffer entirely. For most purposes, * having this operation act as a no-op is acceptable. * * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/remove * @param {Double} start start of the section to remove * @param {Double} end end of the section to remove */ }, { key: 'remove', value: function remove(start, end) { (0, _removeCuesFromTrack2['default'])(start, end, this.metadataTrack_); (0, _removeCuesFromTrack2['default'])(start, end, this.inbandTextTrack_); this.trigger({ type: 'update' }); this.trigger({ type: 'updateend' }); } /** * Receive a buffer from the flv. * * @param {Object} segment * @private */ }, { key: 'receiveBuffer_', value: function receiveBuffer_(segment) { var _this3 = this; // create an in-band caption track if one is present in the segment (0, _createTextTracksIfNecessary2['default'])(this, this.mediaSource, segment); (0, _addTextTrackData2['default'])(this, segment.captions, segment.metadata); // Do this asynchronously since convertTagsToData_ can be time consuming scheduleTick(function () { var flvBytes = _this3.convertTagsToData_(segment); if (_this3.buffer_.length === 0) { scheduleTick(_this3.processBuffer_.bind(_this3)); } if (flvBytes) { _this3.buffer_.push(flvBytes); _this3.bufferSize_ += flvBytes.byteLength; } }); } /** * Append a portion of the current buffer to the SWF. * * @private */ }, { key: 'processBuffer_', value: function processBuffer_() { var chunk = undefined; var i = undefined; var length = undefined; var binary = undefined; var b64str = undefined; var startByte = 0; var appendIterations = 0; var startTime = +new Date(); var appendTime = undefined; if (!this.buffer_.length) { if (this.updating !== false) { this.updating = false; this.trigger({ type: 'updateend' }); } // do nothing if the buffer is empty return; } do { appendIterations++; // concatenate appends up to the max append size chunk = this.buffer_[0].subarray(startByte, startByte + this.chunkSize_); // requeue any bytes that won't make it this round if (chunk.byteLength < this.chunkSize_ || this.buffer_[0].byteLength === startByte + this.chunkSize_) { startByte = 0; this.buffer_.shift(); } else { startByte += this.chunkSize_; } this.bufferSize_ -= chunk.byteLength; // base64 encode the bytes binary = ''; length = chunk.byteLength; for (i = 0; i < length; i++) { binary += String.fromCharCode(chunk[i]); } b64str = window.btoa(binary); // bypass normal ExternalInterface calls and pass xml directly // IE can be slow by default this.mediaSource.swfObj.CallFunction('<invoke name="vjs_appendBuffer"' + 'returntype="javascript"><arguments><string>' + b64str + '</string></arguments></invoke>'); appendTime = new Date() - startTime; } while (this.buffer_.length && appendTime < _flashConstants2['default'].TIME_PER_TICK); if (this.buffer_.length && startByte) { this.buffer_[0] = this.buffer_[0].subarray(startByte); } if (appendTime >= _flashConstants2['default'].TIME_PER_TICK) { // We want to target 4 iterations per time-slot so that gives us // room to adjust to changes in Flash load and other externalities // such as garbage collection while still maximizing throughput this.chunkSize_ = Math.floor(this.chunkSize_ * (appendIterations / 4)); } // We also make sure that the chunk-size doesn't drop below 1KB or // go above 1MB as a sanity check this.chunkSize_ = Math.max(_flashConstants2['default'].MIN_CHUNK, Math.min(this.chunkSize_, _flashConstants2['default'].MAX_CHUNK)); // schedule another append if necessary if (this.bufferSize_ !== 0) { scheduleTick(this.processBuffer_.bind(this)); } else { this.updating = false; this.trigger({ type: 'updateend' }); } } /** * Turns an array of flv tags into a Uint8Array representing the * flv data. Also removes any tags that are before the current * time so that playback begins at or slightly after the right * place on a seek * * @private * @param {Object} segmentData object of segment data */ }, { key: 'convertTagsToData_', value: function convertTagsToData_(segmentData) { var segmentByteLength = 0; var tech = this.mediaSource.tech_; var targetPts = 0; var i = undefined; var j = undefined; var segment = undefined; var filteredTags = []; var tags = this.getOrderedTags_(segmentData); // Establish the media timeline to PTS translation if we don't // have one already if (isNaN(this.basePtsOffset_) && tags.length) { this.basePtsOffset_ = tags[0].pts; } // Trim any tags that are before the end of the end of // the current buffer if (tech.buffered().length) { targetPts = tech.buffered().end(0) - this.timestampOffset; } // Trim to currentTime if it's ahead of buffered or buffered doesn't exist targetPts = Math.max(targetPts, tech.currentTime() - this.timestampOffset); // PTS values are represented in milliseconds targetPts *= 1e3; targetPts += this.basePtsOffset_; // skip tags with a presentation time less than the seek target for (i = 0; i < tags.length; i++) { if (tags[i].pts >= targetPts) { filteredTags.push(tags[i]); } } if (filteredTags.length === 0) { return; } // concatenate the bytes into a single segment for (i = 0; i < filteredTags.length; i++) { segmentByteLength += filteredTags[i].bytes.byteLength; } segment = new Uint8Array(segmentByteLength); for (i = 0, j = 0; i < filteredTags.length; i++) { segment.set(filteredTags[i].bytes, j); j += filteredTags[i].bytes.byteLength; } return segment; } /** * Assemble the FLV tags in decoder order. * * @private * @param {Object} segmentData object of segment data */ }, { key: 'getOrderedTags_', value: function getOrderedTags_(segmentData) { var videoTags = segmentData.tags.videoTags; var audioTags = segmentData.tags.audioTags; var tag = undefined; var tags = []; while (videoTags.length || audioTags.length) { if (!videoTags.length) { // only audio tags remain tag = audioTags.shift(); } else if (!audioTags.length) { // only video tags remain tag = videoTags.shift(); } else if (audioTags[0].dts < videoTags[0].dts) { // audio should be decoded next tag = audioTags.shift(); } else { // video should be decoded next tag = videoTags.shift(); } tags.push(tag.finalize()); } return tags; } }]); return FlashSourceBuffer; })(_videoJs2['default'].EventTarget); exports['default'] = FlashSourceBuffer; module.exports = exports['default']; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./add-text-track-data":21,"./create-text-tracks-if-necessary":23,"./flash-constants":24,"./remove-cues-from-track":28,"mux.js":8}],27:[function(require,module,exports){ (function (global){ /** * @file html-media-source.js */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null); var _videoJs2 = _interopRequireDefault(_videoJs); var _virtualSourceBuffer = require('./virtual-source-buffer'); var _virtualSourceBuffer2 = _interopRequireDefault(_virtualSourceBuffer); var _codecUtils = require('./codec-utils'); /** * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard * `avc1.<hhhhhh>` * * @param {Array} codecs an array of codec strings to fix * @return {Array} the translated codec array * @private */ var translateLegacyCodecs = function translateLegacyCodecs(codecs) { return codecs.map(function (codec) { return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) { var profileHex = ('00' + Number(profile).toString(16)).slice(-2); var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2); return 'avc1.' + profileHex + '00' + avcLevelHex; }); }); }; /** * Our MediaSource implementation in HTML, mimics native * MediaSource where/if possible. * * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource * @class HtmlMediaSource * @extends videojs.EventTarget */ var HtmlMediaSource = (function (_videojs$EventTarget) { _inherits(HtmlMediaSource, _videojs$EventTarget); function HtmlMediaSource() { var _this = this; _classCallCheck(this, HtmlMediaSource); _get(Object.getPrototypeOf(HtmlMediaSource.prototype), 'constructor', this).call(this); var property = undefined; this.nativeMediaSource_ = new window.MediaSource(); // delegate to the native MediaSource's methods by default for (property in this.nativeMediaSource_) { if (!(property in HtmlMediaSource.prototype) && typeof this.nativeMediaSource_[property] === 'function') { this[property] = this.nativeMediaSource_[property].bind(this.nativeMediaSource_); } } // emulate `duration` and `seekable` until seeking can be // handled uniformly for live streams // see https://github.com/w3c/media-source/issues/5 this.duration_ = NaN; Object.defineProperty(this, 'duration', { get: function get() { if (this.duration_ === Infinity) { return this.duration_; } return this.nativeMediaSource_.duration; }, set: function set(duration) { this.duration_ = duration; if (duration !== Infinity) { this.nativeMediaSource_.duration = duration; return; } } }); Object.defineProperty(this, 'seekable', { get: function get() { if (this.duration_ === Infinity) { return _videoJs2['default'].createTimeRanges([[0, this.nativeMediaSource_.duration]]); } return this.nativeMediaSource_.seekable; } }); Object.defineProperty(this, 'readyState', { get: function get() { return this.nativeMediaSource_.readyState; } }); Object.defineProperty(this, 'activeSourceBuffers', { get: function get() { return this.activeSourceBuffers_; } }); // the list of virtual and native SourceBuffers created by this // MediaSource this.sourceBuffers = []; this.activeSourceBuffers_ = []; /** * update the list of active source buffers based upon various * imformation from HLS and video.js * * @private */ this.updateActiveSourceBuffers_ = function () { // Retain the reference but empty the array _this.activeSourceBuffers_.length = 0; // By default, the audio in the combined virtual source buffer is enabled // and the audio-only source buffer (if it exists) is disabled. var combined = false; var audioOnly = true; // TODO: maybe we can store the sourcebuffers on the track objects? // safari may do something like this for (var i = 0; i < _this.player_.audioTracks().length; i++) { var track = _this.player_.audioTracks()[i]; if (track.enabled && track.kind !== 'main') { // The enabled track is an alternate audio track so disable the audio in // the combined source buffer and enable the audio-only source buffer. combined = true; audioOnly = false; break; } } // Since we currently support a max of two source buffers, add all of the source // buffers (in order). _this.sourceBuffers.forEach(function (sourceBuffer) { /* eslinst-disable */ // TODO once codecs are required, we can switch to using the codecs to determine // what stream is the video stream, rather than relying on videoTracks /* eslinst-enable */ if (sourceBuffer.videoCodec_ && sourceBuffer.audioCodec_) { // combined sourceBuffer.audioDisabled_ = combined; } else if (sourceBuffer.videoCodec_ && !sourceBuffer.audioCodec_) { // If the "combined" source buffer is video only, then we do not want // disable the audio-only source buffer (this is mostly for demuxed // audio and video hls) sourceBuffer.audioDisabled_ = true; audioOnly = false; } else if (!sourceBuffer.videoCodec_ && sourceBuffer.audioCodec_) { // audio only sourceBuffer.audioDisabled_ = audioOnly; if (audioOnly) { return; } } _this.activeSourceBuffers_.push(sourceBuffer); }); }; // Re-emit MediaSource events on the polyfill ['sourceopen', 'sourceclose', 'sourceended'].forEach(function (eventName) { this.nativeMediaSource_.addEventListener(eventName, this.trigger.bind(this)); }, this); // capture the associated player when the MediaSource is // successfully attached this.on('sourceopen', function (event) { // Get the player this MediaSource is attached to var video = document.querySelector('[src="' + _this.url_ + '"]'); if (!video) { return; } _this.player_ = (0, _videoJs2['default'])(video.parentNode); _this.player_.audioTracks().on('change', _this.updateActiveSourceBuffers_); _this.player_.audioTracks().on('addtrack', _this.updateActiveSourceBuffers_); _this.player_.audioTracks().on('removetrack', _this.updateActiveSourceBuffers_); }); // explicitly terminate any WebWorkers that were created // by SourceHandlers this.on('sourceclose', function (event) { this.sourceBuffers.forEach(function (sourceBuffer) { if (sourceBuffer.transmuxer_) { sourceBuffer.transmuxer_.terminate(); } }); this.sourceBuffers.length = 0; if (!this.player_) { return; } this.player_.audioTracks().off('change', this.updateActiveSourceBuffers_); this.player_.audioTracks().off('addtrack', this.updateActiveSourceBuffers_); this.player_.audioTracks().off('removetrack', this.updateActiveSourceBuffers_); }); } /** * Add a range that that can now be seeked to. * * @param {Double} start where to start the addition * @param {Double} end where to end the addition * @private */ _createClass(HtmlMediaSource, [{ key: 'addSeekableRange_', value: function addSeekableRange_(start, end) { var error = undefined; if (this.duration !== Infinity) { error = new Error('MediaSource.addSeekableRange() can only be invoked ' + 'when the duration is Infinity'); error.name = 'InvalidStateError'; error.code = 11; throw error; } if (end > this.nativeMediaSource_.duration || isNaN(this.nativeMediaSource_.duration)) { this.nativeMediaSource_.duration = end; } } /** * Add a source buffer to the media source. * * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/addSourceBuffer * @param {String} type the content-type of the content * @return {Object} the created source buffer */ }, { key: 'addSourceBuffer', value: function addSourceBuffer(type) { var buffer = undefined; var parsedType = (0, _codecUtils.parseContentType)(type); // Create a VirtualSourceBuffer to transmux MPEG-2 transport // stream segments into fragmented MP4s if (parsedType.type === 'video/mp2t') { var codecs = []; if (parsedType.parameters && parsedType.parameters.codecs) { codecs = parsedType.parameters.codecs.split(','); codecs = translateLegacyCodecs(codecs); codecs = codecs.filter(function (codec) { return (0, _codecUtils.isAudioCodec)(codec) || (0, _codecUtils.isVideoCodec)(codec); }); } if (codecs.length === 0) { codecs = ['avc1.4d400d', 'mp4a.40.2']; } buffer = new _virtualSourceBuffer2['default'](this, codecs); if (this.sourceBuffers.length !== 0) { // If another VirtualSourceBuffer already exists, then we are creating a // SourceBuffer for an alternate audio track and therefore we know that // the source has both an audio and video track. // That means we should trigger the manual creation of the real // SourceBuffers instead of waiting for the transmuxer to return data this.sourceBuffers[0].createRealSourceBuffers_(); buffer.createRealSourceBuffers_(); // Automatically disable the audio on the first source buffer if // a second source buffer is ever created this.sourceBuffers[0].audioDisabled_ = true; } } else { // delegate to the native implementation buffer = this.nativeMediaSource_.addSourceBuffer(type); } this.sourceBuffers.push(buffer); return buffer; } }]); return HtmlMediaSource; })(_videoJs2['default'].EventTarget); exports['default'] = HtmlMediaSource; module.exports = exports['default']; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./codec-utils":22,"./virtual-source-buffer":30}],28:[function(require,module,exports){ /** * @file remove-cues-from-track.js */ /** * Remove cues from a track on video.js. * * @param {Double} start start of where we should remove the cue * @param {Double} end end of where the we should remove the cue * @param {Object} track the text track to remove the cues from * @private */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var removeCuesFromTrack = function removeCuesFromTrack(start, end, track) { var i = undefined; var cue = undefined; if (!track) { return; } i = track.cues.length; while (i--) { cue = track.cues[i]; // Remove any overlapping cue if (cue.startTime <= end && cue.endTime >= start) { track.removeCue(cue); } } }; exports["default"] = removeCuesFromTrack; module.exports = exports["default"]; },{}],29:[function(require,module,exports){ /** * @file transmuxer-worker.js */ /** * videojs-contrib-media-sources * * Copyright (c) 2015 Brightcove * All rights reserved. * * Handles communication between the browser-world and the mux.js * transmuxer running inside of a WebWorker by exposing a simple * message-based interface to a Transmuxer object. */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _muxJs = require('mux.js'); var _muxJs2 = _interopRequireDefault(_muxJs); /** * Re-emits tranmsuxer events by converting them into messages to the * world outside the worker. * * @param {Object} transmuxer the transmuxer to wire events on * @private */ var wireTransmuxerEvents = function wireTransmuxerEvents(transmuxer) { transmuxer.on('data', function (segment) { // transfer ownership of the underlying ArrayBuffer // instead of doing a copy to save memory // ArrayBuffers are transferable but generic TypedArrays are not // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects) var typedArray = segment.data; segment.data = typedArray.buffer; postMessage({ action: 'data', segment: segment, byteOffset: typedArray.byteOffset, byteLength: typedArray.byteLength }, [segment.data]); }); if (transmuxer.captionStream) { transmuxer.captionStream.on('data', function (caption) { postMessage({ action: 'caption', data: caption }); }); } transmuxer.on('done', function (data) { postMessage({ action: 'done' }); }); }; /** * All incoming messages route through this hash. If no function exists * to handle an incoming message, then we ignore the message. * * @class MessageHandlers * @param {Object} options the options to initialize with */ var MessageHandlers = (function () { function MessageHandlers(options) { _classCallCheck(this, MessageHandlers); this.options = options || {}; this.init(); } /** * Our web wroker interface so that things can talk to mux.js * that will be running in a web worker. the scope is passed to this by * webworkify. * * @param {Object} self the scope for the web worker */ /** * initialize our web worker and wire all the events. */ _createClass(MessageHandlers, [{ key: 'init', value: function init() { if (this.transmuxer) { this.transmuxer.dispose(); } this.transmuxer = new _muxJs2['default'].mp4.Transmuxer(this.options); wireTransmuxerEvents(this.transmuxer); } /** * Adds data (a ts segment) to the start of the transmuxer pipeline for * processing. * * @param {ArrayBuffer} data data to push into the muxer */ }, { key: 'push', value: function push(data) { // Cast array buffer to correct type for transmuxer var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength); this.transmuxer.push(segment); } /** * Recreate the transmuxer so that the next segment added via `push` * start with a fresh transmuxer. */ }, { key: 'reset', value: function reset() { this.init(); } /** * Set the value that will be used as the `baseMediaDecodeTime` time for the * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime` * set relative to the first based on the PTS values. * * @param {Object} data used to set the timestamp offset in the muxer */ }, { key: 'setTimestampOffset', value: function setTimestampOffset(data) { var timestampOffset = data.timestampOffset || 0; this.transmuxer.setBaseMediaDecodeTime(Math.round(timestampOffset * 90000)); } /** * Forces the pipeline to finish processing the last segment and emit it's * results. * * @param {Object} data event data, not really used */ }, { key: 'flush', value: function flush(data) { this.transmuxer.flush(); } }]); return MessageHandlers; })(); var Worker = function Worker(self) { self.onmessage = function (event) { if (event.data.action === 'init' && event.data.options) { this.messageHandlers = new MessageHandlers(event.data.options); return; } if (!this.messageHandlers) { this.messageHandlers = new MessageHandlers(); } if (event.data && event.data.action && event.data.action !== 'init') { if (this.messageHandlers[event.data.action]) { this.messageHandlers[event.data.action](event.data); } } }; }; exports['default'] = function (self) { return new Worker(self); }; module.exports = exports['default']; },{"mux.js":8}],30:[function(require,module,exports){ (function (global){ /** * @file virtual-source-buffer.js */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null); var _videoJs2 = _interopRequireDefault(_videoJs); var _createTextTracksIfNecessary = require('./create-text-tracks-if-necessary'); var _createTextTracksIfNecessary2 = _interopRequireDefault(_createTextTracksIfNecessary); var _removeCuesFromTrack = require('./remove-cues-from-track'); var _removeCuesFromTrack2 = _interopRequireDefault(_removeCuesFromTrack); var _addTextTrackData = require('./add-text-track-data'); var _addTextTrackData2 = _interopRequireDefault(_addTextTrackData); var _webworkify = require('webworkify'); var _webworkify2 = _interopRequireDefault(_webworkify); var _transmuxerWorker = require('./transmuxer-worker'); var _transmuxerWorker2 = _interopRequireDefault(_transmuxerWorker); var _codecUtils = require('./codec-utils'); /** * VirtualSourceBuffers exist so that we can transmux non native formats * into a native format, but keep the same api as a native source buffer. * It creates a transmuxer, that works in its own thread (a web worker) and * that transmuxer muxes the data into a native format. VirtualSourceBuffer will * then send all of that data to the naive sourcebuffer so that it is * indestinguishable from a natively supported format. * * @param {HtmlMediaSource} mediaSource the parent mediaSource * @param {Array} codecs array of codecs that we will be dealing with * @class VirtualSourceBuffer * @extends video.js.EventTarget */ var VirtualSourceBuffer = (function (_videojs$EventTarget) { _inherits(VirtualSourceBuffer, _videojs$EventTarget); function VirtualSourceBuffer(mediaSource, codecs) { var _this = this; _classCallCheck(this, VirtualSourceBuffer); _get(Object.getPrototypeOf(VirtualSourceBuffer.prototype), 'constructor', this).call(this, _videoJs2['default'].EventTarget); this.timestampOffset_ = 0; this.pendingBuffers_ = []; this.bufferUpdating_ = false; this.mediaSource_ = mediaSource; this.codecs_ = codecs; this.audioCodec_ = null; this.videoCodec_ = null; this.audioDisabled_ = false; var options = { remux: false }; this.codecs_.forEach(function (codec) { if ((0, _codecUtils.isAudioCodec)(codec)) { _this.audioCodec_ = codec; } else if ((0, _codecUtils.isVideoCodec)(codec)) { _this.videoCodec_ = codec; } }); // append muxed segments to their respective native buffers as // soon as they are available this.transmuxer_ = (0, _webworkify2['default'])(_transmuxerWorker2['default']); this.transmuxer_.postMessage({ action: 'init', options: options }); this.transmuxer_.onmessage = function (event) { if (event.data.action === 'data') { return _this.data_(event); } if (event.data.action === 'done') { return _this.done_(event); } }; // this timestampOffset is a property with the side-effect of resetting // baseMediaDecodeTime in the transmuxer on the setter Object.defineProperty(this, 'timestampOffset', { get: function get() { return this.timestampOffset_; }, set: function set(val) { if (typeof val === 'number' && val >= 0) { this.timestampOffset_ = val; // We have to tell the transmuxer to set the baseMediaDecodeTime to // the desired timestampOffset for the next segment this.transmuxer_.postMessage({ action: 'setTimestampOffset', timestampOffset: val }); } } }); // setting the append window affects both source buffers Object.defineProperty(this, 'appendWindowStart', { get: function get() { return (this.videoBuffer_ || this.audioBuffer_).appendWindowStart; }, set: function set(start) { if (this.videoBuffer_) { this.videoBuffer_.appendWindowStart = start; } if (this.audioBuffer_) { this.audioBuffer_.appendWindowStart = start; } } }); // this buffer is "updating" if either of its native buffers are Object.defineProperty(this, 'updating', { get: function get() { return !!(this.bufferUpdating_ || !this.audioDisabled_ && this.audioBuffer_ && this.audioBuffer_.updating || this.videoBuffer_ && this.videoBuffer_.updating); } }); // the buffered property is the intersection of the buffered // ranges of the native source buffers Object.defineProperty(this, 'buffered', { get: function get() { var start = null; var end = null; var arity = 0; var extents = []; var ranges = []; if (!this.videoBuffer_ && (this.audioDisabled_ || !this.audioBuffer_)) { return _videoJs2['default'].createTimeRange(); } // Handle the case where we only have one buffer if (!this.videoBuffer_) { return this.audioBuffer_.buffered; } else if (this.audioDisabled_ || !this.audioBuffer_) { return this.videoBuffer_.buffered; } // Handle the case where there is no buffer data if ((!this.videoBuffer_ || this.videoBuffer_.buffered.length === 0) && (!this.audioBuffer_ || this.audioBuffer_.buffered.length === 0)) { return _videoJs2['default'].createTimeRange(); } // Handle the case where we have both buffers and create an // intersection of the two var videoBuffered = this.videoBuffer_.buffered; var audioBuffered = this.audioBuffer_.buffered; var count = videoBuffered.length; // A) Gather up all start and end times while (count--) { extents.push({ time: videoBuffered.start(count), type: 'start' }); extents.push({ time: videoBuffered.end(count), type: 'end' }); } count = audioBuffered.length; while (count--) { extents.push({ time: audioBuffered.start(count), type: 'start' }); extents.push({ time: audioBuffered.end(count), type: 'end' }); } // B) Sort them by time extents.sort(function (a, b) { return a.time - b.time; }); // C) Go along one by one incrementing arity for start and decrementing // arity for ends for (count = 0; count < extents.length; count++) { if (extents[count].type === 'start') { arity++; // D) If arity is ever incremented to 2 we are entering an // overlapping range if (arity === 2) { start = extents[count].time; } } else if (extents[count].type === 'end') { arity--; // E) If arity is ever decremented to 1 we leaving an // overlapping range if (arity === 1) { end = extents[count].time; } } // F) Record overlapping ranges if (start !== null && end !== null) { ranges.push([start, end]); start = null; end = null; } } return _videoJs2['default'].createTimeRanges(ranges); } }); } /** * When we get a data event from the transmuxer * we call this function and handle the data that * was sent to us * * @private * @param {Event} event the data event from the transmuxer */ _createClass(VirtualSourceBuffer, [{ key: 'data_', value: function data_(event) { var segment = event.data.segment; // Cast ArrayBuffer to TypedArray segment.data = new Uint8Array(segment.data, event.data.byteOffset, event.data.byteLength); (0, _createTextTracksIfNecessary2['default'])(this, this.mediaSource_, segment); // Add the segments to the pendingBuffers array this.pendingBuffers_.push(segment); return; } /** * When we get a done event from the transmuxer * we call this function and we process all * of the pending data that we have been saving in the * data_ function * * @private * @param {Event} event the done event from the transmuxer */ }, { key: 'done_', value: function done_(event) { // All buffers should have been flushed from the muxer // start processing anything we have received this.processPendingSegments_(); return; } /** * Create our internal native audio/video source buffers and add * event handlers to them with the following conditions: * 1. they do not already exist on the mediaSource * 2. this VSB has a codec for them * * @private */ }, { key: 'createRealSourceBuffers_', value: function createRealSourceBuffers_() { var _this2 = this; var types = ['audio', 'video']; types.forEach(function (type) { // Don't create a SourceBuffer of this type if we don't have a // codec for it if (!_this2[type + 'Codec_']) { return; } // Do nothing if a SourceBuffer of this type already exists if (_this2[type + 'Buffer_']) { return; } var buffer = null; // If the mediasource already has a SourceBuffer for the codec // use that if (_this2.mediaSource_[type + 'Buffer_']) { buffer = _this2.mediaSource_[type + 'Buffer_']; } else { buffer = _this2.mediaSource_.nativeMediaSource_.addSourceBuffer(type + '/mp4;codecs="' + _this2[type + 'Codec_'] + '"'); _this2.mediaSource_[type + 'Buffer_'] = buffer; } _this2[type + 'Buffer_'] = buffer; // Wire up the events to the SourceBuffer ['update', 'updatestart', 'updateend'].forEach(function (event) { buffer.addEventListener(event, function () { // if audio is disabled if (type === 'audio' && _this2.audioDisabled_) { return; } var shouldTrigger = types.every(function (t) { // skip checking audio's updating status if audio // is not enabled if (t === 'audio' && _this2.audioDisabled_) { return true; } // if the other type if updating we don't trigger if (type !== t && _this2[t + 'Buffer_'] && _this2[t + 'Buffer_'].updating) { return false; } return true; }); if (shouldTrigger) { return _this2.trigger(event); } }); }); }); } /** * Emulate the native mediasource function, but our function will * send all of the proposed segments to the transmuxer so that we * can transmux them before we append them to our internal * native source buffers in the correct format. * * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/appendBuffer * @param {Uint8Array} segment the segment to append to the buffer */ }, { key: 'appendBuffer', value: function appendBuffer(segment) { // Start the internal "updating" state this.bufferUpdating_ = true; this.transmuxer_.postMessage({ action: 'push', // Send the typed-array of data as an ArrayBuffer so that // it can be sent as a "Transferable" and avoid the costly // memory copy data: segment.buffer, // To recreate the original typed-array, we need information // about what portion of the ArrayBuffer it was a view into byteOffset: segment.byteOffset, byteLength: segment.byteLength }, [segment.buffer]); this.transmuxer_.postMessage({ action: 'flush' }); } /** * Emulate the native mediasource function and remove parts * of the buffer from any of our internal buffers that exist * * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/remove * @param {Double} start position to start the remove at * @param {Double} end position to end the remove at */ }, { key: 'remove', value: function remove(start, end) { if (this.videoBuffer_) { this.videoBuffer_.remove(start, end); } if (!this.audioDisabled_ && this.audioBuffer_) { this.audioBuffer_.remove(start, end); } // Remove Metadata Cues (id3) (0, _removeCuesFromTrack2['default'])(start, end, this.metadataTrack_); // Remove Any Captions (0, _removeCuesFromTrack2['default'])(start, end, this.inbandTextTrack_); } /** * Process any segments that the muxer has output * Concatenate segments together based on type and append them into * their respective sourceBuffers * * @private */ }, { key: 'processPendingSegments_', value: function processPendingSegments_() { var sortedSegments = { video: { segments: [], bytes: 0 }, audio: { segments: [], bytes: 0 }, captions: [], metadata: [] }; // Sort segments into separate video/audio arrays and // keep track of their total byte lengths sortedSegments = this.pendingBuffers_.reduce(function (segmentObj, segment) { var type = segment.type; var data = segment.data; segmentObj[type].segments.push(data); segmentObj[type].bytes += data.byteLength; // Gather any captions into a single array if (segment.captions) { segmentObj.captions = segmentObj.captions.concat(segment.captions); } if (segment.info) { segmentObj[type].info = segment.info; } // Gather any metadata into a single array if (segment.metadata) { segmentObj.metadata = segmentObj.metadata.concat(segment.metadata); } return segmentObj; }, sortedSegments); // Create the real source buffers if they don't exist by now since we // finally are sure what tracks are contained in the source if (!this.videoBuffer_ && !this.audioBuffer_) { // Remove any codecs that may have been specified by default but // are no longer applicable now if (sortedSegments.video.bytes === 0) { this.videoCodec_ = null; } if (sortedSegments.audio.bytes === 0) { this.audioCodec_ = null; } this.createRealSourceBuffers_(); } if (sortedSegments.audio.info) { this.mediaSource_.trigger({ type: 'audioinfo', info: sortedSegments.audio.info }); } if (sortedSegments.video.info) { this.mediaSource_.trigger({ type: 'videoinfo', info: sortedSegments.video.info }); } // Merge multiple video and audio segments into one and append if (this.videoBuffer_) { this.concatAndAppendSegments_(sortedSegments.video, this.videoBuffer_); // TODO: are video tracks the only ones with text tracks? (0, _addTextTrackData2['default'])(this, sortedSegments.captions, sortedSegments.metadata); } if (!this.audioDisabled_ && this.audioBuffer_) { this.concatAndAppendSegments_(sortedSegments.audio, this.audioBuffer_); } this.pendingBuffers_.length = 0; // We are no longer in the internal "updating" state this.bufferUpdating_ = false; } /** * Combine all segments into a single Uint8Array and then append them * to the destination buffer * * @param {Object} segmentObj * @param {SourceBuffer} destinationBuffer native source buffer to append data to * @private */ }, { key: 'concatAndAppendSegments_', value: function concatAndAppendSegments_(segmentObj, destinationBuffer) { var offset = 0; var tempBuffer = undefined; if (segmentObj.bytes) { tempBuffer = new Uint8Array(segmentObj.bytes); // Combine the individual segments into one large typed-array segmentObj.segments.forEach(function (segment) { tempBuffer.set(segment, offset); offset += segment.byteLength; }); destinationBuffer.appendBuffer(tempBuffer); } } /** * Emulate the native mediasource function. abort any soureBuffer * actions and throw out any un-appended data. * * @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/abort */ }, { key: 'abort', value: function abort() { if (this.videoBuffer_) { this.videoBuffer_.abort(); } if (this.audioBuffer_) { this.audioBuffer_.abort(); } if (this.transmuxer_) { this.transmuxer_.postMessage({ action: 'reset' }); } this.pendingBuffers_.length = 0; this.bufferUpdating_ = false; } }]); return VirtualSourceBuffer; })(_videoJs2['default'].EventTarget); exports['default'] = VirtualSourceBuffer; module.exports = exports['default']; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./add-text-track-data":21,"./codec-utils":22,"./create-text-tracks-if-necessary":23,"./remove-cues-from-track":28,"./transmuxer-worker":29,"webworkify":31}],31:[function(require,module,exports){ var bundleFn = arguments[3]; var sources = arguments[4]; var cache = arguments[5]; var stringify = JSON.stringify; module.exports = function (fn) { var keys = []; var wkey; var cacheKeys = Object.keys(cache); for (var i = 0, l = cacheKeys.length; i < l; i++) { var key = cacheKeys[i]; if (cache[key].exports === fn) { wkey = key; break; } } if (!wkey) { wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16); var wcache = {}; for (var i = 0, l = cacheKeys.length; i < l; i++) { var key = cacheKeys[i]; wcache[key] = key; } sources[wkey] = [ Function(['require','module','exports'], '(' + fn + ')(self)'), wcache ]; } var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16); var scache = {}; scache[wkey] = wkey; sources[skey] = [ Function(['require'],'require(' + stringify(wkey) + ')(self)'), scache ]; var src = '(' + bundleFn + ')({' + Object.keys(sources).map(function (key) { return stringify(key) + ':[' + sources[key][0] + ',' + stringify(sources[key][1]) + ']' ; }).join(',') + '},{},[' + stringify(skey) + '])' ; var URL = window.URL || window.webkitURL || window.mozURL || window.msURL; return new Worker(URL.createObjectURL( new Blob([src], { type: 'text/javascript' }) )); }; },{}],32:[function(require,module,exports){ (function (global){ /** * @file videojs-contrib-media-sources.js */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _flashMediaSource = require('./flash-media-source'); var _flashMediaSource2 = _interopRequireDefault(_flashMediaSource); var _htmlMediaSource = require('./html-media-source'); var _htmlMediaSource2 = _interopRequireDefault(_htmlMediaSource); var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null); var _videoJs2 = _interopRequireDefault(_videoJs); var urlCount = 0; // ------------ // Media Source // ------------ var defaults = { // how to determine the MediaSource implementation to use. There // are three available modes: // - auto: use native MediaSources where available and Flash // everywhere else // - html5: always use native MediaSources // - flash: always use the Flash MediaSource polyfill mode: 'auto' }; // store references to the media sources so they can be connected // to a video element (a swf object) // TODO: can we store this somewhere local to this module? _videoJs2['default'].mediaSources = {}; /** * Provide a method for a swf object to notify JS that a * media source is now open. * * @param {String} msObjectURL string referencing the MSE Object URL * @param {String} swfId the swf id */ var open = function open(msObjectURL, swfId) { var mediaSource = _videoJs2['default'].mediaSources[msObjectURL]; if (mediaSource) { mediaSource.trigger({ type: 'sourceopen', swfId: swfId }); } else { throw new Error('Media Source not found (Video.js)'); } }; /** * Check to see if the native MediaSource object exists and supports * an MP4 container with both H.264 video and AAC-LC audio. * * @return {Boolean} if native media sources are supported */ var supportsNativeMediaSources = function supportsNativeMediaSources() { return !!window.MediaSource && !!window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported('video/mp4;codecs="avc1.4d400d,mp4a.40.2"'); }; /** * An emulation of the MediaSource API so that we can support * native and non-native functionality such as flash and * video/mp2t videos. returns an instance of HtmlMediaSource or * FlashMediaSource depending on what is supported and what options * are passed in. * * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/MediaSource * @param {Object} options options to use during setup. */ var MediaSource = function MediaSource(options) { var settings = _videoJs2['default'].mergeOptions(defaults, options); this.MediaSource = { open: open, supportsNativeMediaSources: supportsNativeMediaSources }; // determine whether HTML MediaSources should be used if (settings.mode === 'html5' || settings.mode === 'auto' && supportsNativeMediaSources()) { return new _htmlMediaSource2['default'](); } // otherwise, emulate them through the SWF return new _flashMediaSource2['default'](); }; exports.MediaSource = MediaSource; MediaSource.open = open; MediaSource.supportsNativeMediaSources = supportsNativeMediaSources; /** * A wrapper around the native URL for our MSE object * implementation, this object is exposed under videojs.URL * * @link https://developer.mozilla.org/en-US/docs/Web/API/URL/URL */ var URL = { /** * A wrapper around the native createObjectURL for our objects. * This function maps a native or emulated mediaSource to a blob * url so that it can be loaded into video.js * * @link https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL * @param {MediaSource} object the object to create a blob url to */ createObjectURL: function createObjectURL(object) { var objectUrlPrefix = 'blob:vjs-media-source/'; var url = undefined; // use the native MediaSource to generate an object URL if (object instanceof _htmlMediaSource2['default']) { url = window.URL.createObjectURL(object.nativeMediaSource_); object.url_ = url; return url; } // if the object isn't an emulated MediaSource, delegate to the // native implementation if (!(object instanceof _flashMediaSource2['default'])) { url = window.URL.createObjectURL(object); object.url_ = url; return url; } // build a URL that can be used to map back to the emulated // MediaSource url = objectUrlPrefix + urlCount; urlCount++; // setup the mapping back to object _videoJs2['default'].mediaSources[url] = object; return url; } }; exports.URL = URL; _videoJs2['default'].MediaSource = MediaSource; _videoJs2['default'].URL = URL; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./flash-media-source":25,"./html-media-source":27}]},{},[32])(32) });
const webpack = require('webpack'); const path = require('path'); const { merge } = require('webpack-merge'); const HTMLWebpackPlugin = require('html-webpack-plugin'); const rootPath = (exports.rootPath = path.join(__dirname, '..')); const srcPath = (exports.srcPath = path.join(rootPath, 'src')); const distPath = (exports.distPath = path.join(rootPath, 'dist')); let environment = 'development'; if (process.env.NODE_ENV === 'production') { environment = process.env.BUILD_ENV || 'test'; } exports.environment = environment; const baseConfig = (exports.baseConfig = { entry: { index: path.join(srcPath, 'index.js'), }, output: { path: distPath, }, resolve: { alias: { '@': srcPath, }, }, plugins: [ new webpack.EnvironmentPlugin({ ENVIRONMENT: environment, }), new HTMLWebpackPlugin({ title: 'Vue App', template: path.join(srcPath, 'index.ejs'), favicon: path.join(rootPath, 'static/favicon.ico'), }), ], }); exports.devConfig = merge(baseConfig, {}); exports.prodConfig = merge(baseConfig, {});
/* jshint node: true */ 'use strict'; module.exports = { normalizeEntityName: function() {} };
/*global browser, by */ 'use strict'; describe('E2E: Example', function() { beforeEach(function() { browser.get('/'); browser.waitForAngular(); }); it('should route correctly', function() { expect(browser.getLocationAbsUrl()).toMatch('/'); }); it('should show the number defined in the controller', function() { var element = browser.findElement(by.css('.number-example')); expect(element.getText()).toEqual('1234'); }); });
const webpack = require('webpack'); const sassLintPlugin = require('sasslint-webpack-plugin'); const I18nPlugin = require("i18n-webpack-plugin"); const isDev = process.env.NODE_ENV !== 'production'; const entry = isDev ? [ 'webpack-hot-middleware/client?reload=true&timeout=2000', 'react-hot-loader/patch', './client/index.jsx' ] : './client/index.jsx'; const plugins = isDev ? [ new sassLintPlugin({ glob: 'client/**/*.sass', configFile: '.sass-lint.yml', }), new webpack.HotModuleReplacementPlugin(), ] : []; const config = { entry, plugins, cache: isDev, // devtool: isDev ? 'cheap-module-eval-source-map' : 'none', output: { path: `${__dirname}/client/dist`, filename: 'bundle.js', libraryTarget: 'umd', publicPath: '/', }, resolve: { modules: ['node_modules', 'client'], extensions: ['.jsx', '.js'], }, module: { loaders: [ { enforce: 'pre', test: /\.jsx?$/, exclude: /node_modules/, loader: 'eslint-loader', }, { test: /\.md$/, loader: 'markdown-loader', }, { test: /\.jsx?$/, loader: 'babel-loader', }, { test: /\.sass$/, exclude: /node_modules/, loader: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'], }, ], }, }; // List of available languages, will be modified when new languages are added. const languages = ['en']; module.exports = languages.map((lang) => { const newConfig = Object.assign({}, config); newConfig.plugins = [ ...plugins, new I18nPlugin(require(`./client/languages/${lang}/index`)), ]; newConfig.output = { path: `${__dirname}/client/dist`, filename: `${lang}.bundle.js`, libraryTarget: 'umd', publicPath: '/', }; return newConfig; });
export const facebook = {"viewBox":"0 0 16 16","children":[{"name":"path","attribs":{"fill":"#000000","d":"M9.5 3h2.5v-3h-2.5c-1.93 0-3.5 1.57-3.5 3.5v1.5h-2v3h2v8h3v-8h2.5l0.5-3h-3v-1.5c0-0.271 0.229-0.5 0.5-0.5z"}}]};
var _require = require('zoroaster/assert'), deepEqual = _require.deepEqual, throws = _require.throws; var context = require('../context/WroteContext'); var readJSON = require('../../src/read-json'); var readJSONTestSuite = { context, 'should read a JSON file'(_ref) { return new Promise(function ($return, $error) { var expectedJSON, JSONpath, res; expectedJSON = _ref.expectedJSON, JSONpath = _ref.JSONpath; return Promise.resolve(readJSON(JSONpath)).then(function ($await_1) { try { res = $await_1; deepEqual(res, expectedJSON); return $return(); } catch ($boundEx) { return $error($boundEx); } }.bind(this), $error); }.bind(this)); }, 'should throw an error if file is not found'(_ref2) { return new Promise(function ($return, $error) { var tempFile; tempFile = _ref2.tempFile; return Promise.resolve(throws({ fn: readJSON, args: [tempFile], code: 'ENOENT' })).then(function ($await_2) { try { return $return(); } catch ($boundEx) { return $error($boundEx); } }.bind(this), $error); }.bind(this)); }, 'should throw an error if cannot parse JSON'(_ref3) { return new Promise(function ($return, $error) { var invalidJSONpath; invalidJSONpath = _ref3.invalidJSONpath; return Promise.resolve(throws({ fn: readJSON, args: [invalidJSONpath], message: /Unexpected token h/ })).then(function ($await_3) { try { return $return(); } catch ($boundEx) { return $error($boundEx); } }.bind(this), $error); }.bind(this)); } }; module.exports = readJSONTestSuite;
import gulp from 'gulp' import gutil from 'gulp-util' import del from 'del' import WebpackDevServer from "webpack-dev-server" import webpack from "webpack" const path = require('path'); const DEV_PORT = 4000, PROD_PORT = 80 const server = (webpackPath, cb)=> { let webpackConfig = require(webpackPath) let myConfig = Object.create(webpackConfig) myConfig.devtool = 'eval-source-map' myConfig.debug = true; new WebpackDevServer(webpack(myConfig), { hot: true, inline: true, publicPath: '/' + myConfig.output.publicPath, stats: { colors: true } }).listen(DEV_PORT, "127.0.0.1", err => { if (err) throw new gutil.PluginError("webpack-dev-server", err) gutil.log("[webpack-dev-server]", "==> http://127.0.0.1:" + DEV_PORT) }); cb(); }; const build = (webpackPath, cb)=> { let webpackConfig = require(webpackPath) let myConfig = Object.create(webpackConfig) webpack(myConfig, function (err, stats) { if (err) throw new gutil.PluginError("webpack", err) gutil.log("[webpack]", stats.toString({ // output options })); cb() }) }; gulp.task('server-dev', cb => { server(path.join(__dirname, ''), cb); }); gulp.task('server-build', cb => { build(path.join(__dirname, ''), cb); }); gulp.task('base-dev', cb => { }); gulp.task('base-build', cb => { }); gulp.task('clean', cb => del([path.join(__dirname, '/dist/*')]));
/** * @fileoverview Rule to flag use of arguments.callee and arguments.caller. * @author Nicholas C. Zakas */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "suggestion", docs: { description: "disallow the use of `arguments.caller` or `arguments.callee`", recommended: false, url: "https://eslint.org/docs/rules/no-caller" }, schema: [], messages: { unexpected: "Avoid arguments.{{prop}}." } }, create(context) { return { MemberExpression(node) { const objectName = node.object.name, propertyName = node.property.name; if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/u)) { context.report({ node, messageId: "unexpected", data: { prop: propertyName } }); } } }; } };
var React = require('react'); var App = React.createClass({ componentDidMount: function() { DesiredTravelStore.addChangeListener(this._onChange); }, componentWillUnmount: function() { DesiredTravelStore.removeChangeListener(this._onChange); }, /** * @return {object} */ render: function() { return ( <TravelComponent /> ); }, /** * Event handler for 'change' events coming from the TodoStore */ _onChange: function() { console.log("change"); } }); module.exports = App;
var http = require('http'); var parseString = require('xml2js').parseString; var countryIds = require(require('path').resolve(__dirname, 'lib', 'countries.json')); module.exports = function(localization, count, callback) { var url = "http://trends.google.com/trends/hottrends/atom/feed?pn=" + countryIds[localization.toLowerCase()]; if (count > 20) count = 20; xmlToJson(url, function(err, data) { var allFeedItems = data.rss.channel['0'].item; var toReturn = {}; var i = 0; while (i < count) { toReturn[i] = allFeedItems[i]; i++; } callback(err, toReturn); }); } function xmlToJson(url, callback) { var req = http.get(url, function(res) { var xml = ''; res.on('data', function(chunk) { xml += chunk; }); res.on('error', function(e) { callback(e, null); }); res.on('timeout', function(e) { callback(e, null); }); res.on('end', function() { parseString(xml, function(err, result) { callback(null, result); }); }); }); }
//namespace if (!this.hook) this.hook = {}; (function () { function D3Interface(chart) { adapter.Interface.call(this); this.chart = chart; this.dataSource; } D3Interface.prototype = new adapter.Interface(); D3Interface.prototype.constructor = D3Interface; var p = D3Interface.prototype; /* *This function renders on the visualization library , which are hooked to it * @param keys: We need to give the index value or Keys associated with that record [0,3,5] * @param columns: We need to give the the charts column ids like ['col1','col2'] * @param chart: we need to give chart instance generated in c3 */ p.doSelection = function (keys) { this.chart.select(keys); } p.doProbe = function (key) { this.chart.probe(key); } p.setData = function (sourceName, data) { this.dataSource = sourceName; this.chart.renderChart(data); } hook.D3Interface = D3Interface; }());
angular.module('tweetsToSoftware') .directive('topMenu', function($document) { 'use strict'; return { restrict: 'E', templateUrl: 'menu.html', scope: { menu: '=', itemActivateCallback: '=', itemHoverCallback: '=', itemLeaveCallback: '=', rootItemClickCallback: '=', rootItemHoverCallback: '=', rootItemLeaveCallback: '=' }, link: function($scope) { $document.on('click', function(e) { var targetIsMenu = $(e.target).parents('.js-top-menu').length || $(e.target).hasClass('js-top-menu'); if ($scope.menu.isOpen && !targetIsMenu) { console.log('menu close'); $scope.menu.close(); $scope.$apply(); } }); } }; });
const bodyParser = require("body-parser"); const compression = require("compression"); const cors = require("cors"); const express = require("express"); const Joi = require("@hapi/joi"); const { HttpError, ObjectNotExistError } = require("./libs/errors"); const expressMongoDb = require("./middlewares/express_mongo_db"); const expressRedisDb = require("./middlewares/express_redis_db"); const logger = require("morgan"); const winston = require("winston"); const passport = require("passport"); const { jwtStrategy } = require("./utils/passport-strategies"); const ModelManager = require("./models/manager"); const routes = require("./routes"); const schema = require("./schema"); const setupGraphql = require("./utils/setup_graphql"); const { REDIS_URL, CORS_ANY } = process.env; const app = express(); // We are behind the proxy app.set("trust proxy", 1); // Enable compress the traffic if (app.get("env") === "production") { app.use(compression()); } // winston logging setup if (app.get("env") === "test" || app.get("env") === "developement") { winston.remove(winston.transports.Console); } if (app.get("env") !== "test") { app.use(logger("dev")); } app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(expressMongoDb()); app.use(expressRedisDb(REDIS_URL)); app.use((req, res, next) => { req.manager = new ModelManager(req.db); next(); }); if (CORS_ANY === "TRUE") { app.use(cors()); } else { app.use( cors({ origin: [/\.goodjob\.life$/], }) ); } app.use((req, res, next) => { winston.info(req.originalUrl, { ip: req.ip, ips: req.ips, query: req.query, }); next(); }); app.use(passport.initialize()); passport.use(jwtStrategy()); app.use((req, res, next) => { passport.authenticate("jwt", { session: false }, (err, user) => { if (user) { req.user = user; } next(); })(req, res, next); }); app.use("/", routes); setupGraphql(app, { schema, context: ({ req }) => ({ db: req.db, manager: req.manager, user: req.user, }), formatError: err => { winston.warn("", { message: err.message, error: err, }); // If Joi.ValidationError, overwrite code to be the same as UserInputError if (err.originalError instanceof Joi.ValidationError) { err.extensions.code = "BAD_USER_INPUT"; } return err; }, }); // catch 404 and forward to error handler app.use((req, res, next) => { next(new HttpError("Not Found", 404)); }); // error handlers // logging any error except HttpError app.use((err, req, res, next) => { if (err instanceof ObjectNotExistError) { next(new HttpError("Not Found", 404)); return; } if (err instanceof HttpError) { next(err); return; } winston.warn(req.originalUrl, { ip: req.ip, ips: req.ips, message: err.message, error: err, }); next(err); }); // development error handler // will print stacktrace if (app.get("env") === "development") { // eslint-disable-next-line app.use((err, req, res, next) => { if (err instanceof HttpError) { winston.warn(req.originalUrl, { ip: req.ip, ips: req.ips, message: err.message, error: err, }); } res.status(err.status || 500); res.send({ message: err.message, error: err, }); }); } // production error handler // no stacktraces leaked to user // eslint-disable-next-line app.use((err, req, res, next) => { res.status(err.status || 500); res.send({ message: err.message, error: {}, }); }); module.exports = app;
import { waitForVisibilityOf, protractorUniTestkitFactoryCreator, } from 'wix-ui-test-utils/protractor'; import { eyesItInstance } from '../../../test/utils/eyes-it'; import { createTestStoryUrl } from '../../../test/utils/storybook-helpers'; import richTextInputAreaPrivateDriverFactory from '../RichTextInputArea.private.uni.driver'; import { storySettings, testStories } from '../docs/storySettings'; const eyes = eyesItInstance(); describe('RichTextInputArea', () => { const testStoryUrl = createTestStoryUrl({ ...storySettings, testName: testStories.richTextInputArea, }); const createDriver = async (dataHook = storySettings.dataHook) => { const driver = protractorUniTestkitFactoryCreator( richTextInputAreaPrivateDriverFactory, )({ dataHook, }); await waitForVisibilityOf( await driver.element(), `Cannot find <RichTextInputArea/> component with dataHook of ${dataHook}`, ); return driver; }; beforeAll(async () => { await browser.get(testStoryUrl); }); describe('Editor', () => { eyes.it( `should change the editor's background color on hover`, async () => { const driver = await createDriver(); await driver.hoverTextArea(); }, ); eyes.it(`should change the editor's border on click`, async () => { const driver = await createDriver(); await driver.clickTextArea(); }); }); });
'use strict' const allowedOptions = [ '--config', '--help', '--os', '--osVersion', '--browser', '--browserVersion', '--device', '--orientation', '--size', '--timeout', '--project', '--test', '--build', '--local', '--localIdentifier', '--screenshots', '--video', '--framework' ] let path = require('path'), utils = require('./../../../utils'), args = require('minimist')(process.argv.slice(2), { string: [ 'config', 'os', 'osVersion', 'browser', 'browserVersion', 'device', 'orientation', 'size', 'project', 'test', 'build', 'localIdentifier', 'framework' ], boolean: [ 'local', 'screenshots', 'video', 'help' ], alias: { help: 'h' }, default: { browserVersion : null, timeout: 60, local: true }, unknown: opt => { return utils.onUnknownOpt(-1 !== allowedOptions.indexOf(opt) || opt.match(/^http/), opt, help) } }) const helpArgsLine = ' [--help|-h] [--config <config-file>]' + ' [--os <os>] [--osVersion <os-version>]' + ' [--browser <browser>] [--browserVersion <browser-version>] [--device <device> ]' + ' [--orientation <orientation>] [--size <size>]' + ' [--local] [--localIdentifier <identifier>]' + ' [--video] [--screenshots]' + ' [--timeout <timeout-in-sec>]' + ' [--framework <test-framework>]' + ' [--project <project>] [--test <test>] [--build <build>]\n\n', helpDefs = 'Defaults:\n' + ' config cbtr.json in project root, or CBTR_SETTINGS env var\n' + ' browserVersion null\n' + ' timeout 60\n' + ' video false\n' + ' screenshots false\n' + ' local true\n\n', helpOpts = 'Options:\n' + ' help print this help\n' + ' config cross-browser-tests-runner settings file\n' + ' os operating system for a test e.g. Windows\n' + ' osVersion operating system version for a test e.g. 10 (for Windows)\n' + ' browser browser for a test e.g. Firefox\n' + ' browserVersion browser version for a test e.g. 43.0\n' + ' device device for mobile os case e.g. iPhone 5\n' + ' orientation portrait|landscape, for mobile os case\n' + ' size screen size, for mobile os case\n' + ' local if a local page is being tested [forced as true for now]\n' + ' localIdentifier id of tunnel, used in case multiple tunnels are required\n' + ' video whether video of the test should be recorded\n' + ' screenshots whether screenshots of the test should be recorded\n' + ' timeout timeout at which test would be stopped by cross-browser testing platform\n' + ' framework framework used for the test (as of now needed only for SauceLabs)\n' + ' project name of project (username/repository or any other format)\n' + ' test name of test e.g. CI job id\n' + ' build name of build, typically the commit sha1' utils.handleHelp(args, help) let request = require('request-promise'), Log = require('./../../../../lib/core/log').Log, PlatformKeys = require('./../../../../lib/platforms/interfaces/platform').PlatformKeys, log = new Log('Hooks.Testem.Common.Browser') const settings = require('./../../../server/settings')(args.config), signals = ['SIGINT', 'SIGHUP', 'SIGTERM'] const main = (platform) => { log.debug('Arguments received', args) log.debug('settings', settings) let data = { url : args._[0], browser : { }, capabilities : { } } setupInput(data) let run request .post('http://' + settings.server.host + ':' + settings.server.port + '/runs/testem/' + platform, { body: data, json: true }) .then(response => { run = response.id setupExit(platform, run) console.log('created test %s', response.id) }) .catch(err => { log.error('failed to create test - %s', err) }) } function setupInput(data) { Object.keys(args).forEach(opt => { if (-1 !== PlatformKeys.browser.indexOf(opt)) { data.browser[opt] = args[opt] } else if (-1 !== PlatformKeys.capabilities.indexOf(opt)) { data.capabilities[opt] = args[opt] } }) } function setupExit(platform, run) { // set up a default exit timeout of 1 hour let timer = setTimeout(()=>{stopRunExit(platform, run)}, 3600000) signals.forEach(sig => { process.on(sig, () => { log.info('received exit signal %s', sig) clearTimeout(timer) stopRunExit(platform, run) }) }) } function stopRunExit(platform, run) { request .delete('http://' + settings.server.host + ':' + settings.server.port + '/runs/testem/' + platform + '/' + run, { body: { screenshot: args.screenshots }, json: true }) .then(() => { log.info('stopped run %s, exiting...', run) process.exitCode = 0 }) } function help() { console.log( '\n' + path.basename(process.argv[1]) + helpArgsLine + helpDefs + helpOpts ) } exports.run = main
'use strict'; var path = require('path'); var browserify = require('browserify'), eventStream = require('event-stream'), glob = require('glob'), vinylBuffer = require('vinyl-buffer'), vinylSource = require('vinyl-source-stream'), watchify = require('watchify'), eslintify = require('eslintify'), uglifyify = require('uglifyify'); function Bundler(plug, file, src, dest, watch) { var srcFile = path.join(src, file), watchMsg = 'Watching bundle ' + plug.util.colors.magenta(file) + '...'; this.bundle = watchify(browserify({ entries: [srcFile], insertGlobals: false, paths: [ src, path.join(plug.paths.cwd, 'node_modules'), path.join(plug.paths.cwd, 'bower_components') ], debug: true, transform: [], cache: {}, packageCache: {} }), { delay: 100, ignoreWatch: ['**/node_modules/**'], poll: true }); this.bundle.on('update', function(id) { var eventFile = path.relative(src, id[0]); plug.util.log( plug.util.colors.yellow('☀ ') + 'File ' + plug.util.colors.magenta(eventFile) + ' updated. ' + 'Bundling ' + plug.util.colors.magenta(file) + '...' ); this.output(); }.bind(this)); this.bundle.on('log', function(msg) { plug.util.log( plug.util.colors.green('✓ ') + 'Bundled ' + plug.util.colors.magenta(file) + ' ' + plug.util.colors.gray(msg) ); }); this.bundle.transform(eslintify); this.bundle.transform({global: true}, uglifyify); this.output = function() { return this.bundle .bundle() .on('error', function(err) { plug.util.log(err.toString()); this.emit('end'); }) .pipe(vinylSource(file)) .pipe(vinylBuffer()) .pipe(plug.plugins.plumber()) .pipe(plug.plugins.extReplace(plug.pkg.version + '.js', '.js')) .pipe(plug.plugins.sourcemaps.init({ loadMaps: true })) .pipe(plug.plugins.sourcemaps.write('.', { includeContent: true, sourceRoot: '.' })) .pipe(plug.gulp.dest(dest)) .on('end', function() { if (!watch) { this.bundle.close(); } else if (watchMsg) { plug.util.log(watchMsg); watchMsg = false; } }.bind(this)); }; } module.exports = [ 'browserify javascripts', function(done) { var plug = this, watch = plug.watchify === true, src = path.join(plug.paths.assets, 'js'), dest = path.join(plug.paths.staticAssets, 'js'); glob('*.js', {cwd: src}, function(err, files) { if (err) return plug.util.log(err); eventStream.merge(files.map(function(file) { var bundler = new Bundler(plug, file, src, dest, watch); return bundler.output(); })).on('end', function() { if (!watch) return done(); }); }); } ];
var PostService = require('./post.service'); var ZiviService = require('./zivi.service'); var ConfigService = require('./config.service'); var STATES = require('../models/states'); const apiKey = ConfigService.getTelegramApiKey(); var TelegramService = require('./telegram-dummy.service'); if (!apiKey || process.env.zimonTest) { console.warn('Using dummy Telegram service, i.e. ignoring all calls.'); console.warn('Set an API key in ./config/local-config.json to change this.'); module.exports = TelegramService; return; } var TelegramBot = require('node-telegram-bot-api'); var bot = new TelegramBot(apiKey, { polling: true, filepath: false }); var errorCounter = 0; bot.on('polling_error', function(err) { if(errorCounter < 5) { console.error('Telegram polling failure', err.code, err.response && err.response.body); } else if((errorCounter % 40) === 0) { console.error('Telegram polling failure (... 9 more) - trace:', err.code, err.response && err.response.body); } else if((errorCounter % 10) === 0) { console.error('Telegram polling failure (... 9 more) - trace every 40 errors'); } errorCounter++; }); bot.onText(/\/start/, function (msg) { return bot.sendMessage(msg.chat.id, 'Hello, it me, El Señor Chefzimon.\n' + 'First and foremost, if you have no idea what this is, please kindly leave. I dislike strangers.\n' + 'If you are authorised by the authorities to communicate with me, kindly tell me your registered ' + 'first name using /init <Your first name>. Note that the first name is case-sensitive.\n\n' + 'If you require assistance, type /help and I will silently ignore your request but print a standardised message.'); }); bot.onText(/\/help/, function (msg) { return bot.sendMessage(msg.chat.id, 'My name is El Señor Chefzimon.\n' + 'I can (but would prefer not to) do these amazing things:\n' + '/init <first name> - Registers your account with me\n' + '/postler - Asks me for the current Postler\n' + '/accept - Accepts your post offer and increments your counter\n' + '/next - Refuses the post offer, choosing somebody else using my entirely fair algorithm\n\n' + 'If you encounter any issues, feel free to open an issue on GitHub: https://github.com/realzimon/backzimon-node'); }); bot.onText(/\/init (.+)/, function (msg, match) { ZiviService.findOneByName(match[1], function (err, zivi) { if (err || !zivi) { return bot.sendMessage(msg.chat.id, 'Sorry, El Señor Chefzimon is not aware of anyone with this name. Note that ' + 'the name is case-sensitive. Do not hack El Señor Chefzimon because he possesses great power beyond human imagination.'); } zivi.chat = msg.chat.id; ZiviService.saveZivi(zivi, function (err) { if (err) { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon is not sorry, but an error occurred either way.'); } bot.sendMessage(msg.chat.id, 'You have connected your Telegram account to El Señor Chefzimon. He will now read ' + 'all the messages you send to him. Do not send nudes.'); }); }); }); bot.onText(/\/postler/, function (msg) { checkAccountInitialisedOrFail(msg, function () { PostService.findCurrentState(function (post) { if (post.state === STATES.IDLE || !post.zivi) { return bot.sendMessage(msg.chat.id, 'Nobody has been selected yet. Stay alert.'); } return bot.sendMessage(msg.chat.id, post.zivi.name + ' will carry out the Honourable Task.'); }); }); }); bot.onText(/\/accept/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.acceptPost(function (err, post) { if (err) { bot.sendMessage(msg.chat.id, 'Internal error accepting. Try again later.'); console.error('Failed to accept post', err); } else { bot.sendMessage(msg.chat.id, 'You have agreed to carry out the Honourable Task. Please note that this is ' + 'a legally binding agreement. Should you not carry out the Honourable Task, your second-born child belongs ' + 'to El Señor Chefzimon. Take care.'); PostService.pushPostState(post); } }); } }); }); }); bot.onText(/\/next/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.nextZivi(function (err, post) { bot.sendMessage(msg.chat.id, post.zivi.name + ' will carry out the Honourable Task.'); PostService.pushPostState(post); TelegramService.sendPostlerPromptTo(post.zivi); }); } }); }); }); bot.onText(/\/cancel/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err, post) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.justSetState(STATES.IDLE, function (err) { if (err) { console.error(' ## error cancelling Telegram post', err); bot.sendMessage(msg.chat.id, 'Error cancelling the Honourable Task. Try again later.') } else { bot.sendMessage(msg.chat.id, 'You have declined the Honourable Task and therefore ruined the fun for everyone. ' + 'EL Señor Chefzimon is not amused. He will strike upon thee with great vengeance next time.'); } }); } }); }); }); bot.onText(/\/dismiss/, function (msg) { checkAccountInitialisedOrFail(msg, function () { PostService.findCurrentState(function (post) { if (post.state !== STATES.REMINDER) { return bot.sendMessage(msg.chat.id, 'It\'s not time yet. Have a little patience.'); } if (post.zivi.chat !== msg.chat.id) { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon has *not* asked you to return the yellow card. Please do not annoy him again.'); } PostService.dismissReminder(function () { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon is not convinced yet. He is watching you.'); }); }); }); }); bot.onText(/\/volunteer/, function (msg) { checkAccountInitialisedOrFail(msg, function (senderZivi) { PostService.findCurrentState(function (post) { if (post.state === STATES.ACTION) { return bot.sendMessage(msg.chat.id, 'Somebody else is currently doing the post, so idk what you\'re doing'); } if (post.zivi.chat === msg.chat.id && post.state !== STATES.IDLE) { return bot.sendMessage(msg.chat.id, 'You are already the assigned Postler. El Señor will not repeat himself again.'); } PostService.forcePostler(senderZivi, function (err, post) { bot.sendMessage(msg.chat.id, 'This is your life now'); TelegramService.sendPostlerPromptTo(post.zivi); }); }); }); }); TelegramService.sendZiviUpdateToUser = function (zivi, message) { if (!zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, message); }; TelegramService.sendPostlerPromptTo = function (zivi) { if (!zivi || !zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, 'Congratulations, you have been selected for the Honourable Task!\n' + 'You may */accept* the offer later, when you\'re leaving,\n' + 'request the */next* Zivi now if you absolutely cannot do it,\n' + 'or */cancel* if there is no need.', { parse_mode: 'Markdown', reply_markup: { one_time_keyboard: true, resize_keyboard: true, keyboard: [ ['/accept'], ['/next', '/cancel'] ] } }); }; TelegramService.sendYellowCardReminder = function (zivi) { if (!zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, 'El Señor Chefzimon assumes that you have already returned ' + 'the yellow card like a responsible adult. Type /dismiss to swear to ' + 'the sacred GNU General Public License.', { parse_mode: 'Markdown', reply_markup: { one_time_keyboard: true, resize_keyboard: true, keyboard: [ ['/dismiss'] ] } }); }; function checkAccountInitialisedOrFail(msg, callback) { var chatId = msg.chat.id; ZiviService.findBy({chart: chatId}, function (err, zivi) { if (!err && zivi) { callback(zivi); } else { return bot.sendMessage(msg.chat.id, 'You have not yet registered with the El Señor Chefzimon Telegram Integration. ' + 'Type /help for more information.'); } }); } function findPostAndCheckPreconditions(msg, callback) { PostService.findCurrentState(function (post) { if (post.state !== STATES.PREPARATION) { return callback('It\'s not time yet. Have a little patience.'); } else if (!post.zivi || post.zivi.chat !== msg.chat.id) { return callback('I\'m sorry, Dave, I cannot do this. You have not been selected for the Honourable Task.'); } callback(null, post); }); } module.exports = TelegramService;
"use strict"; var path = require('path') var grunt = require("grunt"); grunt.file.defaultEncoding = 'utf8'; function compileAsmToJs() { var pattern = this.data.pattern; var files = grunt.file.expand(pattern); var tmpl = grunt.file.read("src/programs/program.js.tmpl"); files.forEach(function(filepath) { // skip files that don't exist if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return; } var program = grunt.file.read(filepath); var filename = path.basename(filepath, '.asm') var t = tmpl; t = t.replace("%BUILD_DATE%", new Date().toISOString()); t = t.replace("%SRC_FILE%", filename + ".asm"); t = t.replace("%PROGRAM_NAME%", upFirst(filename)); t = t.replace("%PROGRAM%", convertProgram(program)); grunt.file.write(filepath.replace(".asm", ".js"), t); }); } function upFirst(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function convertProgram(src) { var res = ''; var lines = src.split('\n'); for (var i = 0; i < lines.length; i++) { var line = lines[i].trim(); if (line.length === 0) { continue; } if (line[0] === "#") { continue; } res += '\t_ += "' + line + '\\n";\n'; } return res; } var buildSpec = { concat: { js: { src: [ 'src/core.js', 'src/clock.js', 'src/compiler.js', 'src/cpu.js', 'src/mem.js', 'src/screen.js', 'src/input.js', 'src/computer.js', // 'src/programs/hello.js', 'src/programs/math.js', 'src/programs/opts_tests.js', 'src/programs/assert.js' ], dest: 'build/main.js' } }, translate_asm_to_js: { compile: { pattern: 'src/**/*.asm' } }, watch: { scripts: { files: ['src/**/*.js', 'src/**/*.asm'], tasks: ['default'], options: { spawn: false, }, }, } }; module.exports = function(grunt) { grunt.initConfig(buildSpec); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.registerMultiTask('translate_asm_to_js', compileAsmToJs) grunt.registerTask('default', ['translate_asm_to_js', 'concat']) };
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { CKEDITOR.dialog.add( 'pastetext', function( editor ) { return { title : editor.lang.pasteText.title, minWidth : CKEDITOR.env.ie && CKEDITOR.env.quirks ? 368 : 350, minHeight : 240, onShow : function(){ this.setupContent(); }, onOk : function(){ this.commitContent(); }, contents : [ { label : editor.lang.common.generalTab, id : 'general', elements : [ { type : 'html', id : 'pasteMsg', html : '<div style="white-space:normal;width:340px;">' + editor.lang.clipboard.pasteMsg + '</div>' }, { type : 'textarea', id : 'content', className : 'cke_pastetext', onLoad : function() { var label = this.getDialog().getContentElement( 'general', 'pasteMsg' ).getElement(), input = this.getElement().getElementsByTag( 'textarea' ).getItem( 0 ); input.setAttribute( 'aria-labelledby', label.$.id ); input.setStyle( 'direction', editor.config.contentsLangDirection ); }, focus : function() { this.getElement().focus(); }, setup : function() { this.setValue( '' ); }, commit : function() { var value = this.getValue(); setTimeout( function() { editor.fire( 'paste', { 'text' : value } ); }, 0 ); } } ] } ] }; }); })();
import React, { Component } from 'react'; import { Link, Match } from 'react-router'; import $ from 'jquery'; import TopActionComponent from './TopActionComponent'; class SuggestedEmployees extends Component{ constructor(context, props){ super(context, props); } componentDidMount() { } render(){ const styleIEButton = { lineHeight: '10px', padding: '1px 1px 1px 1px', textTransform: 'unset', }; return ( <div> <div className=" column l-1-4 float-right"> <div className="primary promo card l-block"> <span className="beta"></span> <h4> <a href="#" className="js-widget">Get Android App</a> </h4> <p> Take the next step in your career. Amazing jobs for all levels and disciplines! </p> <a href="#" className="button-secondary button-fluid text-center js-widget"> Download from Play Store </a> </div> <div className="primary promo card l-block"> <span className="beta"></span> <h4> <a href="#" className="js-widget">Get iOS App</a> </h4> <p> Take the next step in your career. Amazing jobs for all levels and disciplines! </p> <a href="#" className="button-secondary button-fluid text-center js-widget"> Download from Apple Store </a> </div> </div> <div className="column l-3-4 recommendations"> <div className="news card people-recommendation"> <footer> <div className="media"> <div className="media-left"> <img className="media-object" src="/nyumbani/photo_assets/people_48px.svg" alt="Janta Employees suggestions" /> </div> <div className="media-body with-button-inline"> Employees suggested for you </div> </div> </footer> <section className="js-profiles-list"> <div className="profiles media-list"> <div className="media"> <div className="media-left"> <a href="#" title="Mike Njuguna"> <img src="/nyumbani/photo_assets/anony.jpg" alt="Mike Njuguna" /> </a> </div> <div className="media-body"> <div className="user-meta"> <a href="#" className="basic-link" title="Mike Njuguna">Lawrence Nderu</a> <span className="institution">Jomo Kenyatta University of Agriculture and Technology</span> <span className="relationship">Highly recommended in Computer Science</span> </div> </div> <button type="button" style={styleIEButton} className="basic-link mdl-button mdl-js-button mdl-js-ripple-effect"> View Profile <span><i className="material-icons">account_box</i></span> </button> </div> <div className="media"> <div className="media-left"> <a href="#" title="Mike Njuguna"> <img src="/nyumbani/photo_assets/anony.jpg" alt="Mike Njuguna" /> </a> </div> <div className="media-body"> <div className="user-meta"> <a href="#" className="basic-link" title="Mike Njuguan" data-engagement="profile_name_0">Lawrence Nderu</a> <span className="institution">Jomo Kenyatta University of Agriculture and Technology</span> <span className="relationship">Highly recommended in Computer Science</span> </div> </div> <button type="button" style={styleIEButton} className="basic-link mdl-button mdl-js-button mdl-js-ripple-effect"> View Profile <span><i className="material-icons">account_box</i></span> </button> </div> </div> </section> <section className="community"> <hr /> <div className="text-center see-more"> <button className="basic-link js-see-more-suggestions" data-state="unclicked" data-engagement="see_more"> <span>Load more suggestions</span> </button> </div> </section> </div> </div> </div> ); } } export default SuggestedEmployees;
'use strict'; angular.module('keymediaApp', ['angularFileUpload']) .config(function ($routeProvider) { $routeProvider .when('/:album', { templateUrl: '/wp-content/plugins/keymedia/web/app/views/main.html', controller: 'MainCtrl' }) .otherwise({ redirectTo: '/' }); });
import nodeResolve from 'rollup-plugin-node-resolve' import filesize from 'rollup-plugin-filesize' import commonjs from 'rollup-plugin-commonjs' import pkg from './package.json' const external = [...Object.keys(pkg.dependencies), ...Object.keys(pkg.peerDependencies)]; const plugins = [ nodeResolve({ jsnext: true }), commonjs(), filesize() ] export default [ { input: "./lib/index.js", output: { file: "./dist/index.main.js", format: "cjs" }, external: ['react'], external, plugins }, { input: "./lib/index.js", output: { file: "./dist/index.module.js", format: "es" }, external, plugins } ]
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(734); /***/ }), /***/ 3: /***/ (function(module, exports) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }), /***/ 575: /***/ (function(module, exports) { module.exports = require("./kendo.core"); /***/ }), /***/ 734: /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function(f, define){ !(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(575) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (f), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); })(function(){ var __meta__ = { // jshint ignore:line id: "fx", name: "Effects", category: "framework", description: "Required for animation effects in all Kendo UI widgets.", depends: [ "core" ] }; (function($, undefined) { var kendo = window.kendo, fx = kendo.effects, each = $.each, extend = $.extend, proxy = $.proxy, support = kendo.support, browser = support.browser, transforms = support.transforms, transitions = support.transitions, scaleProperties = { scale: 0, scalex: 0, scaley: 0, scale3d: 0 }, translateProperties = { translate: 0, translatex: 0, translatey: 0, translate3d: 0 }, hasZoom = (typeof document.documentElement.style.zoom !== "undefined") && !transforms, matrix3dRegExp = /matrix3?d?\s*\(.*,\s*([\d\.\-]+)\w*?,\s*([\d\.\-]+)\w*?,\s*([\d\.\-]+)\w*?,\s*([\d\.\-]+)\w*?/i, cssParamsRegExp = /^(-?[\d\.\-]+)?[\w\s]*,?\s*(-?[\d\.\-]+)?[\w\s]*/i, translateXRegExp = /translatex?$/i, oldEffectsRegExp = /(zoom|fade|expand)(\w+)/, singleEffectRegExp = /(zoom|fade|expand)/, unitRegExp = /[xy]$/i, transformProps = ["perspective", "rotate", "rotatex", "rotatey", "rotatez", "rotate3d", "scale", "scalex", "scaley", "scalez", "scale3d", "skew", "skewx", "skewy", "translate", "translatex", "translatey", "translatez", "translate3d", "matrix", "matrix3d"], transform2d = ["rotate", "scale", "scalex", "scaley", "skew", "skewx", "skewy", "translate", "translatex", "translatey", "matrix"], transform2units = { "rotate": "deg", scale: "", skew: "px", translate: "px" }, cssPrefix = transforms.css, round = Math.round, BLANK = "", PX = "px", NONE = "none", AUTO = "auto", WIDTH = "width", HEIGHT = "height", HIDDEN = "hidden", ORIGIN = "origin", ABORT_ID = "abortId", OVERFLOW = "overflow", TRANSLATE = "translate", POSITION = "position", COMPLETE_CALLBACK = "completeCallback", TRANSITION = cssPrefix + "transition", TRANSFORM = cssPrefix + "transform", BACKFACE = cssPrefix + "backface-visibility", PERSPECTIVE = cssPrefix + "perspective", DEFAULT_PERSPECTIVE = "1500px", TRANSFORM_PERSPECTIVE = "perspective(" + DEFAULT_PERSPECTIVE + ")", directions = { left: { reverse: "right", property: "left", transition: "translatex", vertical: false, modifier: -1 }, right: { reverse: "left", property: "left", transition: "translatex", vertical: false, modifier: 1 }, down: { reverse: "up", property: "top", transition: "translatey", vertical: true, modifier: 1 }, up: { reverse: "down", property: "top", transition: "translatey", vertical: true, modifier: -1 }, top: { reverse: "bottom" }, bottom: { reverse: "top" }, "in": { reverse: "out", modifier: -1 }, out: { reverse: "in", modifier: 1 }, vertical: { reverse: "vertical" }, horizontal: { reverse: "horizontal" } }; kendo.directions = directions; extend($.fn, { kendoStop: function(clearQueue, gotoEnd) { if (transitions) { return fx.stopQueue(this, clearQueue || false, gotoEnd || false); } else { return this.stop(clearQueue, gotoEnd); } } }); /* jQuery support for all transform animations (FF 3.5/3.6, Opera 10.x, IE9 */ if (transforms && !transitions) { each(transform2d, function(idx, value) { $.fn[value] = function(val) { if (typeof val == "undefined") { return animationProperty(this, value); } else { var that = $(this)[0], transformValue = value + "(" + val + transform2units[value.replace(unitRegExp, "")] + ")"; if (that.style.cssText.indexOf(TRANSFORM) == -1) { $(this).css(TRANSFORM, transformValue); } else { that.style.cssText = that.style.cssText.replace(new RegExp(value + "\\(.*?\\)", "i"), transformValue); } } return this; }; $.fx.step[value] = function (fx) { $(fx.elem)[value](fx.now); }; }); var curProxy = $.fx.prototype.cur; $.fx.prototype.cur = function () { if (transform2d.indexOf(this.prop) != -1) { return parseFloat($(this.elem)[this.prop]()); } return curProxy.apply(this, arguments); }; } kendo.toggleClass = function(element, classes, options, add) { if (classes) { classes = classes.split(" "); if (transitions) { options = extend({ exclusive: "all", duration: 400, ease: "ease-out" }, options); element.css(TRANSITION, options.exclusive + " " + options.duration + "ms " + options.ease); setTimeout(function() { element.css(TRANSITION, "").css(HEIGHT); }, options.duration); // TODO: this should fire a kendoAnimate session instead. } each(classes, function(idx, value) { element.toggleClass(value, add); }); } return element; }; kendo.parseEffects = function(input, mirror) { var effects = {}; if (typeof input === "string") { each(input.split(" "), function(idx, value) { var redirectedEffect = !singleEffectRegExp.test(value), resolved = value.replace(oldEffectsRegExp, function(match, $1, $2) { return $1 + ":" + $2.toLowerCase(); }), // Support for old zoomIn/fadeOut style, now deprecated. effect = resolved.split(":"), direction = effect[1], effectBody = {}; if (effect.length > 1) { effectBody.direction = (mirror && redirectedEffect ? directions[direction].reverse : direction); } effects[effect[0]] = effectBody; }); } else { each(input, function(idx) { var direction = this.direction; if (direction && mirror && !singleEffectRegExp.test(idx)) { this.direction = directions[direction].reverse; } effects[idx] = this; }); } return effects; }; function parseInteger(value) { return parseInt(value, 10); } function parseCSS(element, property) { return parseInteger(element.css(property)); } function keys(obj) { var acc = []; for (var propertyName in obj) { acc.push(propertyName); } return acc; } function strip3DTransforms(properties) { for (var key in properties) { if (transformProps.indexOf(key) != -1 && transform2d.indexOf(key) == -1) { delete properties[key]; } } return properties; } function normalizeCSS(element, properties) { var transformation = [], cssValues = {}, lowerKey, key, value, isTransformed; for (key in properties) { lowerKey = key.toLowerCase(); isTransformed = transforms && transformProps.indexOf(lowerKey) != -1; if (!support.hasHW3D && isTransformed && transform2d.indexOf(lowerKey) == -1) { delete properties[key]; } else { value = properties[key]; if (isTransformed) { transformation.push(key + "(" + value + ")"); } else { cssValues[key] = value; } } } if (transformation.length) { cssValues[TRANSFORM] = transformation.join(" "); } return cssValues; } if (transitions) { extend(fx, { transition: function(element, properties, options) { var css, delay = 0, oldKeys = element.data("keys") || [], timeoutID; options = extend({ duration: 200, ease: "ease-out", complete: null, exclusive: "all" }, options ); var stopTransitionCalled = false; var stopTransition = function() { if (!stopTransitionCalled) { stopTransitionCalled = true; if (timeoutID) { clearTimeout(timeoutID); timeoutID = null; } element .removeData(ABORT_ID) .dequeue() .css(TRANSITION, "") .css(TRANSITION); options.complete.call(element); } }; options.duration = $.fx ? $.fx.speeds[options.duration] || options.duration : options.duration; css = normalizeCSS(element, properties); $.merge(oldKeys, keys(css)); element .data("keys", $.unique(oldKeys)) .height(); element.css(TRANSITION, options.exclusive + " " + options.duration + "ms " + options.ease).css(TRANSITION); element.css(css).css(TRANSFORM); /** * Use transitionEnd event for browsers who support it - but duplicate it with setTimeout, as the transitionEnd event will not be triggered if no CSS properties change. * This should be cleaned up at some point (widget by widget), and refactored to widgets not relying on the complete callback if no transition occurs. * * For IE9 and below, resort to setTimeout. */ if (transitions.event) { element.one(transitions.event, stopTransition); if (options.duration !== 0) { delay = 500; } } timeoutID = setTimeout(stopTransition, options.duration + delay); element.data(ABORT_ID, timeoutID); element.data(COMPLETE_CALLBACK, stopTransition); }, stopQueue: function(element, clearQueue, gotoEnd) { var cssValues, taskKeys = element.data("keys"), retainPosition = (!gotoEnd && taskKeys), completeCallback = element.data(COMPLETE_CALLBACK); if (retainPosition) { cssValues = kendo.getComputedStyles(element[0], taskKeys); } if (completeCallback) { completeCallback(); } if (retainPosition) { element.css(cssValues); } return element .removeData("keys") .stop(clearQueue); } }); } function animationProperty(element, property) { if (transforms) { var transform = element.css(TRANSFORM); if (transform == NONE) { return property == "scale" ? 1 : 0; } var match = transform.match(new RegExp(property + "\\s*\\(([\\d\\w\\.]+)")), computed = 0; if (match) { computed = parseInteger(match[1]); } else { match = transform.match(matrix3dRegExp) || [0, 0, 0, 0, 0]; property = property.toLowerCase(); if (translateXRegExp.test(property)) { computed = parseFloat(match[3] / match[2]); } else if (property == "translatey") { computed = parseFloat(match[4] / match[2]); } else if (property == "scale") { computed = parseFloat(match[2]); } else if (property == "rotate") { computed = parseFloat(Math.atan2(match[2], match[1])); } } return computed; } else { return parseFloat(element.css(property)); } } var EffectSet = kendo.Class.extend({ init: function(element, options) { var that = this; that.element = element; that.effects = []; that.options = options; that.restore = []; }, run: function(effects) { var that = this, effect, idx, jdx, length = effects.length, element = that.element, options = that.options, deferred = $.Deferred(), start = {}, end = {}, target, children, childrenLength; that.effects = effects; deferred.then($.proxy(that, "complete")); element.data("animating", true); for (idx = 0; idx < length; idx ++) { effect = effects[idx]; effect.setReverse(options.reverse); effect.setOptions(options); that.addRestoreProperties(effect.restore); effect.prepare(start, end); children = effect.children(); for (jdx = 0, childrenLength = children.length; jdx < childrenLength; jdx ++) { children[jdx].duration(options.duration).run(); } } // legacy support for options.properties for (var effectName in options.effects) { extend(end, options.effects[effectName].properties); } // Show the element initially if (!element.is(":visible")) { extend(start, { display: element.data("olddisplay") || "block" }); } if (transforms && !options.reset) { target = element.data("targetTransform"); if (target) { start = extend(target, start); } } start = normalizeCSS(element, start); if (transforms && !transitions) { start = strip3DTransforms(start); } element.css(start) .css(TRANSFORM); // Nudge for (idx = 0; idx < length; idx ++) { effects[idx].setup(); } if (options.init) { options.init(); } element.data("targetTransform", end); fx.animate(element, end, extend({}, options, { complete: deferred.resolve })); return deferred.promise(); }, stop: function() { $(this.element).kendoStop(true, true); }, addRestoreProperties: function(restore) { var element = this.element, value, i = 0, length = restore.length; for (; i < length; i ++) { value = restore[i]; this.restore.push(value); if (!element.data(value)) { element.data(value, element.css(value)); } } }, restoreCallback: function() { var element = this.element; for (var i = 0, length = this.restore.length; i < length; i ++) { var value = this.restore[i]; element.css(value, element.data(value)); } }, complete: function() { var that = this, idx = 0, element = that.element, options = that.options, effects = that.effects, length = effects.length; element .removeData("animating") .dequeue(); // call next animation from the queue if (options.hide) { element.data("olddisplay", element.css("display")).hide(); } this.restoreCallback(); if (hasZoom && !transforms) { setTimeout($.proxy(this, "restoreCallback"), 0); // Again jQuery callback in IE8- } for (; idx < length; idx ++) { effects[idx].teardown(); } if (options.completeCallback) { options.completeCallback(element); } } }); fx.promise = function(element, options) { var effects = [], effectClass, effectSet = new EffectSet(element, options), parsedEffects = kendo.parseEffects(options.effects), effect; options.effects = parsedEffects; for (var effectName in parsedEffects) { effectClass = fx[capitalize(effectName)]; if (effectClass) { effect = new effectClass(element, parsedEffects[effectName].direction); effects.push(effect); } } if (effects[0]) { effectSet.run(effects); } else { // Not sure how would an fx promise reach this state - means that you call kendoAnimate with no valid effects? Why? if (!element.is(":visible")) { element.css({ display: element.data("olddisplay") || "block" }).css("display"); } if (options.init) { options.init(); } element.dequeue(); effectSet.complete(); } }; extend(fx, { animate: function(elements, properties, options) { var useTransition = options.transition !== false; delete options.transition; if (transitions && "transition" in fx && useTransition) { fx.transition(elements, properties, options); } else { if (transforms) { elements.animate(strip3DTransforms(properties), { queue: false, show: false, hide: false, duration: options.duration, complete: options.complete }); // Stop animate from showing/hiding the element to be able to hide it later on. } else { elements.each(function() { var element = $(this), multiple = {}; each(transformProps, function(idx, value) { // remove transforms to avoid IE and older browsers confusion var params, currentValue = properties ? properties[value]+ " " : null; // We need to match if (currentValue) { var single = properties; if (value in scaleProperties && properties[value] !== undefined) { params = currentValue.match(cssParamsRegExp); if (transforms) { extend(single, { scale: +params[0] }); } } else { if (value in translateProperties && properties[value] !== undefined) { var position = element.css(POSITION), isFixed = (position == "absolute" || position == "fixed"); if (!element.data(TRANSLATE)) { if (isFixed) { element.data(TRANSLATE, { top: parseCSS(element, "top") || 0, left: parseCSS(element, "left") || 0, bottom: parseCSS(element, "bottom"), right: parseCSS(element, "right") }); } else { element.data(TRANSLATE, { top: parseCSS(element, "marginTop") || 0, left: parseCSS(element, "marginLeft") || 0 }); } } var originalPosition = element.data(TRANSLATE); params = currentValue.match(cssParamsRegExp); if (params) { var dX = value == TRANSLATE + "y" ? +null : +params[1], dY = value == TRANSLATE + "y" ? +params[1] : +params[2]; if (isFixed) { if (!isNaN(originalPosition.right)) { if (!isNaN(dX)) { extend(single, { right: originalPosition.right - dX }); } } else { if (!isNaN(dX)) { extend(single, { left: originalPosition.left + dX }); } } if (!isNaN(originalPosition.bottom)) { if (!isNaN(dY)) { extend(single, { bottom: originalPosition.bottom - dY }); } } else { if (!isNaN(dY)) { extend(single, { top: originalPosition.top + dY }); } } } else { if (!isNaN(dX)) { extend(single, { marginLeft: originalPosition.left + dX }); } if (!isNaN(dY)) { extend(single, { marginTop: originalPosition.top + dY }); } } } } } if (!transforms && value != "scale" && value in single) { delete single[value]; } if (single) { extend(multiple, single); } } }); if (browser.msie) { delete multiple.scale; } element.animate(multiple, { queue: false, show: false, hide: false, duration: options.duration, complete: options.complete }); // Stop animate from showing/hiding the element to be able to hide it later on. }); } } } }); fx.animatedPromise = fx.promise; var Effect = kendo.Class.extend({ init: function(element, direction) { var that = this; that.element = element; that._direction = direction; that.options = {}; that._additionalEffects = []; if (!that.restore) { that.restore = []; } }, // Public API reverse: function() { this._reverse = true; return this.run(); }, play: function() { this._reverse = false; return this.run(); }, add: function(additional) { this._additionalEffects.push(additional); return this; }, direction: function(value) { this._direction = value; return this; }, duration: function(duration) { this._duration = duration; return this; }, compositeRun: function() { var that = this, effectSet = new EffectSet(that.element, { reverse: that._reverse, duration: that._duration }), effects = that._additionalEffects.concat([ that ]); return effectSet.run(effects); }, run: function() { if (this._additionalEffects && this._additionalEffects[0]) { return this.compositeRun(); } var that = this, element = that.element, idx = 0, restore = that.restore, length = restore.length, value, deferred = $.Deferred(), start = {}, end = {}, target, children = that.children(), childrenLength = children.length; deferred.then($.proxy(that, "_complete")); element.data("animating", true); for (idx = 0; idx < length; idx ++) { value = restore[idx]; if (!element.data(value)) { element.data(value, element.css(value)); } } for (idx = 0; idx < childrenLength; idx ++) { children[idx].duration(that._duration).run(); } that.prepare(start, end); if (!element.is(":visible")) { extend(start, { display: element.data("olddisplay") || "block" }); } if (transforms) { target = element.data("targetTransform"); if (target) { start = extend(target, start); } } start = normalizeCSS(element, start); if (transforms && !transitions) { start = strip3DTransforms(start); } element.css(start).css(TRANSFORM); // Trick webkit into re-rendering that.setup(); element.data("targetTransform", end); fx.animate(element, end, { duration: that._duration, complete: deferred.resolve }); return deferred.promise(); }, stop: function() { var idx = 0, children = this.children(), childrenLength = children.length; for (idx = 0; idx < childrenLength; idx ++) { children[idx].stop(); } $(this.element).kendoStop(true, true); return this; }, restoreCallback: function() { var element = this.element; for (var i = 0, length = this.restore.length; i < length; i ++) { var value = this.restore[i]; element.css(value, element.data(value)); } }, _complete: function() { var that = this, element = that.element; element .removeData("animating") .dequeue(); // call next animation from the queue that.restoreCallback(); if (that.shouldHide()) { element.data("olddisplay", element.css("display")).hide(); } if (hasZoom && !transforms) { setTimeout($.proxy(that, "restoreCallback"), 0); // Again jQuery callback in IE8- } that.teardown(); }, /////////////////////////// Support for kendo.animate; setOptions: function(options) { extend(true, this.options, options); }, children: function() { return []; }, shouldHide: $.noop, setup: $.noop, prepare: $.noop, teardown: $.noop, directions: [], setReverse: function(reverse) { this._reverse = reverse; return this; } }); function capitalize(word) { return word.charAt(0).toUpperCase() + word.substring(1); } function createEffect(name, definition) { var effectClass = Effect.extend(definition), directions = effectClass.prototype.directions; fx[capitalize(name)] = effectClass; fx.Element.prototype[name] = function(direction, opt1, opt2, opt3) { return new effectClass(this.element, direction, opt1, opt2, opt3); }; each(directions, function(idx, theDirection) { fx.Element.prototype[name + capitalize(theDirection)] = function(opt1, opt2, opt3) { return new effectClass(this.element, theDirection, opt1, opt2, opt3); }; }); } var FOUR_DIRECTIONS = ["left", "right", "up", "down"], IN_OUT = ["in", "out"]; createEffect("slideIn", { directions: FOUR_DIRECTIONS, divisor: function(value) { this.options.divisor = value; return this; }, prepare: function(start, end) { var that = this, tmp, element = that.element, outerWidth = kendo._outerWidth, outerHeight = kendo._outerHeight, direction = directions[that._direction], offset = -direction.modifier * (direction.vertical ? outerHeight(element) : outerWidth(element)), startValue = offset / (that.options && that.options.divisor || 1) + PX, endValue = "0px"; if (that._reverse) { tmp = start; start = end; end = tmp; } if (transforms) { start[direction.transition] = startValue; end[direction.transition] = endValue; } else { start[direction.property] = startValue; end[direction.property] = endValue; } } }); createEffect("tile", { directions: FOUR_DIRECTIONS, init: function(element, direction, previous) { Effect.prototype.init.call(this, element, direction); this.options = { previous: previous }; }, previousDivisor: function(value) { this.options.previousDivisor = value; return this; }, children: function() { var that = this, reverse = that._reverse, previous = that.options.previous, divisor = that.options.previousDivisor || 1, dir = that._direction; var children = [ kendo.fx(that.element).slideIn(dir).setReverse(reverse) ]; if (previous) { children.push( kendo.fx(previous).slideIn(directions[dir].reverse).divisor(divisor).setReverse(!reverse) ); } return children; } }); function createToggleEffect(name, property, defaultStart, defaultEnd) { createEffect(name, { directions: IN_OUT, startValue: function(value) { this._startValue = value; return this; }, endValue: function(value) { this._endValue = value; return this; }, shouldHide: function() { return this._shouldHide; }, prepare: function(start, end) { var that = this, startValue, endValue, out = this._direction === "out", startDataValue = that.element.data(property), startDataValueIsSet = !(isNaN(startDataValue) || startDataValue == defaultStart); if (startDataValueIsSet) { startValue = startDataValue; } else if (typeof this._startValue !== "undefined") { startValue = this._startValue; } else { startValue = out ? defaultStart : defaultEnd; } if (typeof this._endValue !== "undefined") { endValue = this._endValue; } else { endValue = out ? defaultEnd : defaultStart; } if (this._reverse) { start[property] = endValue; end[property] = startValue; } else { start[property] = startValue; end[property] = endValue; } that._shouldHide = end[property] === defaultEnd; } }); } createToggleEffect("fade", "opacity", 1, 0); createToggleEffect("zoom", "scale", 1, 0.01); createEffect("slideMargin", { prepare: function(start, end) { var that = this, element = that.element, options = that.options, origin = element.data(ORIGIN), offset = options.offset, margin, reverse = that._reverse; if (!reverse && origin === null) { element.data(ORIGIN, parseFloat(element.css("margin-" + options.axis))); } margin = (element.data(ORIGIN) || 0); end["margin-" + options.axis] = !reverse ? margin + offset : margin; } }); createEffect("slideTo", { prepare: function(start, end) { var that = this, element = that.element, options = that.options, offset = options.offset.split(","), reverse = that._reverse; if (transforms) { end.translatex = !reverse ? offset[0] : 0; end.translatey = !reverse ? offset[1] : 0; } else { end.left = !reverse ? offset[0] : 0; end.top = !reverse ? offset[1] : 0; } element.css("left"); } }); createEffect("expand", { directions: ["horizontal", "vertical"], restore: [ OVERFLOW ], prepare: function(start, end) { var that = this, element = that.element, options = that.options, reverse = that._reverse, property = that._direction === "vertical" ? HEIGHT : WIDTH, setLength = element[0].style[property], oldLength = element.data(property), length = parseFloat(oldLength || setLength), realLength = round(element.css(property, AUTO)[property]()); start.overflow = HIDDEN; length = (options && options.reset) ? realLength || length : length || realLength; end[property] = (reverse ? 0 : length) + PX; start[property] = (reverse ? length : 0) + PX; if (oldLength === undefined) { element.data(property, setLength); } }, shouldHide: function() { return this._reverse; }, teardown: function() { var that = this, element = that.element, property = that._direction === "vertical" ? HEIGHT : WIDTH, length = element.data(property); if (length == AUTO || length === BLANK) { setTimeout(function() { element.css(property, AUTO).css(property); }, 0); // jQuery animate complete callback in IE is called before the last animation step! } } }); var TRANSFER_START_STATE = { position: "absolute", marginLeft: 0, marginTop: 0, scale: 1 }; /** * Intersection point formulas are taken from here - http://zonalandeducation.com/mmts/intersections/intersectionOfTwoLines1/intersectionOfTwoLines1.html * Formula for a linear function from two points from here - http://demo.activemath.org/ActiveMath2/search/show.cmd?id=mbase://AC_UK_calculus/functions/ex_linear_equation_two_points * The transform origin point is the intersection point of the two lines from the top left corners/top right corners of the element and target. * The math and variables below MAY BE SIMPLIFIED (zeroes removed), but this would make the formula too cryptic. */ createEffect("transfer", { init: function(element, target) { this.element = element; this.options = { target: target }; this.restore = []; }, setup: function() { this.element.appendTo(document.body); }, prepare: function(start, end) { var that = this, element = that.element, outerBox = fx.box(element), innerBox = fx.box(that.options.target), currentScale = animationProperty(element, "scale"), scale = fx.fillScale(innerBox, outerBox), transformOrigin = fx.transformOrigin(innerBox, outerBox); extend(start, TRANSFER_START_STATE); end.scale = 1; element.css(TRANSFORM, "scale(1)").css(TRANSFORM); element.css(TRANSFORM, "scale(" + currentScale + ")"); start.top = outerBox.top; start.left = outerBox.left; start.transformOrigin = transformOrigin.x + PX + " " + transformOrigin.y + PX; if (that._reverse) { start.scale = scale; } else { end.scale = scale; } } }); var CLIPS = { top: "rect(auto auto $size auto)", bottom: "rect($size auto auto auto)", left: "rect(auto $size auto auto)", right: "rect(auto auto auto $size)" }; var ROTATIONS = { top: { start: "rotatex(0deg)", end: "rotatex(180deg)" }, bottom: { start: "rotatex(-180deg)", end: "rotatex(0deg)" }, left: { start: "rotatey(0deg)", end: "rotatey(-180deg)" }, right: { start: "rotatey(180deg)", end: "rotatey(0deg)" } }; function clipInHalf(container, direction) { var vertical = kendo.directions[direction].vertical, size = (container[vertical ? HEIGHT : WIDTH]() / 2) + "px"; return CLIPS[direction].replace("$size", size); } createEffect("turningPage", { directions: FOUR_DIRECTIONS, init: function(element, direction, container) { Effect.prototype.init.call(this, element, direction); this._container = container; }, prepare: function(start, end) { var that = this, reverse = that._reverse, direction = reverse ? directions[that._direction].reverse : that._direction, rotation = ROTATIONS[direction]; start.zIndex = 1; if (that._clipInHalf) { start.clip = clipInHalf(that._container, kendo.directions[direction].reverse); } start[BACKFACE] = HIDDEN; end[TRANSFORM] = TRANSFORM_PERSPECTIVE + (reverse ? rotation.start : rotation.end); start[TRANSFORM] = TRANSFORM_PERSPECTIVE + (reverse ? rotation.end : rotation.start); }, setup: function() { this._container.append(this.element); }, face: function(value) { this._face = value; return this; }, shouldHide: function() { var that = this, reverse = that._reverse, face = that._face; return (reverse && !face) || (!reverse && face); }, clipInHalf: function(value) { this._clipInHalf = value; return this; }, temporary: function() { this.element.addClass('temp-page'); return this; } }); createEffect("staticPage", { directions: FOUR_DIRECTIONS, init: function(element, direction, container) { Effect.prototype.init.call(this, element, direction); this._container = container; }, restore: ["clip"], prepare: function(start, end) { var that = this, direction = that._reverse ? directions[that._direction].reverse : that._direction; start.clip = clipInHalf(that._container, direction); start.opacity = 0.999; end.opacity = 1; }, shouldHide: function() { var that = this, reverse = that._reverse, face = that._face; return (reverse && !face) || (!reverse && face); }, face: function(value) { this._face = value; return this; } }); createEffect("pageturn", { directions: ["horizontal", "vertical"], init: function(element, direction, face, back) { Effect.prototype.init.call(this, element, direction); this.options = {}; this.options.face = face; this.options.back = back; }, children: function() { var that = this, options = that.options, direction = that._direction === "horizontal" ? "left" : "top", reverseDirection = kendo.directions[direction].reverse, reverse = that._reverse, temp, faceClone = options.face.clone(true).removeAttr("id"), backClone = options.back.clone(true).removeAttr("id"), element = that.element; if (reverse) { temp = direction; direction = reverseDirection; reverseDirection = temp; } return [ kendo.fx(options.face).staticPage(direction, element).face(true).setReverse(reverse), kendo.fx(options.back).staticPage(reverseDirection, element).setReverse(reverse), kendo.fx(faceClone).turningPage(direction, element).face(true).clipInHalf(true).temporary().setReverse(reverse), kendo.fx(backClone).turningPage(reverseDirection, element).clipInHalf(true).temporary().setReverse(reverse) ]; }, prepare: function(start, end) { start[PERSPECTIVE] = DEFAULT_PERSPECTIVE; start.transformStyle = "preserve-3d"; // hack to trigger transition end. start.opacity = 0.999; end.opacity = 1; }, teardown: function() { this.element.find(".temp-page").remove(); } }); createEffect("flip", { directions: ["horizontal", "vertical"], init: function(element, direction, face, back) { Effect.prototype.init.call(this, element, direction); this.options = {}; this.options.face = face; this.options.back = back; }, children: function() { var that = this, options = that.options, direction = that._direction === "horizontal" ? "left" : "top", reverseDirection = kendo.directions[direction].reverse, reverse = that._reverse, temp, element = that.element; if (reverse) { temp = direction; direction = reverseDirection; reverseDirection = temp; } return [ kendo.fx(options.face).turningPage(direction, element).face(true).setReverse(reverse), kendo.fx(options.back).turningPage(reverseDirection, element).setReverse(reverse) ]; }, prepare: function(start) { start[PERSPECTIVE] = DEFAULT_PERSPECTIVE; start.transformStyle = "preserve-3d"; } }); var RESTORE_OVERFLOW = !support.mobileOS.android; var IGNORE_TRANSITION_EVENT_SELECTOR = ".km-touch-scrollbar, .km-actionsheet-wrapper"; createEffect("replace", { _before: $.noop, _after: $.noop, init: function(element, previous, transitionClass) { Effect.prototype.init.call(this, element); this._previous = $(previous); this._transitionClass = transitionClass; }, duration: function() { throw new Error("The replace effect does not support duration setting; the effect duration may be customized through the transition class rule"); }, beforeTransition: function(callback) { this._before = callback; return this; }, afterTransition: function(callback) { this._after = callback; return this; }, _both: function() { return $().add(this._element).add(this._previous); }, _containerClass: function() { var direction = this._direction, containerClass = "k-fx k-fx-start k-fx-" + this._transitionClass; if (direction) { containerClass += " k-fx-" + direction; } if (this._reverse) { containerClass += " k-fx-reverse"; } return containerClass; }, complete: function(e) { if (!this.deferred || (e && $(e.target).is(IGNORE_TRANSITION_EVENT_SELECTOR))) { return; } var container = this.container; container .removeClass("k-fx-end") .removeClass(this._containerClass()) .off(transitions.event, this.completeProxy); this._previous.hide().removeClass("k-fx-current"); this.element.removeClass("k-fx-next"); if (RESTORE_OVERFLOW) { container.css(OVERFLOW, ""); } if (!this.isAbsolute) { this._both().css(POSITION, ""); } this.deferred.resolve(); delete this.deferred; }, run: function() { if (this._additionalEffects && this._additionalEffects[0]) { return this.compositeRun(); } var that = this, element = that.element, previous = that._previous, container = element.parents().filter(previous.parents()).first(), both = that._both(), deferred = $.Deferred(), originalPosition = element.css(POSITION), originalOverflow; // edge case for grid/scheduler, where the previous is already destroyed. if (!container.length) { container = element.parent(); } this.container = container; this.deferred = deferred; this.isAbsolute = originalPosition == "absolute"; if (!this.isAbsolute) { both.css(POSITION, "absolute"); } if (RESTORE_OVERFLOW) { originalOverflow = container.css(OVERFLOW); container.css(OVERFLOW, "hidden"); } if (!transitions) { this.complete(); } else { element.addClass("k-fx-hidden"); container.addClass(this._containerClass()); this.completeProxy = $.proxy(this, "complete"); container.on(transitions.event, this.completeProxy); kendo.animationFrame(function() { element.removeClass("k-fx-hidden").addClass("k-fx-next"); previous.css("display", "").addClass("k-fx-current"); that._before(previous, element); kendo.animationFrame(function() { container.removeClass("k-fx-start").addClass("k-fx-end"); that._after(previous, element); }); }); } return deferred.promise(); }, stop: function() { this.complete(); } }); var Animation = kendo.Class.extend({ init: function() { var that = this; that._tickProxy = proxy(that._tick, that); that._started = false; }, tick: $.noop, done: $.noop, onEnd: $.noop, onCancel: $.noop, start: function() { if (!this.enabled()) { return; } if (!this.done()) { this._started = true; kendo.animationFrame(this._tickProxy); } else { this.onEnd(); } }, enabled: function() { return true; }, cancel: function() { this._started = false; this.onCancel(); }, _tick: function() { var that = this; if (!that._started) { return; } that.tick(); if (!that.done()) { kendo.animationFrame(that._tickProxy); } else { that._started = false; that.onEnd(); } } }); var Transition = Animation.extend({ init: function(options) { var that = this; extend(that, options); Animation.fn.init.call(that); }, done: function() { return this.timePassed() >= this.duration; }, timePassed: function() { return Math.min(this.duration, (new Date()) - this.startDate); }, moveTo: function(options) { var that = this, movable = that.movable; that.initial = movable[that.axis]; that.delta = options.location - that.initial; that.duration = typeof options.duration == "number" ? options.duration : 300; that.tick = that._easeProxy(options.ease); that.startDate = new Date(); that.start(); }, _easeProxy: function(ease) { var that = this; return function() { that.movable.moveAxis(that.axis, ease(that.timePassed(), that.initial, that.delta, that.duration)); }; } }); extend(Transition, { easeOutExpo: function (t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeOutBack: function (t, b, c, d, s) { s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; } }); fx.Animation = Animation; fx.Transition = Transition; fx.createEffect = createEffect; fx.box = function(element) { element = $(element); var result = element.offset(); result.width = kendo._outerWidth(element); result.height = kendo._outerHeight(element); return result; }; fx.transformOrigin = function(inner, outer) { var x = (inner.left - outer.left) * outer.width / (outer.width - inner.width), y = (inner.top - outer.top) * outer.height / (outer.height - inner.height); return { x: isNaN(x) ? 0 : x, y: isNaN(y) ? 0 : y }; }; fx.fillScale = function(inner, outer) { return Math.min(inner.width / outer.width, inner.height / outer.height); }; fx.fitScale = function(inner, outer) { return Math.max(inner.width / outer.width, inner.height / outer.height); }; })(window.kendo.jQuery); return window.kendo; }, __webpack_require__(3)); /***/ }) /******/ });
ScalaJS.impls.scala_Function2$mcJDI$sp$class__$init$__Lscala_Function2$mcJDI$sp__V = (function($$this) { /*<skip>*/ }); //@ sourceMappingURL=Function2$mcJDI$sp$class.js.map
module.exports = { 'rules': { 'strict': ['error', 'global'], }, }
/** * Created by Brennon Bortz on 8/6/14. */ 'use strict'; // Server var server = require('../../../server'); var app; // Config module var config = require('../../../config/config'); // Testing tools var request = require('supertest'); var should = require('chai').should(); describe('Core Controller Tests', function() { before(function(done) { server.then(function(startedApp) { app = startedApp; done(); }); }); describe('sessions', function() { var agent = request.agent('localhost:' + config.port); var cookieA, cookieB; it('should be in use', function(done) { agent .get('/') .expect('set-cookie', /connect\.sid.*/) .end(function(err, res) { if (err) { return done(err); } cookieA = res.header['set-cookie']; done(); }); }); it('should be reset on any visit to the index', function(done) { agent .get('/') .expect('set-cookie', /connect\.sid.*/) .end(function(err, res) { if (err) { return done(err); } cookieB = res.header['set-cookie']; cookieA.should.not.equal(cookieB); done(); }); }); }); });
"use strict"; class Scene { constructor(canvasId, presentBtnId) { /* const */ this.DISTANCE = 40.0; this.webglCanvas = document.getElementById(canvasId); this.presentBtn = document.getElementById(presentBtnId); this.vrDisplay = null; this.gl = this.webglCanvas.getContext("webgl"); this.projectionMat = mat4.create(); this.viewMat = mat4.create(); this.modelViewMat = mat4.create(); this.modelMat = mat4.create(); let options = { lines: WGLUUrl.getBool("lines", false), vertexShader: WGLUUrl.getString("vertex", "waves2"), fragmentShader: WGLUUrl.getString("fragment", "normal"), texture: WGLUUrl.getString("texture", "normal") }; let rows = WGLUUrl.getInt("rows", 80); this.ocean = new Ocean(this.gl, rows, 100.0, options); this.init(); this.initWebVr(); } init() { this.gl.enable(this.gl.DEPTH_TEST); this.gl.clearColor(0.53, 0.81, 0.98, 1.0); let eye = vec3.create(); vec3.set(eye, 0, 0, 0); let target = vec3.create(); vec3.set(target, 0, -this.DISTANCE / 2.0, -this.DISTANCE); let up = vec3.create(); vec3.set(up, 0, 1, 0); mat4.lookAt(this.viewMat, eye, target, up); } initWebVr() { if (navigator.getVRDisplays) { this.frameData = new VRFrameData(); navigator.getVRDisplays().then((function(displays) { if (displays.length > 0) { this.vrDisplay = displays[displays.length - 1]; this.vrDisplay.depthNear = 0.1; this.vrDisplay.depthFar = 1024.0; if (this.vrDisplay.capabilities.canPresent) { this.presentBtn.style.display = "block"; this.presentBtn.addEventListener("click", this.onVrRequestPresent.bind(this)); } window.addEventListener('vrdisplaypresentchange', this.onVrPresentChange.bind(this), false); window.addEventListener('vrdisplayactivate', this.onVrRequestPresent.bind(this), false); window.addEventListener('vrdisplaydeactivate', this.onVrExitPresent.bind(this), false); } else { console.log("WebVr supported, but no VRDisplays found."); } }).bind(this)); } else { console.log("WebVr not supported"); } } onVrRequestPresent() { this.vrDisplay.requestPresent([{source: this.webglCanvas}]).then( function() {}, function (err) { let errMsg = "requestPresent failed."; if (err && err.message) { errMsg += " " + err.message; } console.log(errMsg); }); } onVrExitPresent() { if (!this.vrDisplay.isPresenting) return; this.vrDisplay.exitPresent().then( function() {}, function (err) { let errMsg = "exitPresent failed."; if (err && err.message) { errMsg += " " + err.message } console.log(errMsg); }); } onVrPresentChange() { this.onResize(); if (this.vrDisplay.isPresenting) { this.presentBtn.style.display = "none"; } else { this.presentBtn.style.display = "block"; } } onResize() { if (this.vrDisplay && this.vrDisplay.isPresenting) { let leftEye = this.vrDisplay.getEyeParameters("left"); let rightEye = this.vrDisplay.getEyeParameters("right"); this.webglCanvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2; this.webglCanvas.height = Math.max(leftEye.renderHeight, rightEye.renderHeight); } else { this.webglCanvas.width = this.webglCanvas.offsetWidth * window.devicePixelRatio; this.webglCanvas.height = this.webglCanvas.offsetHeight * window.devicePixelRatio; } } onAnimationFrame(time) { let gl = this.gl; gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT); mat4.identity(this.modelMat); mat4.translate(this.modelMat, this.modelMat, [0, -this.DISTANCE, 0]); if (this.vrDisplay) { this.vrDisplay.requestAnimationFrame(this.onAnimationFrame.bind(this)); this.vrDisplay.getFrameData(this.frameData); if (this.vrDisplay.isPresenting) { gl.viewport(0, 0, this.webglCanvas.width * 0.5, this.webglCanvas.height); this.ocean.render(this.frameData.leftProjectionMatrix, this.frameData.leftViewMatrix, this.modelMat, time / 1000.0); gl.viewport(this.webglCanvas.width * 0.5, 0, this.webglCanvas.width * 0.5, this.webglCanvas.height); this.ocean.render(this.frameData.rightProjectionMatrix, this.frameData.rightViewMatrix, this.modelMat, time / 1000.0); this.vrDisplay.submitFrame(); } else { gl.viewport(0, 0, this.webglCanvas.width, this.webglCanvas.height); mat4.perspective(this.projectionMat, Math.PI * 0.4, this.webglCanvas.width / this.webglCanvas.height, 0.1, 1024.0); this.ocean.render(this.projectionMat, this.frameData.leftViewMatrix, this.modelMat, time / 1000.0); } } else { window.requestAnimationFrame(this.onAnimationFrame.bind(this)); gl.viewport(0, 0, this.webglCanvas.width, this.webglCanvas.height); mat4.perspective(this.projectionMat, Math.PI * 0.4, this.webglCanvas.width / this.webglCanvas.height, 0.1, 1024.0); this.ocean.render(this.projectionMat, this.viewMat, this.modelMat, time / 1000.0); } } } window.onload = function () { let scene = new Scene("webgl-canvas", "present-btn"); scene.onResize(); window.addEventListener("resize", scene.onResize.bind(scene), false); window.requestAnimationFrame(scene.onAnimationFrame.bind(scene)); };
(function(d,c){c.Tablecols=Class.extend({dropdown:!1,table:!1,headers:!1,columns:!1,keystorage:"",tml:'<li class="checkbox"><label><input type="checkbox" value="%%index%%" %%checked%% />%%title%%</label></li>',init:function(a,b){this.dropdown=d(a);this.table=this.dropdown.parent().find("table:first");this.headers=this.table.find("tr:first");this.keystorage=this.getkeystorage();"DataStorage"in c?this.load():d.load_script(ltoptions.files+"/js/litepubl/system/storage.min.js",d.proxy(this.load,this)); b&&(this.tml=b);this.init_dropdown()},set:function(a,b){this.columns[b++]=a;this.table.find("td:nth-child("+b+"),th:nth-child("+b+")")[a?"addClass":"removeClass"]("hidden")},load:function(){var a=c.getdatastorage().get(this.keystorage);if(a){this.columns=a;for(var b=0;b<a.length;b++)this.set(a[b],b)}else a=this.headers.find("th"),this.columns=[],this.columns.length=a.length},save:function(){c.getdatastorage().set(this.keystorage,this.columns)},getkeystorage:function(){var a="tablecols";ltoptions.idurl&& (a+=ltoptions.idurl);return a},init_dropdown:function(){var a=this;this.dropdown.find("button").dropdown().off("click.bs.dropdown").on("click.tablecols",function(){var b=d(this),c=b.parent();c.hasClass("open")||c.find(".dropdown-menu").html(a.getmenu());b.dropdown("toggle");return!1});this.dropdown.find(".dropdown-menu").on("click.tablecols",function(b){b.stopPropagation();b=d(b.target);b.is("[type=checkbox]")&&(a.set(!b.prop("checked"),b.val()),a.save())})},getmenu:function(){var a="",b=this.tml, c=this.columns;this.headers.find("th").each(function(e){var f=d(this);f.hasClass("col-checkbox")||(a+=d.parsetml(b,{index:e,title:f.text(),checked:c[e]?"":'checked="checked"'}))});return a}})})(jQuery,litepubl);
(function(){ // Manager (static) ppc.manager = cloz(base, { init: function(){ try { ppc.logger.get('add', 'PPCの初期化を開始しました', 0, 'start initialization'); // 最大同時接続数を設定 ppc.user.set('connections', ppc.parser.created.get('val', 'connections')); // 測定日時を設定 var now = (new Date()).getTime() + (new Date()).getTimezoneOffset() * 60 * 1000 + 540 * 60 * 1000; ppc.user.set('now', now); // 環境設定から最大測定対象数を取得 var max_illusts = Number(ppc.parser.created.get('val', 'max_illusts')); // 最大測定対象数が測定対象上限数を上回っている場合、測定対象上限数丸める if (max_illusts > ppc.admin.get('max_illusts')) { ppc.user.set('illusts', ppc.admin.get('max_illusts')); } // 最大測定対象数が測定対象下限数を下回っている場合、測定対象下限数に丸める if (max_illusts < ppc.admin.get('min_illusts')) { ppc.user.set('illusts', ppc.admin.get('min_illusts')); } // 測定するイラスト数を設定 var illusts = ppc.user.set('illusts', ppc.parser.home.get('length', 'illust')); // 最大測定対象数より表示されているイラストが多い場合、最大測定対象数に丸める if (illusts > max_illusts) { ppc.user.set('illusts', max_illusts); } // イラスト投稿数が0または正しく取得できなかった場合、処理を停止 if (!ppc.user.get('illusts')) { ppc.logger.get('add', '作品投稿数が取得できませんでした', 3); return false; } // 各イラストについてオブジェクトを生成し、配列に格納 var box = {}; // ID重複確認用 for (var i = 0; i < ppc.user.get('illusts'); i++) { var id = ppc.parser.home.get('illust_id', i); if (!isFinite(id)) { ppc.logger.get('add', '作品のIDが取得できませんでした (index = ' + i + ')', 3); return false; } ppc.logger.get('add', 'イラストのIDを取得しました => ' + id + ' (index = ' + i + ')', 0); for (var k in box) { if (box[k] == id) { ppc.logger.get('add', '作品IDの競合が検出されました', 3); return false; } } box[i] = id; var ins = cloz(ppc.illust, { id: id, }); ppc.illusts[i] = ins; } ppc.logger.get('add', 'PPCの初期化を完了しました', 0, 'end initialization'); return true; } catch (e) { ppc.logger.get('error', e); } }, run: function(){ ppc.logger.get('add', '測定を開始しました', 0, 'start analyzing'); // タブを切り替える ppc.parser.created.get('jq', 'tab_group').tabs({ disabled: [2], }).tabs('option', 'active', 1); if (!ppc.ajax.illust.get('init')) { return false; } if (!ppc.ajax.illust.get('run')) { return false; } return true; }, finish: function(){ ppc.logger.get('add', '測定を完了しました', 0, 'end analyzing'); if (!this.get('_process')) { return false; } return true; }, _process: function(){ ppc.logger.get('add', 'データ処理を開始しました', 0); try { for (var i = 0; i < ppc.user.get('illusts'); i++) { $html = ppc.illusts[i].get('jq'); // イラストごとにオブジェクトを継承 ppc.parser.illust.illusts[i] = cloz(ppc.parser.illust, { $doc: $html, $image_response: null, }); } // イラスト情報の登録 for (var j = 0; j < ppc.user.get('illusts'); j++) { var illust = ppc.illusts[j], parser = ppc.parser.illust.illusts[j]; // ID・サムネイル var id = ppc.parser.home.get('illust_id', j), $thumbnail = ppc.parser.home.get('$illust_thumbnail', j); illust.set('id', id); illust.set('$thumbnail', $thumbnail); // タイトル var title = parser.get('text', 'title'); illust.set('title', title); // 総合ブックマーク数・公開ブックマーク数・非公開ブックマーク数 var $bookmarked = parser.get('jq', 'bookmarked'), $bookmarked_total = parser.get('jq', 'bookmarked_total'), bookmarked_total = 0, bookmarked_public = 0, bookmarked_private = 0; // 1つ以上のブックマークがある場合 if ($bookmarked_total.length) { bookmarked_total = $bookmarked_total.text().number(0); } // 1つ以上の公開ブックマークがある場合 if ($bookmarked.length) { var bookmarked = $bookmarked.text().number(null); // 公開ブックマークしかない場合 if (bookmarked.length < 3) { bookmarked_public = bookmarked_total; } // 非公開ブックマークがある場合 else { bookmarked_public = bookmarked[1].number(0); bookmarked_private = bookmarked[2].number(0); } } // 公開ブックマークがない場合 else { bookmarked_private = bookmarked_total; } illust.set('bookmarked_total', bookmarked_total); illust.set('bookmarked_public', bookmarked_public); illust.set('bookmarked_private', bookmarked_private); illust.set('bookmarked_public_ratio', ppc.math.get('div', bookmarked_public * 100, bookmarked_total)); // 評価回数・総合点・コメント数・閲覧数 var rated = ppc.parser.home.get('illust_figures', j, 'rating-count'), scored = ppc.parser.home.get('illust_figures', j, 'score'), commented = ppc.parser.home.get('illust_figures', j, 'comments'), viewed = ppc.parser.home.get('illust_figures', j, 'views'); illust.set('rated', rated); illust.set('scored', scored); illust.set('commented', commented); illust.set('viewed', viewed); illust.set('scored_average', ppc.math.get('div', scored, rated)); illust.set('rated_ratio', ppc.math.get('div', rated * 100, viewed)); illust.set('bookmarked_ratio', ppc.math.get('div', bookmarked_total * 100, viewed)); // 投稿日時 var timestamp = parser.get('text', 'datetime'), timestamp_a = timestamp.number(null), datetime = new Date(timestamp_a[0], timestamp_a[1] - 1, timestamp_a[2], timestamp_a[3], timestamp_a[4], timestamp_a[5], 0), timestamp_b = timestamp.split(' '), date = timestamp_b[0], time = timestamp_b[1], milliseconds = datetime.getTime(), interval = ppc.user.get('now') - milliseconds; illust.set({ timestamp: timestamp, date: date, time: time, milliseconds: milliseconds, interval: interval, // ミリ秒単位の経過時間 interval_days: interval / (1000 * 60 * 60 * 24), // 日単位の経過時間 }); // HOT var hot = ppc.math.get('div', viewed, interval / (1000 * 60 * 60 * 24)); illust.set('hot', hot); // イメレスbadge $image_response = parser.get('jq', 'image_response'); illust.set('$image_response', $image_response); // タグ $tags = parser.get('jq', 'tags'); illust.set('$tags', $tags); // タグ数 tags_num_total = parser.get('length', 'tags_num_total'); tags_num_self = parser.get('length', 'tags_num_self'); illust.set({ tags_num_total: tags_num_total, tags_num_self: tags_num_self, }); // 最新ブックマーク $bookmarked_latest = parser.get('jq', 'bookmarked_latest'); illust.set('$bookmarked_latest', $bookmarked_latest); } // ユーザーID(数字)・ニックネーム・投稿数 var user_name = ppc.parser.illust.illusts[0].get('text', 'user_name'), posted = ppc.parser.home.get('text', 'posted').number(0); ppc.user.set({ nickname: user_name, posted: posted, }); this.get('_calc'); } catch (e){ ppc.logger.get('error', e); return false; } ppc.logger.get('add', 'データ処理を完了しました', 0); }, _calc: function(){ ppc.logger.get('add', '計算を開始しました'); // 各パラメータ合計 var rated_sum = ppc.math.get('sum', ppc.illusts, 'rated'), scored_sum = ppc.math.get('sum', ppc.illusts, 'scored'), commented_sum = ppc.math.get('sum', ppc.illusts, 'commented'), viewed_sum = ppc.math.get('sum', ppc.illusts, 'viewed'), bookmarked_sum = ppc.math.get('sum', ppc.illusts, 'bookmarked_total'), bookmarked_public_sum = ppc.math.get('sum', ppc.illusts, 'bookmarked_public'), hot_sum = ppc.math.get('sum', ppc.illusts, 'hot'); ppc.user.set({ rated_sum: rated_sum, scored_sum: scored_sum, commented_sum: commented_sum, viewed_sum: viewed_sum, bookmarked_sum: bookmarked_sum, bookmarked_public_sum: bookmarked_public_sum, hot_sum: hot_sum | 0, }); try { var now = ppc.user.get('now'), illusts = ppc.user.get('illusts'), followers = ppc.user.get('followers'), my_pixiv = ppc.user.get('my_pixiv'), total_power = 0, pixiv_power = 0; var index_last = illusts - 1, interval_longest = (now - ppc.illusts[index_last].get('milliseconds')) / (1000 * 60 * 60 * 24); var interval_average = interval_longest / illusts; ppc.user.set({ interval_longest: interval_longest, interval_average: interval_average.toFixed(1), }); for (var i = 0; i < illusts; i++) { var illust = ppc.illusts[i], interval = illust.get('interval'), freshment = ppc.math.get('freshment', interval_average, interval), power = 0, bt = illust.get('bookmarked_total'), bpb = illust.get('bookmarked_public'), bpr = illust.get('bookmarked_private'), r = illust.get('rated'), s = illust.get('scored'), c = illust.get('commented'), v = illust.get('viewed'); if (v) { power = c * 10; power += v; power += bt * bpb * 1000 / v; if (r) { power += s * s / r; } power *= freshment; power = Math.round(power); total_power += power; } illust.set({ freshment: freshment, power: power, }); // Elements var elements = [ ['現在', null], ['閲覧', v], ['評価', r], ['点', s], ['ブクマ', bt], ['日', illust.get('interval_days')], ['パワー', power] ]; illust.set('elements', elements); } pixiv_power = ppc.math.get('pixivPower', followers, my_pixiv, total_power, hot_sum); ppc.user.set({ total_power: Math.ceil(total_power), pixiv_power: Math.ceil(pixiv_power), }); } catch (e) { ppc.logger.get('error', e); return false; } ppc.logger.get('add', '計算を完了しました'); this.get('result'); }, result: function(){ ppc.logger.get('add', '結果表示を開始しました', 0); ppc.renderer.get('remove', '#processing,#processing-description'); if (!ppc.old.get('result')) { return false; } ppc.logger.get('add', '結果表示を終了しました', 0); }, }); })();
modulex.add("event-custom", ["modulex-event-base","modulex-util"], function(require, exports, module) { var modulexEventBase = require("modulex-event-base"); var modulexUtil = require("modulex-util"); /* combined modules: event-custom event-custom/target event-custom/observable event-custom/observer event-custom/object */ var eventCustomObserver, eventCustomObject, eventCustomObservable, eventCustomTarget, eventCustom; eventCustomObserver = function (exports) { exports = {}; /** * @ignore * Observer for custom event * @author yiminghe@gmail.com */ var BaseEvent = modulexEventBase; var util = modulexUtil; /** * Observer for custom event * @class CustomEvent.Observer * @extends Event.Observer * @private */ function CustomEventObserver() { CustomEventObserver.superclass.constructor.apply(this, arguments); } util.extend(CustomEventObserver, BaseEvent.Observer, { keys: [ 'fn', 'context', 'groups' ] }); exports = CustomEventObserver; return exports; }(); eventCustomObject = function (exports) { exports = {}; /** * @ignore * simple custom event object for custom event mechanism. * @author yiminghe@gmail.com */ var BaseEvent = modulexEventBase; var util = modulexUtil; /** * Do not new by yourself. * * Custom event object. * @private * @class CustomEvent.Object * @param {Object} data data which will be mixed into custom event instance * @extends Event.Object */ function CustomEventObject(data) { CustomEventObject.superclass.constructor.call(this); util.mix(this, data); } util.extend(CustomEventObject, BaseEvent.Object); exports = CustomEventObject; return exports; }(); eventCustomObservable = function (exports) { exports = {}; var BaseEvent = modulexEventBase; var CustomEventObserver = eventCustomObserver; var CustomEventObject = eventCustomObject; var Utils = BaseEvent.Utils; var util = modulexUtil; function CustomEventObservable() { var self = this; CustomEventObservable.superclass.constructor.apply(self, arguments); self.defaultFn = null; self.defaultTargetOnly = false; self.bubbles = true; } util.extend(CustomEventObservable, BaseEvent.Observable, { on: function (cfg) { var observer = new CustomEventObserver(cfg); if (this.findObserver(observer) === -1) { this.observers.push(observer); } }, fire: function (eventData) { eventData = eventData || {}; var self = this, bubbles = self.bubbles, currentTarget = self.currentTarget, parents, parentsLen, type = self.type, defaultFn = self.defaultFn, i, customEventObject = eventData, gRet, ret; eventData.type = type; if (!customEventObject.isEventObject) { customEventObject = new CustomEventObject(customEventObject); } customEventObject.target = customEventObject.target || currentTarget; customEventObject.currentTarget = currentTarget; ret = self.notify(customEventObject); if (gRet !== false && ret !== undefined) { gRet = ret; } if (bubbles && !customEventObject.isPropagationStopped()) { parents = currentTarget.getTargets(); parentsLen = parents && parents.length || 0; for (i = 0; i < parentsLen && !customEventObject.isPropagationStopped(); i++) { ret = parents[i].fire(type, customEventObject); if (gRet !== false && ret !== undefined) { gRet = ret; } } } if (defaultFn && !customEventObject.isDefaultPrevented()) { var target = customEventObject.target, lowestCustomEventObservable = target.getEventListeners(customEventObject.type); if (!self.defaultTargetOnly && (!lowestCustomEventObservable || !lowestCustomEventObservable.defaultTargetOnly) || currentTarget === target) { gRet = defaultFn.call(currentTarget, customEventObject); } } return gRet; }, notify: function (event) { var observers = [].concat(this.observers), ret, gRet, len = observers.length, i; for (i = 0; i < len && !event.isImmediatePropagationStopped(); i++) { ret = observers[i].notify(event, this); if (gRet !== false && ret !== undefined) { gRet = ret; } } return gRet; }, detach: function (cfg) { var groupsRe, self = this, fn = cfg.fn, context = cfg.context, currentTarget = self.currentTarget, observers = self.observers, groups = cfg.groups; if (!observers.length) { return; } if (groups) { groupsRe = Utils.getGroupsRe(groups); } var i, j, t, observer, observerContext, len = observers.length; if (fn || groupsRe) { context = context || currentTarget; for (i = 0, j = 0, t = []; i < len; ++i) { observer = observers[i]; var observerConfig = observer.config; observerContext = observerConfig.context || currentTarget; if (context !== observerContext || fn && fn !== observerConfig.fn || groupsRe && !observerConfig.groups.match(groupsRe)) { t[j++] = observer; } } self.observers = t; } else { self.reset(); } } }); exports = CustomEventObservable; return exports; }(); eventCustomTarget = function (exports) { exports = {}; var BaseEvent = modulexEventBase; var CustomEventObservable = eventCustomObservable; var util = modulexUtil; var Utils = BaseEvent.Utils, splitAndRun = Utils.splitAndRun, KS_BUBBLE_TARGETS = '__~ks_bubble_targets'; var KS_CUSTOM_EVENTS = '__~ks_custom_events'; function getCustomEventObservable(self, type) { var customEvent = self.getEventListeners(type); if (!customEvent) { customEvent = self.getEventListeners()[type] = new CustomEventObservable({ currentTarget: self, type: type }); } return customEvent; } exports = { isTarget: 1, fire: function (type, eventData) { var self = this, ret, targets = self.getTargets(), hasTargets = targets && targets.length; if (type.isEventObject) { eventData = type; type = type.type; } eventData = eventData || {}; splitAndRun(type, function (type) { var r2, customEventObservable; Utils.fillGroupsForEvent(type, eventData); type = eventData.type; customEventObservable = self.getEventListeners(type); if (!customEventObservable && !hasTargets) { return; } if (customEventObservable) { if (!customEventObservable.hasObserver() && !customEventObservable.defaultFn) { if (customEventObservable.bubbles && !hasTargets || !customEventObservable.bubbles) { return; } } } else { customEventObservable = new CustomEventObservable({ currentTarget: self, type: type }); } r2 = customEventObservable.fire(eventData); if (ret !== false && r2 !== undefined) { ret = r2; } }); return ret; }, publish: function (type, cfg) { var customEventObservable, self = this; splitAndRun(type, function (t) { customEventObservable = getCustomEventObservable(self, t); util.mix(customEventObservable, cfg); }); return self; }, addTarget: function (anotherTarget) { var self = this, targets = self.getTargets(); if (!util.inArray(anotherTarget, targets)) { targets.push(anotherTarget); } return self; }, removeTarget: function (anotherTarget) { var self = this, targets = self.getTargets(), index = util.indexOf(anotherTarget, targets); if (index !== -1) { targets.splice(index, 1); } return self; }, getTargets: function () { return this[KS_BUBBLE_TARGETS] || (this[KS_BUBBLE_TARGETS] = []); }, getEventListeners: function (type) { var observables = this[KS_CUSTOM_EVENTS] || (this[KS_CUSTOM_EVENTS] = {}); return type ? observables[type] : observables; }, on: function (type, fn, context) { var self = this; Utils.batchForType(function (type, fn, context) { var cfg = Utils.normalizeParam(type, fn, context); type = cfg.type; var customEvent = getCustomEventObservable(self, type); customEvent.on(cfg); }, 0, type, fn, context); return self; }, detach: function (type, fn, context) { var self = this; Utils.batchForType(function (type, fn, context) { var cfg = Utils.normalizeParam(type, fn, context); type = cfg.type; if (type) { var customEvent = self.getEventListeners(type); if (customEvent) { customEvent.detach(cfg); } } else { util.each(self.getEventListeners(), function (customEvent) { customEvent.detach(cfg); }); } }, 0, type, fn, context); return self; } }; return exports; }(); eventCustom = function (exports) { exports = {}; var Target = eventCustomTarget; var util = modulexUtil; exports = { version: '1.0.0', Target: Target, Object: eventCustomObject, global: util.mix({}, Target) }; return exports; }(); module.exports = eventCustom; });
"use strict"; const mods = [ "shellfish/low", "shellfish/mid", "shellfish/high", "shell/ui", "shell/files" ]; require(mods, function (low, mid, high, ui, files) { function openPage() { var page = high.element(mid.Page); page .onClosed(page.discard) .onSwipeBack(function () { page.pop_(); }) .header( high.element(mid.PageHeader).title("Administration") .left( high.element(mid.Button).icon("arrow_back") .onClicked(function () { page.pop_(); }) ) ) .add( high.element(mid.ListView) .add( high.element(mid.ListItem) .icon("/::res/shell/icons/server.png") .title("Server") .onClicked(function () { openServerPage(); }) ) .add( high.element(mid.ListItem) .icon("/::res/shell/icons/face.png") .title("Users") .onClicked(function () { openUsersPage(); }) ) .add( high.element(mid.ListItem) .icon("/::res/shell/file-icons/text.png") .title("Statistics") .onClicked(function () { ui.showError("Statistics are not yet available."); }) ) ); page.push_(); } function openServerPage() { var listenAddress = high.binding("0.0.0.0"); var port = high.binding(8000); var useSsl = high.binding(false); var contentRoot = high.binding("/"); var dlg = high.element(mid.Dialog); dlg .onClosed(dlg.discard) .title("Server Settings") .button( high.element(mid.Button).text("Save and Restart") .onClicked(function () { var config = { "listen": dlg.find("listen").get().text, "port": Number.parseInt(dlg.find("port").get().text), "use_ssl": dlg.find("ssl").get().checked, "root": dlg.find("root").get().text }; console.log(JSON.stringify(config)); configureServer(config); dlg.close_(); }) ) .button( high.element(mid.Button).text("Cancel") .onClicked(function () { dlg.close_(); }) ) .add( high.element(mid.Labeled).text("Listen Address:") .add( high.element(mid.TextInput).id("listen").text(listenAddress).focus(true) ) ) .add( high.element(mid.Labeled).text("Port:") .add( high.element(mid.TextInput).id("port") .text(high.predicate([port], function () { return "" + port.value(); })) ) ) .add( high.element(mid.Labeled).text("Use SSL:") .add( high.element(mid.Switch).id("ssl").checked(useSsl) ) ) .add( high.element(mid.Labeled).text("Content Root:") .add( high.element(mid.TextInput).id("root").text(contentRoot) ) ) dlg.show_(); var busyIndicator = high.element(mid.BusyPopup).text("Loading"); busyIndicator.show_(); $.ajax({ type: "GET", url: "/::admin/server", dataType: "json", beforeSend: function (xhr) { xhr.overrideMimeType("application/json"); } }) .done(function (data, status, xhr) { listenAddress.assign(data.listen); port.assign(data.port); useSsl.assign(data.use_ssl); contentRoot.assign(data.root); }) .fail(function (xhr, status, err) { ui.showError("Could not load server configuration: " + err); }) .always(function () { busyIndicator.hide_(); }); } function openUsersPage() { var page = high.element(mid.Page); page .onClosed(page.discard) .onSwipeBack(function () { page.pop_(); }) .header( high.element(mid.PageHeader).title("Users") .left( high.element(mid.Button).icon("arrow_back") .onClicked(function () { page.pop_(); }) ) .right( high.element(mid.Button).icon("person_add") .onClicked(function () { showCreateUserDialog(); }) ) ) .add( high.element(mid.ListView).id("listview") ); page.push_(); var busyIndicator = high.element(mid.BusyPopup).text("Loading"); busyIndicator.show_(); $.ajax({ type: "GET", url: "/::admin/users", dataType: "json", beforeSend: function (xhr) { xhr.overrideMimeType("application/json"); } }) .done(function (data, status, xhr) { data.users.forEach(function (item) { var name = item.name; page.find("listview") .add( high.element(mid.ListItem) .icon("/::res/shell/icons/face.png") .title(item.name) .subtitle(item.home + " (" + item.permissions.join(" ") + ")") .action(["sh-icon-delete", function () { ui.showQuestion("Delete User", "Delete user " + name + "?", function () { deleteUser(name); }, function () { }); }]) ); }); }) .fail(function (xhr, status, err) { ui.showError("Failed to retrieve users: " + err); }) .always(function () { busyIndicator.hide_(); }); } function showCreateUserDialog() { var dlg = high.element(mid.Dialog); dlg .onClosed(dlg.discard) .title("Create User") .add( high.element(mid.Label).text("Create a new user.") ) .add( high.element(mid.Labeled).text("Name:") .add( high.element(mid.TextInput).id("name").text("user").focus(true) ) ) .add( high.element(mid.Labeled).text("Password:") .add( high.element(mid.TextInput).id("password") ) ) .add( high.element(mid.Labeled).text("Home:") .add( high.element(mid.TextInput).id("home").text(files.currentUri()) ) ) .add( high.element(mid.Labeled).text("Create") .add( high.element(mid.Switch).id("mayCreate").checked(true) ) ) .add( high.element(mid.Labeled).text("Delete") .add( high.element(mid.Switch).id("mayDelete").checked(true) ) ) .add( high.element(mid.Labeled).text("Modify") .add( high.element(mid.Switch).id("mayModify").checked(true) ) ) .add( high.element(mid.Labeled).text("Share") .add( high.element(mid.Switch).id("mayShare").checked(false) ) ) .add( high.element(mid.Labeled).text("Administrator") .add( high.element(mid.Switch).id("mayAdmin").checked(false) ) ) .button( high.element(mid.Button).text("Create").isDefault(true) .action(function () { var permissions = []; if (dlg.find("mayCreate").get().checked) permissions.push("CREATE"); if (dlg.find("mayDelete").get().checked) permissions.push("DELETE"); if (dlg.find("mayModify").get().checked) permissions.push("MODIFY"); if (dlg.find("mayShare").get().checked) permissions.push("SHARE"); if (dlg.find("mayAdmin").get().checked) permissions.push("ADMIN"); createUser(dlg.find("name").get().text, dlg.find("password").get().text, dlg.find("home").get().text, permissions); dlg.close_(); }) ) .button( high.element(mid.Button).text("Cancel") .action(function () { dlg.close_(); }) ); dlg.show_(); } function configureServer(config) { var busyIndicator = high.element(mid.BusyPopup).text("Saving"); busyIndicator.show_(); $.ajax({ type: "POST", url: "/::admin/configure-server", data: JSON.stringify(config) }) .done(function (data, status, xhr) { window.location.reload(); }) .fail(function (xhr, status, err) { ui.showError("Could not configure server: " + err); }) .always(function () { busyIndicator.hide_(); }) } function createUser(name, password, home, permissions) { $.ajax({ type: "POST", url: "/::admin/create-user", beforeSend: function(xhr) { xhr.setRequestHeader("x-pilvini-user", name); xhr.setRequestHeader("x-pilvini-password", password); xhr.setRequestHeader("x-pilvini-home", home); xhr.setRequestHeader("x-pilvini-permissions", permissions.join(" ")); }, }) .done(function (data, status, xhr) { low.pagePop(); openUsersPage(); }) .fail(function (xhr, status, err) { ui.showError("Could not create user: " + err); }); } function deleteUser(name) { $.ajax({ type: "POST", url: "/::admin/delete-user", beforeSend: function(xhr) { xhr.setRequestHeader("x-pilvini-user", name); }, }) .done(function (data, status, xhr) { low.pagePop(); openUsersPage(); }) .fail(function (xhr, status, err) { ui.showError("Could not delete user: " + err); }); } files.actionsMenu().find("tools-menu") .add( high.element(mid.MenuItem).text("Administration") .visible(high.predicate([files.properties().permissions], function () { return files.properties().permissions.value().indexOf("ADMIN") !== -1; })) .onClicked(openPage) ); /* .add( high.element(mid.MenuItem).text("User Agent") .visible(high.predicate([files.properties().permissions], function () { return files.properties().permissions.value().indexOf("ADMIN") !== -1; })) .onClicked(function () { var dlg = high.element(mid.Dialog).title("User Agent") .add( high.element(mid.Label).text(navigator.userAgent) ) .button( high.element(mid.Button).text("Ok") .action(function () { dlg.close_(); }) ); dlg.show_(); }) ) */ });
var config = require('../config').proc, gulp = require('gulp'); gulp.task('watch', ['build'], function () { gulp.watch('src/images/**/*', ['images']); gulp.watch(['src/css/**/*.css', 'src/**/*.pug'], ['pug']); });
//jshint strict: false module.exports = function(config) { config.set({ basePath: './app', files: [ 'bower_components/angular/angular.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/angular-local-storage/dist/angular-local-storage.js', '**/*.module.js', '*!(.module|.spec).js', '!(bower_components)/**/*!(.module|.spec).js', '**/*.spec.js' ], autoWatch: true, frameworks: ['jasmine'], browsers: ['Chrome'], plugins: [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter' ], junitReporter: { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
(function () { 'use strict'; var get = Ember.get, set = Ember.set, getConverter = Frzn.getConverter, relationships = Frzn.relationships; var DeferredMixin = Ember.Mixin.create({ /** Add handlers to be called when the Deferred object is resolved or rejected. @method then @param {Function} resolve a callback function to be called when done @param {Function} reject a callback function to be called when failed */ then: function (resolve, reject, label) { var deferred, promise, entity; entity = this; deferred = get(this, '_deferred'); promise = deferred.promise; function fulfillmentHandler(fulfillment) { if (fulfillment === promise) { return resolve(entity); } else { return resolve(fulfillment); } } return promise.then(resolve && fulfillmentHandler, reject, label); }, /** Resolve a Deferred object and call any `doneCallbacks` with the given args. @method resolve */ resolve: function (value) { var deferred, promise; deferred = get(this, '_deferred'); promise = deferred.promise; if (value === this) { deferred.resolve(promise); } else { deferred.resolve(value); } }, /** Reject a Deferred object and call any `failCallbacks` with the given args. @method reject */ reject: function (value) { get(this, '_deferred').reject(value); }, _deferred: Ember.computed(function () { return Ember.RSVP.defer('Ember: DeferredMixin - ' + this); }) }); Frzn.DeferredMixin = DeferredMixin; var setupRelationship = function (model, name, options) { //For relationships we create a wrapper object using Ember proxies if (typeof options.destination === 'string') { var dst = get(options.destination); if (!dst) { var s = options.destination.split('.'); if (s.length) { dst = Ember.Namespace.byName(s[0]).get(s.slice(1).join('.')); } } options.destination = dst; } Ember.assert('You must provide a valid model class for field ' + name, options.destination !== null && options.destination !== undefined); var rel = relationships[options.relationshipType].create({ type: options.relationshipType, options: options }); var data = model._data; var rels = model._relationships; set(rels, name, rel); set(data, name, undefined); }; /** * Initialize a model field. This function tries to understand what kind of attribute should be * instantiated, along with converters and relationships. * * @param model {Frzn.Model} - the model the field applies to * @param name {string} - the field name * @param options {object=} - options describing the field */ var initField = function (model, name, options) { Ember.assert('Field name must not be null', name !== null && name !== undefined && name !== ''); if (get(model, '_data').hasOwnProperty(name) === false) { options = options || {}; if (options.isRelationship) { setupRelationship(model, name, options); } else { set(model, '_data.' + name, options.defaultValue); } var properties = model._properties; if (-1 === properties.indexOf(name)) {//do not redefine properties.push(name); } } }; var getValue = function (model, key) { var meta = model.constructor.metaForProperty(key); //prepare for reading value: get _data object var data = get(model, '_data'); if (meta.options.isRelationship) { //we are dealing with a relationship, so get its definition first var rel = model._relationships[key]; //the real value is the content of the relationship proxy object if (meta.options.embedded === false && meta.options.fetch === 'eager') { return rel.fetch(); } else { return get(rel, 'content'); } } else { //a plain field was requested, get the value from the _data object return Ember.getWithDefault(data, key, meta.options.defaultValue); } }; var setValue = function (model, key, value) { var meta = model.constructor.metaForProperty(key); var converter = getConverter(meta.type); value = converter.convert(value, meta.options); //prepare object: get _data and _backup var data = model._data; var backup = model._backup; //the old value is the one already present in _data object var oldValue = get(data, key); if (meta.options.isRelationship) { //we are dealing with a relationship, so get its definition first var rel = model._relationships[key]; //old value is the content of the relationship object oldValue = get(rel, 'content'); //set the parent object in the content if (value) { set(value, '_parent', model); } //update the value of the relationship set(rel, 'content', value); rel.resolve(); } else { //update the value of the field set(data, key, value); } //save the old value in the backup object if needed if (!backup[key]) { backup[key] = oldValue; } //mark dirty the field if necessary if (oldValue !== value) { markDirty(model, key); } return value; }; var attr = function (type, options) { type = type || 'string'; options = options || {}; return function (key, value) { initField(this, key, options); if (arguments.length > 1) { //setter value = setValue(this, key, value); } else { //getter value = getValue(this, key); } return value; }.property('_data').meta({type: type, options: options}); }; window.Frzn.reopenClass({ /** * Utility function to define a model attribute * @param type The type of attribute. Default to 'string' * @returns a computed property for the given attribute * @param options An hash describing the attribute. Accepted values are: * defaultValue: a default value for the field when it is not defined (not valid for relationships) */ attr: attr }); var saveState = function (model) { var dirtyAttrs = get(model, '_dirtyAttributes'); for (var i = 0; i < dirtyAttrs.length; i++) { var p = dirtyAttrs[i]; if (model.constructor.metaForProperty(p).options.isRelationship) { model.getRel(p).commit(); } } set(model, '_dirtyAttributes', []); set(model, '_backup', {}); return model; }; var discardChanges = function (model) { var backup = model.get('_backup'); set(model, '_backup', {}); var dirtyAttrs = get(model, '_dirtyAttributes'); Ember.setProperties(model, Ember.getProperties(backup, dirtyAttrs)); var relationships = model._relationships; for (var name in relationships) { if (relationships.hasOwnProperty(name)) { model.getRel(name).discard(); } } model._dirtyAttributes = []; return model; }; var markDirty = function (model, field) { var dirtyAttributes = model._dirtyAttributes; if (-1 === dirtyAttributes.indexOf(field)) { dirtyAttributes.push(field); } return model; }; var guid = function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }; Frzn.Model = Ember.Object.extend(DeferredMixin, Ember.Evented, { isAjax: false, isLoaded: false, isSaved: false, isDeleted: false, url: null, errors: null, clientId: null, init: function () { this._super(); this.clientId = guid(); this._dirtyAttributes = []; this._backup = {}; }, getId: function () { return this.get(this.constructor.idProperty); }, getClientId: function () { return this.clientId; }, getRel: function (rel) { return this.get('_relationships.' + rel); }, discard: function () { return discardChanges(this); }, isDirty: function (attr) { var dirtyAttributes = this.get('_dirtyAttributes'); if (attr !== undefined) { return !Ember.isEmpty(dirtyAttributes) && (dirtyAttributesindexOf(attr) !== -1); } else { var dirty = false; var callback = function (previousValue, item) { return previousValue || item.isDirty(); }; for (var relName in this._relationships) { if (this._relationships.hasOwnProperty(relName)) { var rel = this._relationships[relName]; if (rel.get('type') === 'hasOne' || rel.get('type') === 'belongsTo') { dirty = dirty || rel.get('content').isDirty(); } else if (rel.get('type') === 'hasMany') { dirty = dirty || rel.get('content').reduce(callback, false); } } } return dirty || !Ember.isEmpty(dirtyAttributes); } }, commit: function () { return saveState(this); }, toPlainObject: function () { var properties = this._properties; var rel = this._relationships; var keep = []; var related = {}; for (var i = 0; i < properties.length; i++) { var meta = this.constructor.metaForProperty(properties[i]); if (meta.options.isRelationship) { rel = this.getRel(properties[i]); related[properties[i]] = rel.toPlainObject(); } else { keep.push(properties[i]); } } var base = this.getProperties(keep); return Ember.merge(base, related); }, toJSON: function () { return JSON.stringify(this.toPlainObject()); }, load: function (data) { this.setProperties(data); this.commit(); return this; }, save: function () { if (this.getId()) { return this.update(); } this.resetPromise(); return this.constructor.adapter.createRecord(this.constructor, this); }, update: function () { this.resetPromise(); return this.constructor.adapter.updateRecord(this.constructor, this); }, remove: function () { this.resetPromise(); return this.constructor.adapter.deleteRecord(this.constructor, this); }, reload: function () { this.resetPromise(); return this.constructor.adapter.reloadRecord(this.constructor, this); }, fetch: function () { return this.reload(); }, resetPromise: function () { this.set('_deferred', Ember.RSVP.defer()); return this; } }); Frzn.Model.reopenClass({ idProperty: 'id', rootProperty: null, rootCollectionProperty: null, create: function () { var C = this; var props = { _backup: {}, _data: {}, _dirtyAttributes: [], _properties: [], _relationships: {}, _validators: {} }; if (arguments.length > 0) { Ember.merge(props, arguments[0]); } this._initProperties([props]); var instance = new C(); instance.resolve(instance); return instance; }, _create: Ember.Object.create, getName: function () { var name = this + ''; if (name && name.lastIndexOf('.') !== -1) { name = name.substr(name.lastIndexOf('.') + 1); } return name; }, find: function (id) { Ember.assert('You must provide a valid id when searching for ' + this, (id !== undefined)); var properties = {}; properties[this.idProperty] = id; var record = this.create(properties); record = this.adapter.getFromStore(record) || record; record.resetPromise(); return this.adapter.find(this, record, id); }, findAll: function () { var records = Frzn.RecordArray.create({ type: this }); return this.adapter.findAll(this, records); }, findQuery: function (params) { var records = Frzn.RecordArray.create({ type: this }); return this.adapter.findQuery(this, records, params); }, findIds: function () { var records = Frzn.RecordArray.create({ type: this }); var ids = Array.prototype.slice.apply(arguments); return this.adapter.findIds(this, records, ids); } }); window.Frzn = Frzn; })();
var util = require('util'), bleno = require('bleno'); var BlenoCharacteristic = bleno.Characteristic; var BlenoDescriptor = bleno.Descriptor; function ManufacturerNameCharacteristic(manufacturer) { ManufacturerNameCharacteristic.super_.call(this, { uuid: '2a29', properties: ['read'], value: new Buffer(manufacturer), descriptors: [ new BlenoDescriptor({ uuid: '2901', value: 'Manufacturer Name String' }) ] }); } util.inherits(ManufacturerNameCharacteristic, BlenoCharacteristic); module.exports = ManufacturerNameCharacteristic;
const Route = require('lib/router/route') module.exports = new Route({ method: 'del', path: '/', handler: async function (ctx) { const token = ctx.state.token if (!token) { return ctx.throw(401) } if (ctx.state.authMethod !== 'Bearer') { return ctx.throw(403) } token.isDeleted = true await token.save() ctx.body = { data: 'OK' } } })
(function() { 'use strict'; var root = this; var Px = (function () { function Px(pxString) { this._ctor(pxString); } function _arrayOfZeroes(l) { var a = []; while (l--) { a[l] = 0; } return a; } Px.prototype = { keyword: function(k) { if (! _.include(this.keywords(), k)) { throw ('\'' + k + '\' is not a valid KEYWORD'); } if (this.metadata[k].TABLE) { return this.metadata[k].TABLE; } else { return this.metadata[k]; } }, title: function() { return this.keyword('TITLE'); }, keywords: function() { return _.keys(this.metadata); }, variables: function() { return _.flatten([this.keyword('STUB'), this.keyword('HEADING')]); }, variable: function(v) { var vars = this.variables(); if (typeof(v) === 'number') { return vars[v]; } else if (typeof(v) === 'string') { return _.indexOf(vars, v); } else { return undefined; } }, values: function(v) { var varName = typeof(v) === 'number' ? this.variable(v) : this.variables()[this.variable(v)]; return this.keyword('VALUES')[varName]; }, codes: function(v) { var varName = typeof(v) === 'number' ? this.variable(v) : this.variables()[this.variable(v)]; if (!this.metadata.CODES || !this.keyword('CODES')[varName]) { return this.keyword('VALUES')[varName]; } else { return this.keyword('CODES')[varName]; } }, valCounts: function() { var counts = []; _.each(this.variables(), function(e,i) { counts.push(_.size(this.values(i))); }, this); return counts; }, value: function(code, variable) { var idx = _.indexOf(this.codes(variable), code); return this.values(variable)[idx]; }, code: function(val, variable) { var idx = _.indexOf(this.values(variable), val); return this.codes(variable)[idx]; }, datum: function(s) { // TODO: check for correct array length // TODO: check that each index is in range var counts = this.valCounts(); var index = 0; for (var i = 0, len = s.length - 1; i < len; i++) { index += s[i] * ( _.reduce( counts.slice(i+1), function(a, b) { return a * b; }) ); } index += _.last(s); // if true is passed as 2nd arg index rather than value is returned if (arguments[1] === true) { return index; } else { return this.data[index].replace(/"|'/g, ''); } }, dataCol: function(s) { // TODO: check for correct array length (s) and check for 1 and only 1 wildcard var counts = this.valCounts(); var dataCol = []; var grpIdx = _.indexOf(s, '*'); var a = s.slice(0); //copy array so function doesn't alter it for (var i = 0; i < counts[grpIdx]; i++) { a[grpIdx] = i; // if true is passed as 2nd arg indices rather than values are returned dataCol.push(this.datum(a, arguments[1])); } return dataCol; }, dataDict: function(s) { // TODO allow code or val to be dict keys via optional 2nd arg var datadict = {}, grpIdx = _.indexOf(s, '*'), codes = this.codes(grpIdx), dataCol = this.dataCol(s); _.each(dataCol, function(d, i) { datadict[codes[i]] = d; }); return datadict; }, datatable: function(s) { // This is fairly useless remove 2-dimension limit // TODO: check for correct array length (s) and check for 2 and only 2 wildcard // ALSO: allow either wildcard be the grouping variable (the STUB) var counts = this.valCounts(); var grpIdxs = []; _.each(s, function(el, i) { if (el === '*') { grpIdxs.push(i); } }); var grpIdx = grpIdxs[0]; var chgIdx = _.last(grpIdxs); var datatable = []; for (var i = 0; i < counts[chgIdx]; i++) { s[grpIdx] = '*'; s[chgIdx] = i; datatable.push(this.dataCol(s, arguments[1])); } return datatable; }, entries: function() { // TODO -- check for data array size and if too big either (a) split the job, // (b) throw an exception and suggest a truncate or subset operation first // TODO -- allow keys to be code or values via optional argument var counts = this.valCounts(), vars = this.variables(), valIdx = _arrayOfZeroes(counts.length), last = valIdx.length - 1, multipliers = [], dataset = []; for (var i = 0, l = counts.length; i < l - 1; i++) { // the multiplier for each variable is the product of the numbers of values // for each variable occuring after it in the variables array multipliers[i] = _.reduce(counts.slice(i+1), function(a, b) { return a * b; }); } _.each(this.data, function(d, i) { // create datum object and push onto dataset var datum = {num: d}; for (var di = 0, dl = vars.length; di < dl; di++) { datum[vars[di]] = this.values(di)[valIdx[di]]; } dataset.push(datum); // increment indices: for (var mi = 0, ml = multipliers.length; mi < ml; mi++) { if ( (i + 1) % (multipliers[mi]) === 0 ) { valIdx[mi] = valIdx[mi] === counts[mi] - 1 ? 0 : valIdx[mi] + 1; } } valIdx[last] = valIdx[last] === counts[last] - 1 ? 0 : valIdx[last] + 1; }, this); return dataset; }, // remove values and associated data from this object truncate: function(s) { //TODO: validate array length //TODO: return unwanted subset as new Px object var counts = this.valCounts(), multipliers = []; _.each(s, function(d, i) { if (d[0] === '*') { s[i] = _.range(0, counts[i] - 1); } }); for (var i = 0, l = counts.length; i < l - 1; i++) { multipliers[i] = _.reduce(counts.slice(i+1), function(a, b) { return a * b; }); } multipliers.push(1); for (var j = 0, k = s.length; j < k; j++) { // drop the values this.metadata.VALUES[this.variables()[j]] = _.filter(this.metadata.VALUES[this.variables()[j]], function(e, m) { return _.indexOf(s[j], m) !== -1; }); } var keepIdxs = []; var pattern = function pattern(c,m,w,p) { if (c.length > 1) { p = typeof p !== 'undefined' ? p : 1; var count = c.pop(), multiple = m.pop(), want = w.pop(); var patt = _.flatten(_.map(_.range(0, count), function(d) { return _.include(want, d) ? p : _arrayOfZeroes(multiple); })); pattern(c, m, w, patt); } keepIdxs.push(_.flatten(p)); }; pattern(counts,multipliers,s); keepIdxs = keepIdxs[0]; var indices = []; _.each(s[0], function(d) { var start = d * multipliers[0]; var end = start + multipliers[0]; indices.push(_.filter(_.range(start, end), function(d, i) {return keepIdxs[i] === 1;})); }); indices = _.flatten(indices); this.data = _.filter(this.data, function(d, i) {return _.indexOf(indices, i) !== -1;}); }, // create a new object from a subset of values in this object subset: function(s) { // TODO }, _ctor: function(pxString) { var metadata = {}; var data; var pxSplit = pxString.split(/\nDATA=/); var pxMetadata = pxSplit[0] .replace(/;\s*(\r\n?|\n)/g, ';;') .replace(/;;$/, ';') .replace(/(\r\n?|\n)/g, '') .replace(/""/g, ' ') .split(';;'); var pxData = pxSplit[1]; // parse metadata for (var i = 0, pxLen = pxMetadata.length; i < pxLen; i++) { var keyOptVal = pxMetadata[i] .match(/^(.+?)(?:\((.+?)\))?=(.+)$/); if (!keyOptVal[2]) { keyOptVal[2] = 'TABLE'; } var key = keyOptVal[1]; var vals = keyOptVal[3].replace(/^"|"$/g, '').split(/","/g); var opt = keyOptVal[2].replace(/"/g, ''); if (!metadata[key]) { metadata[key] = {}; } if (key !== 'VALUES') { // ensure that a single VALUES option still gets assigned to an array metadata[key][opt] = vals.length === 1 ? vals[0] : vals; } else { metadata[key][opt] = vals; } } // parse data data = pxData .replace(/(\r\n|\r|\n)/g, '') .replace(/;\s*/, '') .split(/\s+/); // Fix for bad files with no HEADING if (!metadata.HEADING) { metadata.HEADING = {TABLE: []}; } // Assign instance data this.metadata = metadata; this.data = data; } }; return Px; }()); var _ = root._; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = Px; } exports.Px = Px; _ = require('underscore'); } else { root.Px = Px; } }.call(this));
// +@typename cracked_com_blog // +@include http://www.cracked.com/blog/* // +@history (0.0.1) Initial Release // +@history (0.0.9) Removed bottom banner on pages // +@history (0.0.12) Updated addPageContent to use $target AntiPagination.add({ name: 'cracked_com_blog', test: function(currentURL){ // Test URL var isCrackedBlogPatt = /https?\:\/\/(?:www\.)?cracked\.com\/blog\//i; var isCrackedBlog = false; isCrackedBlog = isCrackedBlogPatt.test(currentURL); if(isCrackedBlog) isCrackedBlog = ($('.PaginationContent').length > 0); return isCrackedBlog; }, init: function(currentURL, currentPageNumber, maxNumberOfPages){ $content = this.getCurrentPageContent(currentURL, currentPageNumber); this.removeBottomBanner($content); }, getCurrentPageNumber: function(currentURL){ var $PaginationContent = $('.PaginationContent'); var currentNum = $PaginationContent.find('.paginationNumber').first().html(); if(typeof currentNum !== "undefined" && currentNum != '') return parseInt(currentNum); return -1; }, getMaxNumberOfPages: function(currentURL){ var $PaginationContent = $('.PaginationContent'); var maxNum = $PaginationContent.find('.paginationNumber').last().html(); if(typeof maxNum !== "undefined" && maxNum != '') return parseInt(maxNum); return -1; }, getCurrentPageContent: function(currentURL){ if($('.AntiPagination_currentPage').length > 0) return $('.AntiPagination_currentPage'); $('#safePlace .body > section:first').addClass('AntiPagination_currentPage'); return $('#safePlace .body > section:first'); }, addPageContent: function(currentURL, currentPageNumber, contentPageNumber, $target){ var urlHTMLPatt = /((?:_p\d+)?\/)\s*$/gi; var newURL = currentURL.replace(urlHTMLPatt, "_p" + contentPageNumber + "/"); newURL += ' #safePlace .body > section:first > *'; //$(".AntiPagination_p" + contentPageNumber).load(newURL, function(){}); $target.load(newURL, function(){}); }, onContentAdded: function(contentPageNumber, $content){ this.removeBottomBanner($content); $content.find('img[data-img]').each(function(){ $this = $(this); var dataImg = $this.attr('data-img'); $this.attr('src', dataImg).css('display', 'inline'); }); }, onAllPagesAdded: function(){ console.log('onAllPagesAdded!'); }, removeBottomBanner: function($content){ $lastP = $content.children('p').last(); if($lastP.find('a[target="_blank"] img').length > 0) $lastP.remove(); } });
import curry from '../Func/curry' import fix from '../Func/fix' // + find :: (a -> Boolean) -> [a] -> a export default fix((find) => curry((fn, [x, ...xs]) => x ? fn(x) ? x : find(fn, xs) : undefined ))
/** * Object.assign的polyfill * 解决webview等不支持ES6的浏览器兼容性 */ 'use strict'; (function() { if (!Object.assign) { Object.defineProperty(Object, 'assign', { enumerable: false, configurable: true, writable: true, value: function(target) { if (target === undefined || target === null) { throw new TypeError('Cannot convert first argument to object'); } var to = Object(target); for (var i = 1; i < arguments.length; i++) { var nextSource = arguments[i]; if (nextSource === undefined || nextSource === null) { continue; } nextSource = Object(nextSource); var keysArray = Object.keys(Object(nextSource)); for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { var nextKey = keysArray[nextIndex]; var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); if (desc !== undefined && desc.enumerable) { to[nextKey] = nextSource[nextKey]; } } } return to; } }); } })();
/** * * * * * * * * * * * * */ /* Depandances PROVIDE : * ===================== */ stage.provide("deferred"); /* * Depandances REQUIRE : * ===================== */ stage.register("deferred",function(){ var deferred = function(){ this.notificationsCenter = stage.createEventsManager(); this.fifo = stage.structs.createQueue(); this.state = "pending"; }; deferred.prototype.then = function(callBackDone, callbackFail, callBackProgress){ var length = arguments.length; switch (length){ case 1 : this.done( arguments[0] ); break; case 2 : this.done( arguments[0] ); this.fail( arguments[1] ); break; case 3 : this.done( arguments[0] ); this.fail( arguments[1] ); this.progress(arguments[2]) break; default : console.log("default") } return this; }; deferred.prototype.done = function(callback, context){ return this.notificationsCenter.listen(context || this, "onDone", callback) }; deferred.prototype.fail = function(callback, context){ return this.notificationsCenter.listen(context || this, "onFail", callback) }; deferred.prototype.progress = function(callback, context){ return this.notificationsCenter.listen(context || this, "onProgress", callback) }; deferred.prototype.resolve = function(){ if (this.state === "rejected"){ this.fifo.purge(); return false; }else{ this.fifo.dequeue(); var func = this.fifo.peek(); } if ( func ){ Array.prototype.unshift.call(arguments, this); try { this.state = "pending"; var res = func.apply(this, arguments); }catch(e){ this.reject(e); } return res ; }else{ this.state = "resolved"; Array.prototype.unshift.call(arguments, "onDone"); return this.notificationsCenter.fireEvent.apply(this.notificationsCenter, arguments ); } }; deferred.prototype.resolveWith = function(context){ if (this.state === "rejected"){ this.fifo.purge(); return false; }else{ this.fifo.dequeue(); var func = this.fifo.peek(); } if ( func ){ Array.prototype.unshift.call(arguments, this); try { this.state = "pending"; var res = func.apply(this, arguments); }catch(e){ return this.reject(e); } return res; }else{ this.state = "resolved"; Array.prototype.unshift.call(arguments, "onDone"); return this.notificationsCenter.fireWith.apply(this.notificationsCenter , arguments); } }; deferred.prototype.reject = function(){ this.state = "rejected"; Array.prototype.unshift.call(arguments, "onFail"); return this.notificationsCenter.fireEvent.apply(this.notificationsCenter, arguments ); }; deferred.prototype.rejectWith = function(){ this.state = "rejected"; Array.prototype.unshift.call(arguments, "onFail"); return this.notificationsCenter.fireWith.apply(this.notificationsCenter , arguments); }; deferred.prototype.notify = function(){ Array.prototype.unshift.call(arguments, "onProgress"); return this.notificationsCenter.fireEvent.apply(this.notificationsCenter, arguments ); }; deferred.prototype.notifyWith = function(){ Array.prototype.unshift.call(arguments, "onProgress"); return this.notificationsCenter.fireWith.apply(this.notificationsCenter , arguments); }; var when = function(){ var args = Array.prototype.slice.call(arguments); var length = args.length for (var i=0 ; i < length ; i++ ){ this.fifo.enqueue(args[i]); } var func = this.fifo.peek(); if( func ){ try { func.call(this,this); }catch(e){ this.reject(e); } } return this; } return { local:{ Deferred:function(){ return new deferred(); }, when:function(){ if (arguments[0] instanceof deferred ){ var defer = arguments[0]; Array.prototype.shift.call(arguments) }else{ var defer = new deferred(); } return when.apply(defer, arguments); } } } })
/* eslint no-use-before-define:0 */ 'use strict'; var RSVP = require('rsvp'); var Promise = RSVP.Promise; module.exports = PromiseExt; // Utility functions on the native CTOR need some massaging module.exports.hash = function () { return this.resolve(RSVP.hash.apply(null, arguments)); }; module.exports.denodeify = function () { var fn = RSVP.denodeify.apply(null, arguments); var Constructor = this; var newFn = function () { return Constructor.resolve(fn.apply(null, arguments)); }; Object.setPrototypeOf(newFn, arguments[0]); return newFn; }; module.exports.filter = function () { return this.resolve(RSVP.filter.apply(null, arguments)); }; module.exports.map = function () { return this.resolve(RSVP.map.apply(null, arguments)); }; function PromiseExt(resolver, label) { this._superConstructor(resolver, label); } PromiseExt.prototype = Object.create(Promise.prototype); PromiseExt.prototype.constructor = PromiseExt; PromiseExt.prototype._superConstructor = Promise; Object.setPrototypeOf(PromiseExt, Promise); PromiseExt.prototype.returns = function (value) { return this.then(function () { return value; }); }; PromiseExt.prototype.invoke = function (method) { var args = Array.prototype.slice(arguments, 1); return this.then(function (value) { return value[method].apply(value, args); }, undefined, 'invoke: ' + method + ' with: ' + args); }; PromiseExt.prototype.map = function (mapFn) { var Constructor = this.constructor; return this.then(function (values) { return Constructor.map(values, mapFn); }); }; PromiseExt.prototype.filter = function (mapFn) { var Constructor = this.constructor; return this.then(function (values) { return Constructor.filter(values, mapFn); }); };